cronrunner 2.15.0

Run cron jobs manually.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
mod utils;

use std::collections::HashMap;
use std::env;

use cronrunner::crontab::{RunResultDetail, make_instance};
use cronrunner::reader::{ReadError, ReadErrorDetail, Reader};
use cronrunner::tokens::{Comment, CommentKind, CronJob, Token, Variable};

use crate::utils::{mock_crontab, mock_shell, read_output_file};

// Warning: These tests MUST be run sequentially. Running them in
// parallel threads may cause conflicts with environment variables,
// as a variable may be overridden before it is used.

// Really, this is a unit test. But here we've got the mocking machinery
// available at no extra cost.
#[test]
fn correct_argument_is_passed_to_crontab() {
    mock_crontab("crontab_output_args");

    let crontab = Reader::read().unwrap();

    // crontab -l
    assert_eq!(crontab.trim(), "-l");
}

#[test]
fn run_job_success() {
    mock_crontab("crontab_runnable_jobs");
    mock_shell("shell_do_nothing");

    let crontab = make_instance().unwrap();
    let job = crontab.get_job_from_uid(2).unwrap();

    let res = crontab.run(job);

    assert!(res.was_successful);
    assert_eq!(res.detail, RunResultDetail::DidRun { exit_code: Some(0) });
}

#[test]
fn run_job_detached_success() {
    mock_crontab("crontab_runnable_jobs");
    mock_shell("shell_do_nothing");

    let crontab = make_instance().unwrap();
    let job = crontab.get_job_from_uid(2).unwrap();

    let res = crontab.run_detached(job);

    assert!(!res.was_successful); // We don't know yet, it's running!
    matches!(res.detail, RunResultDetail::IsRunning { pid: _ });
}

#[test]
fn run_job_error_shell_executable_not_found() {
    mock_crontab("crontab_bad_shell");

    let crontab = make_instance().unwrap();
    let job = crontab.get_job_from_uid(1).unwrap();

    let res = crontab.run(job);

    assert!(!res.was_successful);
    assert_eq!(
        res.detail,
        RunResultDetail::DidNotRun {
            reason: String::from("Failed to run command (does shell exist?).")
        }
    );
}

#[test]
fn run_job_detached_error_shell_executable_not_found() {
    mock_crontab("crontab_bad_shell");

    let crontab = make_instance().unwrap();
    let job = crontab.get_job_from_uid(1).unwrap();

    let res = crontab.run_detached(job);

    assert!(!res.was_successful);
    assert_eq!(
        res.detail,
        RunResultDetail::DidNotRun {
            reason: String::from("Failed to run command (does shell exist?).")
        }
    );
}

#[test]
fn run_job_error_other_reason() {
    mock_crontab("crontab_runnable_jobs");

    let crontab = make_instance().unwrap();
    let job_not_in_crontab = CronJob {
        uid: 42,
        fingerprint: 13_376_942,
        tag: None,
        schedule: String::from("@never"),
        command: String::from("sleep infinity"),
        description: None,
        section: None,
    };

    // We could trigger any error here, besides obviously a problem with
    // the shell executable.
    let res = crontab.run(&job_not_in_crontab);

    assert!(!res.was_successful);
    assert_eq!(
        res.detail,
        RunResultDetail::DidNotRun {
            reason: String::from("The given job is not in the crontab.")
        }
    );
}

#[test]
fn run_job_detached_error_other_reason() {
    mock_crontab("crontab_runnable_jobs");

    let crontab = make_instance().unwrap();
    let job_not_in_crontab = CronJob {
        uid: 42,
        fingerprint: 13_376_942,
        tag: None,
        schedule: String::from("@never"),
        command: String::from("sleep infinity"),
        description: None,
        section: None,
    };

    // We could trigger any error here, besides obviously a problem with
    // the shell executable.
    let res = crontab.run_detached(&job_not_in_crontab);

    assert!(!res.was_successful);
    assert_eq!(
        res.detail,
        RunResultDetail::DidNotRun {
            reason: String::from("The given job is not in the crontab.")
        }
    );
}

