diff --git a/README.md b/README.md index e8adccd..2103e51 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ There are three ways to run sync: | `cronitor sync --auto` | nothing | yes | **all of them** | - Run plain `cronitor sync` again whenever you add jobs or change a schedule. It shows one summary with each change (for example `L3 Nightly backup: schedule 0 2 * * * → 30 3 * * *`) and asks once. If nothing changed, it asks nothing. -- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed, so `cronitor sync --auto file | crontab -` is safe. If the shell wrapper cannot be installed or the crontab cannot be saved, it prints the original crontab and exits 1. It also monitors every new job, so it is not the way to pick up one schedule change. +- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed. Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. Do not add `--silent` to that command: `--auto --silent` prints no crontab, so the pipe would install an empty one. It also monitors every new job, so it is not the way to pick up one schedule change. - If any crontab fails to apply, in any mode, sync exits 1. - For a monitored job, sync sends only what changed. Names, tags and alert lists set in Cronitor are kept; alert lists change only with `--notification-list` (omitting the flag keeps existing lists; new monitors get Cronitor's default). A `# Name:` comment is updated to the name in Cronitor. - If a monitor was deleted in Cronitor, sync warns and does not create it again. A hand-written `CRONITOR=new-key` line for a monitor that was never created gets the same warning; create the monitor first, or remove the key and let sync add it. diff --git a/cmd/discover.go b/cmd/discover.go index 3212904..6bea780 100644 --- a/cmd/discover.go +++ b/cmd/discover.go @@ -111,9 +111,127 @@ var notificationList string var existingMonitors = ExistingMonitors{} var processingMultipleCrontabs = false var userAbortedSync = false // Set to true when user presses Ctrl+D to abort sync entirely -var syncFile string // Path to YAML/JSON file for bulk monitor import -var syncFormat string // --format: "", "short" or "exec" -var withMonitored bool // --with-monitored: also ask about jobs that are already monitored + +// stdoutIsCrontab is true while `cronitor sync --auto` handles one crontab +// file and will print it on stdout. Verbose logs go to stderr so the pipe +// cannot install log text or a partial crontab. +var stdoutIsCrontab bool + +// reserveStdoutForCrontab reports whether this sync should keep stdout for +// the crontab. Flags are already parsed when it runs (including from +// initConfig, before the config file is logged). +func reserveStdoutForCrontab(args []string) bool { + if runtime.GOOS == "windows" || !isAutoDiscover || isSilent { + return false + } + return len(args) > 0 && !isPathToDirectory(args[0]) +} + +// printOriginalCrontab prints the crontab for a --auto run on one readable +// file. Sync calls it when it fails before a plan exists. A missing or +// unreadable file prints nothing. +func printOriginalCrontab(args []string) { + if !reserveStdoutForCrontab(args) { + return + } + info, err := os.Stat(args[0]) + if err != nil || !info.Mode().IsRegular() { + return + } + b, err := os.ReadFile(args[0]) + if err != nil { + return + } + text := strings.TrimSpace(string(b)) + if text == "" { + return + } + fmt.Println(text) +} + +// redactAPIKeyArgs hides API and ping keys passed on the command line so +// the dry-run reminder does not print them. Forms: -k X, -kX, -k=X, +// --api-key X, --api-key=X, a short cluster such as -vkX or -vk=X, and the +// same forms for -p / --ping-api-key (placeholder ). +func redactAPIKeyArgs(args []string) []string { + out := make([]string, 0, len(args)) + for i := 0; i < len(args); i++ { + a := args[i] + if i == 0 { + out = append(out, a) + continue + } + redacted, next := redactAPIKeyToken(a) + out = append(out, redacted) + if next != "" && i+1 < len(args) { + i++ + out = append(out, next) + } + } + return out +} + +// shortFlagTakesValue reports shorthands on sync whose value consumes the +// rest of a combined short-flag cluster. k and p are handled by the caller. +func shortFlagTakesValue(letter byte) bool { + switch letter { + case 'c', 'e', 'l', 'n', 'u': + return true + default: + return false + } +} + +// redactAPIKeyToken redacts one argv element. next is the placeholder for +// the following argument, or "" when this token already holds the value. +func redactAPIKeyToken(token string) (string, string) { + switch { + case token == "--api-key" || token == "-k": + return token, "" + case token == "--ping-api-key" || token == "-p": + return token, "" + case strings.HasPrefix(token, "--api-key="): + return "--api-key=", "" + case strings.HasPrefix(token, "--ping-api-key="): + return "--ping-api-key=", "" + case strings.HasPrefix(token, "-k="): + return "-k=", "" + case strings.HasPrefix(token, "-p="): + return "-p=", "" + } + if !strings.HasPrefix(token, "-") || strings.HasPrefix(token, "--") || len(token) < 2 { + return token, "" + } + body := token[1:] + for i := 0; i < len(body); i++ { + placeholder := "" + switch body[i] { + case 'k': + placeholder = "" + case 'p': + placeholder = "" + default: + if shortFlagTakesValue(body[i]) { + return token, "" + } + continue + } + if i+1 >= len(body) { + return token, placeholder + } + // Keep the '=' in a cluster such as -vk=X. + end := i + 2 + if body[i+1] == '=' { + end++ + } + return token[:end] + placeholder, "" + } + return token, "" +} + +var syncFile string // Path to YAML/JSON file for bulk monitor import +var syncFormat string // --format: "", "short" or "exec" +var withMonitored bool // --with-monitored: also ask about jobs that are already monitored // To deprecate this feature we are hijacking this flag that will trigger removal of auto-discover lines from existing user's crontabs. var noAutoDiscover = true @@ -150,8 +268,13 @@ There are three ways to run sync: $ cronitor sync --auto > Asks nothing. Monitors every new job, sends schedule and timezone changes, and writes the crontab - > Prints the crontab to stdout even when nothing changed, so pipelines such as - cronitor sync --auto file | crontab - never install an empty crontab + > Prints the crontab to stdout even when nothing changed. Once sync has read the file, + a failure prints the original crontab and exits 1. A direct "| crontab -" pipe can + still install an empty crontab if sync fails before it can read the file, for example + when the file is missing or a flag is invalid. Capture the output first: + out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab - + Do not add --silent to that command: --auto --silent prints no crontab, + so the pipe would install an empty one. > Use it to automate sync, not to pick up one schedule change: it also monitors every new job For a job that is already monitored, sync sends only what changed. Names, tags and alert lists set @@ -199,11 +322,16 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read processingMultipleCrontabs = false userAbortedSync = false jobsNeedingSudo = 0 + stdoutIsCrontab = false if len(viper.GetString(varApiKey)) < 10 { + // Fail before a plan exists. When this is --auto on one readable + // file, stdout still gets that crontab so a pipe can reinstall it. + printOriginalCrontab(args) fatal(discoverMissingAPIKeyGuidance(), 1) } if _, err := parseSyncFormat(syncFormat); err != nil { + printOriginalCrontab(args) fatal(err.Error(), 1) } if runtime.GOOS == "windows" && syncFormat != "" { @@ -216,6 +344,14 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read return } + // initConfig may already have set this so the config log stays off + // stdout. Set it again from the args Run received, and clear it + // when the command returns. + if reserveStdoutForCrontab(args) { + stdoutIsCrontab = true + defer func() { stdoutIsCrontab = false }() + } + var username string if u, err := user.Current(); err == nil { username = u.Username @@ -290,13 +426,18 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read printSuccessText("View your dashboard https://cronitor.io/app/dashboard", false) } if dryRun { - saveCommand := strings.Join(os.Args, " ") + saveCommand := strings.Join(redactAPIKeyArgs(os.Args), " ") saveCommand = strings.Replace(saveCommand, " --dry-run", "", -1) if importedCrontabs > 0 { msg := "Reminder: This is a DRY-RUN. Integration is not complete." next := "To complete integration, run:" - cmd := fmt.Sprintf(" %s --auto --silent", saveCommand) + // Same command without --dry-run. That is `cronitor sync` + // after an interactive dry run, or `cronitor sync --auto` + // when --auto was already set. --auto --silent is neither: + // --auto would monitor every new job, and with --silent it + // also skips printing the crontab. + cmd := " " + saveCommand if isAutoDiscover || isSilent { fmt.Fprintln(os.Stderr, msg) fmt.Fprintln(os.Stderr, next) @@ -314,6 +455,18 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read // crontabWritable reports whether sync can write a crontab. Tests replace it. var crontabWritable = func(c *lib.Crontab) bool { return c.IsWritable() } +// crontabFileReadable reports whether a file crontab can be opened. A user +// crontab is not a path. Callers use this after Parse fails, to tell an +// unreadable file from an empty one. +func crontabFileReadable(c *lib.Crontab) bool { + f, err := os.Open(c.Filename) + if err != nil { + return false + } + f.Close() + return true +} + // jobsNeedingSudo counts jobs in crontabs this user cannot write. var jobsNeedingSudo int @@ -639,10 +792,25 @@ func finishSync(plans []*crontabPlan) int { // When running --auto mode with a single crontab, you should be able to pipe or redirect crontab // output elsewhere, so print it whether or not anything changed. Print first, then // exit, so a failed apply still writes the original crontab before exitFn. + // applyPlan must return on failure. os.Exit skips this print. + // A missing or unwritable file is the same kind of failure: exit 1, and + // print the original only when there is one to print. applyFailed := false + unusable := false + for _, p := range plans { + if p.unusable { + unusable = true + applyFailed = true + } + } defer func() { if !isSilent && isAutoDiscover && !processingMultipleCrontabs { for _, p := range plans { + // A missing file has no crontab. A blank line would still + // be installed by `... | crontab -`. + if p.unusable && strings.TrimSpace(p.output) == "" { + continue + } fmt.Println(strings.TrimSpace(p.output)) } } @@ -650,6 +818,9 @@ func finishSync(plans []*crontabPlan) int { exitFn(1) } }() + if unusable { + return 0 + } var todo []*crontabPlan for _, p := range plans { if p.hasChanges() { @@ -741,6 +912,7 @@ type crontabPlan struct { aborted bool // the user quit rewrites bool // the crontab text changes even if no monitor does output string // the crontab text --auto prints: as planned, or as written + unusable bool // missing or not writable: do not apply; finishSync exits 1 } type promptChoice int @@ -784,15 +956,30 @@ var askAboutJob = func(line *lib.Line, name string, monitored bool) promptResult } // planCrontab reads a crontab and decides what to do with each job. It -// returns nil when the crontab cannot be used. +// returns nil when a crontab is skipped. One named file that does not exist +// or is not writable is an unusable plan: sync prints the original crontab +// when it has one, and exits 1. func planCrontab(crontab *lib.Crontab) *crontabPlan { if !crontab.Exists() { + // One named file that is not there is a failure. Scanning many + // crontabs still skips a user who has none. + if !processingMultipleCrontabs { + reportError(fmt.Sprintf("%s does not exist", crontab.DisplayName())) + return &crontabPlan{crontab: crontab, unusable: true} + } printWarningText("This crontab does not exist. Skipping.", true) return nil } // This will mostly happen when the crontab is empty if err, _ := crontab.Parse(noAutoDiscover); err != nil { + // A named file that cannot be read is a failure. There is nothing + // to print. An empty crontab is still a skip: installing it changes + // nothing. Scanning many crontabs keeps the old skip. + if !processingMultipleCrontabs && !crontab.IsUserCrontab && !crontabFileReadable(crontab) { + reportError(err.Error()) + return &crontabPlan{crontab: crontab, unusable: true} + } // While scanning, an empty or unreadable system crontab is only logged. if !processingMultipleCrontabs || crontab.IsUserCrontab { printWarningText("This crontab is empty. Skipping.", true) @@ -806,10 +993,13 @@ func planCrontab(crontab *lib.Crontab) *crontabPlan { if !crontabWritable(crontab) { if processingMultipleCrontabs { jobsNeedingSudo += countJobs(crontab) - } else { - printWarningText("This crontab is not writable. Run sync with sudo.", true) + return nil } - return nil + // Readable (Parse succeeded) but not writable. Same as an API, shim + // or save failure: stdout gets the original crontab when this run + // prints one, and the process exits 1. + reportError(fmt.Sprintf("%s is not writable. Run sync with sudo.", crontab.DisplayName())) + return &crontabPlan{crontab: crontab, output: crontab.Original(), unusable: true} } // If a timezone env var is set in the crontab it takes precedence over system tz @@ -1052,7 +1242,14 @@ func applyPlan(plan *crontabPlan) bool { printDoneText("Sending to Cronitor", true) sent, err := getCronitorApi().PutMonitors(monitors) if err != nil { - fatal(err.Error(), 1) + // os.Exit here skips finishSync's deferred print, so + // `cronitor sync --auto file | crontab -` installs an empty + // crontab. Same as a shim or save failure: stdout gets the + // original crontab (not the planned rewrite) and the process + // exits 1. + plan.output = crontab.Original() + reportError(err.Error()) + return false } // New monitors get their code from the response. Existing lines keep // the key they have: it may be a hand-written key, not the code. @@ -1069,8 +1266,8 @@ func applyPlan(plan *crontabPlan) bool { if err := configureShellShim(crontab, false); err != nil { // The file is unchanged. --auto stdout must not print the planned // crontab (SHELL= would point at a wrapper that was never installed). - // Print the original so `... | crontab -` without pipefail reinstalls - // a working crontab instead of an empty one; finishSync then exits 1. + // Print the original so a pipe to crontab reinstalls a working + // crontab instead of an empty one; finishSync then exits 1. plan.output = crontab.Original() if isAutoDiscover || isSilent { fmt.Fprintln(os.Stderr, err.Error()) diff --git a/cmd/root.go b/cmd/root.go index 76a5d43..8a11e68 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -111,12 +111,19 @@ func init() { // initConfig reads in config file and ENV variables if set. func initConfig() { viper.AutomaticEnv() // read in environment variables that match + // ParseFlags has already run. Do this before logging the config path: + // with --verbose that line would otherwise precede the crontab on stdout. + stdoutIsCrontab = reserveStdoutForCrontab(discoverCmd.Flags().Args()) configFile := viper.GetString(varConfig) // If a custom config file is specified by flag or env var, use it. Otherwise use default file. if len(configFile) > 0 { if len(configFile) < 5 || strings.ToLower(configFile[len(configFile)-5:]) != ".json" { - fmt.Println("Error: Config file must be a .json file") + if stdoutIsCrontab { + fmt.Fprintln(os.Stderr, "Error: Config file must be a .json file") + } else { + fmt.Println("Error: Config file must be a .json file") + } } viper.SetConfigFile(configFile) } else { @@ -483,11 +490,24 @@ func log(msg string) { } if verbose { + // sync --auto on one crontab file owns stdout (`... | crontab -`). + // Verbose text there would be installed as the crontab. + if stdoutIsCrontab { + fmt.Fprintln(os.Stderr, msg) + return + } fmt.Println(msg) } } func fatal(msg string, exitCode int) { + reportError(msg) + os.Exit(exitCode) +} + +// reportError writes a redacted error to stderr and the debug log. +// It does not exit, so a caller can still print a crontab on stdout. +func reportError(msg string) { msg = redactSecrets(msg) debugLog := viper.GetString(varLog) if len(debugLog) > 0 { @@ -497,7 +517,6 @@ func fatal(msg string, exitCode int) { } fmt.Fprintln(os.Stderr, msg) - os.Exit(exitCode) } // redactSecrets removes remembered secrets and the configured API / ping keys diff --git a/cmd/shell_shim_sync_test.go b/cmd/shell_shim_sync_test.go index f5d8672..b9894ab 100644 --- a/cmd/shell_shim_sync_test.go +++ b/cmd/shell_shim_sync_test.go @@ -41,6 +41,12 @@ func runSyncArgs(t *testing.T, serverURL, path string, extra ...string) string { isAutoDiscover = false isSilent = false withMonitored = false + stdoutIsCrontab = false + verbose = false + if f := RootCmd.PersistentFlags().Lookup("verbose"); f != nil { + _ = f.Value.Set("false") + f.Changed = false + } _ = discoverCmd.Flags().Set("format", "") _ = discoverCmd.Flags().Set("dry-run", "false") _ = discoverCmd.Flags().Set("no-stdout", "false") @@ -151,6 +157,7 @@ func withSyncFixture(t *testing.T) (serverURL, shimPath string) { lib.BaseURLOverride = oldBase isAutoDiscover = oldAuto isSilent = oldSilent + stdoutIsCrontab = false syncFormat = oldFormat dryRun = oldDry existingMonitors = oldMonitors diff --git a/cmd/sync_rerun_test.go b/cmd/sync_rerun_test.go index fc6a106..a113b7d 100644 --- a/cmd/sync_rerun_test.go +++ b/cmd/sync_rerun_test.go @@ -603,6 +603,110 @@ func TestSyncAutoPrintsOriginalWhenShimInstallFails(t *testing.T) { } } +// An API failure used to os.Exit inside applyPlan, skipping the deferred +// print. `cronitor sync --auto file | crontab -` then installed an empty crontab. +func TestSyncAutoPrintsOriginalWhenAPIFails(t *testing.T) { + withSyncFixture(t) + withNotificationList(t, "") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodGet { + io.WriteString(w, `{"total_monitor_count":0,"page_size":50,"monitors":[]}`) + return + } + http.Error(w, "nope", http.StatusInternalServerError) + })) + t.Cleanup(srv.Close) + body := "0 2 * * * /usr/bin/backup.sh\n" + path := writeCron(t, body) + + var code int + oldExit := exitFn + t.Cleanup(func() { + exitFn = oldExit + verbose = false + if f := RootCmd.PersistentFlags().Lookup("verbose"); f != nil { + _ = f.Value.Set("false") + f.Changed = false + } + }) + exitFn = func(c int) { code = c } + + // A previous test may have viper.Set the config path, which hides --config. + viperUnset(varConfig) + // --verbose must not prefix the crontab. Those logs used to be written + // before os.Exit, so the pipe installed a partial crontab. + stderr := runSyncArgs(t, srv.URL, path, "--auto", "--verbose") + + if code != 1 { + t.Fatalf("exit %d; want 1 after the API call fails", code) + } + if strings.TrimSpace(lastSyncStdout) == "" { + t.Fatal("stdout is empty; the pipe would install an empty crontab") + } + if strings.TrimSpace(lastSyncStdout) != strings.TrimSpace(body) { + t.Fatalf("stdout = %q; want the original crontab", lastSyncStdout) + } + if got := readCron(t, path); got != body { + t.Fatalf("crontab on disk changed:\n%s", got) + } + if strings.TrimSpace(stderr) == "" { + t.Fatal("stderr is empty; the API error was not reported") + } +} + +// A missing or unwritable file used to print nothing and exit 0, so +// `cronitor sync --auto file | crontab -` installed an empty crontab. +func TestSyncAutoExitsWhenCrontabMissingOrUnwritable(t *testing.T) { + withSyncFixture(t) + withNotificationList(t, "") + _, apiURL := newRerunAPI(t, backupMonitor) + + var code int + oldExit := exitFn + t.Cleanup(func() { exitFn = oldExit }) + exitFn = func(c int) { code = c } + + t.Run("missing", func(t *testing.T) { + code = 0 + missing := filepath.Join(t.TempDir(), "no-such-crontab") + stderr := runSyncArgs(t, apiURL, missing, "--auto") + if code != 1 { + t.Fatalf("exit %d; want 1 when the crontab does not exist", code) + } + if lastSyncStdout != "" { + t.Fatalf("stdout = %q; want nothing when the file does not exist", lastSyncStdout) + } + if strings.TrimSpace(stderr) == "" { + t.Fatal("stderr is empty; the missing file was not reported") + } + }) + + t.Run("unwritable", func(t *testing.T) { + code = 0 + body := "0 2 * * * /usr/bin/backup.sh\n" + path := writeCron(t, body) + // Root can still open a mode 0444 file, so stub the check planCrontab uses. + old := crontabWritable + t.Cleanup(func() { crontabWritable = old }) + crontabWritable = func(*lib.Crontab) bool { return false } + + stderr := runSyncArgs(t, apiURL, path, "--auto") + if code != 1 { + t.Fatalf("exit %d; want 1 when the crontab is not writable", code) + } + if strings.TrimSpace(lastSyncStdout) != strings.TrimSpace(body) { + t.Fatalf("stdout = %q; want the original crontab", lastSyncStdout) + } + if got := readCron(t, path); got != body { + t.Fatalf("crontab on disk changed:\n%s", got) + } + if strings.TrimSpace(stderr) == "" { + t.Fatal("stderr is empty; the unwritable file was not reported") + } + }) +} + func TestSyncSilentStillConfirms(t *testing.T) { withSyncFixture(t) withNotificationList(t, "") diff --git a/docs/releases/33.15.md b/docs/releases/33.15.md index e14d0bf..2875beb 100644 --- a/docs/releases/33.15.md +++ b/docs/releases/33.15.md @@ -8,7 +8,8 @@ Sync is now safe and quiet to run again on a crontab it already set up ([#90](ht - Plain `cronitor sync` is the normal way to rerun. It checks every monitored job against Cronitor and picks up schedule and timezone changes without asking about the job. - For a job that is already monitored, sync sends only what changed: the schedule, the timezone, and the alert list when you pass `--notification-list`. Without that flag, existing alert lists are kept and new monitors get Cronitor's default. Before, every sync replaced tags set in Cronitor with `cron-job` and reset alert lists to `default`. - A changed `CRON_TZ` or `TZ` line now updates the monitor's timezone even when the schedule stays the same. Before, sync missed it. -- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`), so `cronitor sync --auto file | crontab -` never installs an empty crontab. If the shell wrapper cannot be installed or the crontab cannot be saved, it prints the original crontab and exits 1, so that pipe reinstalls a working crontab instead of one whose `SHELL=` points at a missing wrapper. Use it for scripts, not to pick up one schedule change. +- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`). Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. Do not add `--silent` to that command: `--auto --silent` prints no crontab, so the pipe would install an empty one. Use it for scripts, not to pick up one schedule change. +- `--dry-run` on a single named file that can't be written now exits 1. - If any crontab fails to apply, in any mode (interactive or `--auto`, one crontab or several), sync now exits 1. Before, it exited 0. - `--silent` hides status messages. On an interactive run it still asks `Apply these changes?` before sending or writing, so a monitored job's schedule cannot change with no confirmation. Combined with `--auto`, it also skips printing the crontab. - The name in Cronitor wins. Sync no longer sends the name from a `# Name:` comment for a monitored job, so a rename in the dashboard stays. If the comment differs, sync updates it. It does not add a new `# Name:` comment. diff --git a/tests/test-discover.bats b/tests/test-discover.bats index 63fec70..b445b96 100755 --- a/tests/test-discover.bats +++ b/tests/test-discover.bats @@ -82,12 +82,17 @@ teardown() { run -1 bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" --no-stdout | grep "cronitor exec" | grep -q "no-stdout"' } +# discover --auto on one file prints the crontab on stdout and --verbose +# request logs on stderr. Windows does not reserve stdout, so those logs +# stay there. Read both streams: the needles are not in the crontab. +# bash -c does not see this test's variables unless they are passed in. @test "Discover omits 'notifications' if notification-list not specificed" { - run -1 bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" | grep -q "notifications"' + run -1 env API_KEY="$API_KEY" FIXTURES_DIR="$FIXTURES_DIR" CRONITOR_ARGS="$CRONITOR_ARGS" \ + bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" 2>&1 | grep -q "notifications"' } @test "Discover includes custom notification-list" { - ../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" --notification-list test-list-name | grep -q "test-list-name" + ../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" --notification-list test-list-name 2>&1 | grep -q "test-list-name" } @test "Discover reads all of the crontabs in a directory" {