#[test]
fn run_job_with_custom_env() {
    mock_crontab("crontab_runnable_jobs");
    mock_shell("shell_output_env_to_file");

    // `PATH` is overridden too, so we need to manually persist it.
    let path = env::var("PATH").expect("set in `mock_shell()`");

    let mut crontab = make_instance().unwrap();

    crontab.set_env(HashMap::from([
        (String::from("FOO"), String::from("bar")),
        (String::from("BAZ"), String::from("42")),
        (String::from("PATH"), path),
    ]));

    let job = crontab.get_job_from_uid(1).unwrap();

    let res = crontab.run(job);

    assert!(res.was_successful);

    let output = read_output_file("output_env");

    dbg!(&output);
    assert!(output.contains("FOO=bar"));
    assert!(output.contains("BAZ=42"));
    assert!(output.contains("PATH=") && output.contains("/mock_bin/:/bin:/usr/bin/"));
}

#[test]
fn run_job_with_custom_env_crontab_variables_have_precedence() {
    mock_crontab("crontab_runnable_jobs");
    mock_shell("shell_output_env_to_file");

    // `PATH` is overridden too, so we need to manually persist it.
    let path = env::var("PATH").expect("set in `mock_shell()`");

    let mut crontab = make_instance().unwrap();

    crontab.set_env(HashMap::from([
        (String::from("FOO"), String::from("bar")),
        (String::from("BAZ"), String::from("42")),
        (String::from("PATH"), path),
    ]));

    // Second job has `FOO=miam` set, which first job does not.
    let job = crontab.get_job_from_uid(2).unwrap();

    let res = crontab.run(job);

    assert!(res.was_successful);

    let output = read_output_file("output_env");

    dbg!(&output);
    assert!(output.contains("FOO=miam")); // Crontab has precedence.
    assert!(output.contains("BAZ=42")); // From `set_env()`.
}

#[test]
fn run_job_with_custom_env_parent_env_does_not_leak_into_set_env() {
    mock_crontab("crontab_runnable_jobs");
    mock_shell("shell_output_env_to_file");

    // `PATH` is overridden too, so we need to manually persist it.
    let path = env::var("PATH").expect("set in `mock_shell()`");

    unsafe {
        env::set_var("CRONRUNNER_TEST", "1337");
    }

    let mut crontab = make_instance().unwrap();

    crontab.set_env(HashMap::from([(String::from("PATH"), path)]));

    // Second job has `FOO=miam` set, which first job does not.
    let job = crontab.get_job_from_uid(1).unwrap();

    let res = crontab.run(job);

    assert!(res.was_successful);

    let output = read_output_file("output_env");

    dbg!(&output);
    assert!(!output.contains("CRONRUNNER_TEST=1337"));
}

#[test]
fn correct_job_is_run() {
    mock_crontab("crontab_runnable_jobs");
    mock_shell("shell_output_args_to_file");

    let crontab = make_instance().unwrap();
    let job = crontab.get_job_from_uid(2).unwrap();

    let res = crontab.run(job);

    assert!(res.was_successful);

    let output = read_output_file("output_args");

    assert_eq!(output.trim(), "-c echo \":)\"");
}

#[test]
fn edge_cases_with_variables() {
    mock_crontab("crontab_variables_edge_cases");
    mock_shell("shell_output_stdout_stderr_to_file");

    let crontab = make_instance().unwrap();
    let job = crontab.get_job_from_uid(1).unwrap();

    let res = crontab.run(job);

    assert!(res.was_successful);

    let output = read_output_file("output_stdout_stderr");

    assert_eq!(
        output.trim().split_terminator('\n').collect::<Vec<&str>>(),
        vec![
            "double_quoted_identifier",
            "single_quoted_identifier",
            "double_quoted_value",
            "single_quoted_value",
            "double_quoted_identifier_and_value",
            "single_quoted_identifier_and_value",
            "quoted # hash",
            "unquoted # hash",
            "$UNEXPANDED_QUOTED",
            "$UNEXPANDED_UNQUOTED",
        ]
    );
}

#[test]
fn make_instance_success() {
    mock_crontab("crontab_example");

    let crontab = make_instance().unwrap();

    assert_eq!(
        crontab.tokens,
        vec![
            Token::Comment(Comment {
                value: String::from(
                    "use /bin/sh to run commands, overriding the default set by cron"
                ),
                kind: CommentKind::Regular,
            }),
            Token::Variable(Variable {
                identifier: String::from("SHELL"),
                value: String::from("/bin/sh")
            }),
            Token::Comment(Comment {
                value: String::from("mail any output to `paul', no matter whose crontab this is"),
                kind: CommentKind::Regular,
            }),
            Token::Variable(Variable {
                identifier: String::from("MAILTO"),
                value: String::from("paul")
            }),
            Token::Comment(Comment {
                value: String::new(),
                kind: CommentKind::Regular,
            }),
            Token::Comment(Comment {
                value: String::from("run five minutes after midnight, every day"),
                kind: CommentKind::Regular,
            }),
            Token::CronJob(CronJob {
                uid: 1,
                fingerprint: 430_144_761_983_614_012,
                tag: None,
                schedule: String::from("5 0 * * *"),
                command: String::from("$HOME/bin/daily.job >> $HOME/tmp/out 2>&1"),
                description: None,
                section: None,
            }),
            Token::Comment(Comment {
                value: String::from(
                    "run at 2:15pm on the first of every month -- output mailed to paul"
                ),
                kind: CommentKind::Regular,
            }),
            Token::CronJob(CronJob {
                uid: 2,
                fingerprint: 3_821_308_948_991_142_357,
                tag: None,
                schedule: String::from("15 14 1 * *"),
                command: String::from("$HOME/bin/monthly"),
                description: None,
                section: None,
            }),
            Token::Comment(Comment {
                value: String::from("run at 10 pm on weekdays, annoy Joe"),
                kind: CommentKind::Regular,
            }),
            Token::CronJob(CronJob {
                uid: 3,
                fingerprint: 10_608_454_177_928_423_339,
                tag: None,
                schedule: String::from("0 22 * * 1-5"),
                command: String::from("mail -s \"It's 10pm\" joe%Joe,%%Where are your kids?%"),
                description: None,
                section: None,
            }),
            Token::CronJob(CronJob {
                uid: 4,
                fingerprint: 4_729_581_268_415_706_813,
                tag: None,
                schedule: String::from("23 0-23/2 * * *"),
                command: String::from("echo \"run 23 minutes after midn, 2am, 4am ..., everyday\""),
                description: None,
                section: None,
            }),
            Token::CronJob(CronJob {
                uid: 5,
                fingerprint: 18_432_149_502_519_362_576,
                tag: None,
                schedule: String::from("5 4 * * sun"),
                command: String::from("echo \"run at 5 after 4 every sunday\""),
                description: None,
                section: None,
            })
        ]
    );
}

#[test]
fn make_instance_error_reading_crontab() {
    mock_crontab("crontab_exit_non_zero");

    let crontab = make_instance();
    let error = crontab.unwrap_err();

    assert_eq!(
        error,
        ReadError {
            reason: "Cannot read crontab of current user.",
            detail: ReadErrorDetail::NonZeroExit {
                exit_code: Some(2),
                stderr: Some(String::from("crontab: illegal option -- <test>\n")),
            }
        }
    );
}

#[test]
fn make_instance_error_running_crontab_command() {
    // Make `crontab` executable inaccessible.
    unsafe {
        env::set_var("PATH", "");
    }

    let crontab = make_instance();
    let error = crontab.unwrap_err();

    assert_eq!(
        error,
        ReadError {
            reason: "Unable to locate the crontab executable on the system.",
            detail: ReadErrorDetail::CouldNotRunCommand,
        }
    );
}