Debian Codegraph @

t/unit/app/test_schedules.py

raw
1 import sys
2 import time
3 from contextlib import contextmanager
4 from datetime import datetime, timedelta, timezone
5 from pickle import dumps, loads
6 from unittest import TestCase
7 from unittest.mock import Mock
8
9 import pytest
10
11 from celery.schedules import ParseException, crontab, crontab_parser, schedule, solar
12
13 if sys.version_info >= (3, 9):
14 from zoneinfo import ZoneInfo
15 else:
16 from backports.zoneinfo import ZoneInfo
17
18
19 assertions = TestCase('__init__')
20
21
22 @contextmanager
23 def patch_crontab_nowfun(cls, retval):
24 prev_nowfun = cls.nowfun
25 cls.nowfun = lambda: retval
26 try:
27 yield
28 finally:
29 cls.nowfun = prev_nowfun
30
31
32 class test_solar:
33
34 def setup_method(self):
35 pytest.importorskip('ephem')
36 self.s = solar('sunrise', 60, 30, app=self.app)
37
38 def test_reduce(self):
39 fun, args = self.s.__reduce__()
40 assert fun(*args) == self.s
41
42 def test_eq(self):
43 assert self.s == solar('sunrise', 60, 30, app=self.app)
44 assert self.s != solar('sunset', 60, 30, app=self.app)
45 assert self.s != schedule(10)
46
47 def test_repr(self):
48 assert repr(self.s)
49
50 def test_is_due(self):
51 self.s.remaining_estimate = Mock(name='rem')
52 self.s.remaining_estimate.return_value = timedelta(seconds=0)
53 assert self.s.is_due(datetime.now(timezone.utc)).is_due
54
55 def test_is_due__not_due(self):
56 self.s.remaining_estimate = Mock(name='rem')
57 self.s.remaining_estimate.return_value = timedelta(hours=10)
58 assert not self.s.is_due(datetime.now(timezone.utc)).is_due
59
60 def test_remaining_estimate(self):
61 self.s.cal = Mock(name='cal')
62 self.s.cal.next_rising().datetime.return_value = datetime.now(timezone.utc)
63 self.s.remaining_estimate(datetime.now(timezone.utc))
64
65 def test_coordinates(self):
66 with pytest.raises(ValueError):
67 solar('sunrise', -120, 60, app=self.app)
68 with pytest.raises(ValueError):
69 solar('sunrise', 120, 60, app=self.app)
70 with pytest.raises(ValueError):
71 solar('sunrise', 60, -200, app=self.app)
72 with pytest.raises(ValueError):
73 solar('sunrise', 60, 200, app=self.app)
74
75 def test_invalid_event(self):
76 with pytest.raises(ValueError):
77 solar('asdqwewqew', 60, 60, app=self.app)
78
79 def test_dusk_horizons_are_negative(self):
80 """All dusk events should have negative horizons (sun below horizon)."""
81 for event in ('dusk_civil', 'dusk_nautical', 'dusk_astronomical'):
82 s = solar(event, 50, 10, app=self.app)
83 horizon = float(s.cal.horizon)
84 assert horizon < 0, (
85 f"{event} horizon should be negative (below horizon), "
86 f"got {s.cal.horizon}"
87 )
88
89 def test_event_uses_center(self):
90 s = solar('solar_noon', 60, 60, app=self.app)
91 for ev, is_center in s._use_center_l.items():
92 s.method = s._methods[ev]
93 s.is_center = s._use_center_l[ev]
94 try:
95 s.remaining_estimate(datetime.now(timezone.utc))
96 except TypeError:
97 pytest.fail(
98 f"{s.method} was called with 'use_center' which is not a "
99 "valid keyword for the function.")
100
101
102 class test_schedule:
103
104 def test_ne(self):
105 s1 = schedule(10, app=self.app)
106 s2 = schedule(12, app=self.app)
107 s3 = schedule(10, app=self.app)
108 assert s1 == s3
109 assert s1 != s2
110
111 def test_pickle(self):
112 s1 = schedule(10, app=self.app)
113 fun, args = s1.__reduce__()
114 s2 = fun(*args)
115 assert s1 == s2
116
117
118 # This is needed for test_crontab_parser because datetime.utcnow doesn't pickle
119 # in python 2
120 def utcnow():
121 return datetime.now(timezone.utc)
122
123
124 class test_crontab_parser:
125
126 def crontab(self, *args, **kwargs):
127 return crontab(*args, **dict(kwargs, app=self.app))
128
129 def test_crontab_reduce(self):
130 c = self.crontab('*')
131 assert c == loads(dumps(c))
132 c = self.crontab(
133 minute='1',
134 hour='2',
135 day_of_week='3',
136 day_of_month='4',
137 month_of_year='5',
138 nowfun=utcnow)
139 assert c == loads(dumps(c))
140
141 def test_range_steps_not_enough(self):
142 with pytest.raises(crontab_parser.ParseException):
143 crontab_parser(24)._range_steps([1])
144
145 def test_parse_star(self):
146 assert crontab_parser(24).parse('*') == set(range(24))
147 assert crontab_parser(60).parse('*') == set(range(60))
148 assert crontab_parser(7).parse('*') == set(range(7))
149 assert crontab_parser(31, 1).parse('*') == set(range(1, 31 + 1))
150 assert crontab_parser(12, 1).parse('*') == set(range(1, 12 + 1))
151
152 def test_parse_range(self):
153 assert crontab_parser(60).parse('1-10') == set(range(1, 10 + 1))
154 assert crontab_parser(24).parse('0-20') == set(range(0, 20 + 1))
155 assert crontab_parser().parse('2-10') == set(range(2, 10 + 1))
156 assert crontab_parser(60, 1).parse('1-10') == set(range(1, 10 + 1))
157
158 def test_parse_range_wraps(self):
159 assert crontab_parser(12).parse('11-1') == {11, 0, 1}
160 assert crontab_parser(60, 1).parse('2-1') == set(range(1, 60 + 1))
161
162 def test_parse_groups(self):
163 assert crontab_parser().parse('1,2,3,4') == {1, 2, 3, 4}
164 assert crontab_parser().parse('0,15,30,45') == {0, 15, 30, 45}
165 assert crontab_parser(min_=1).parse('1,2,3,4') == {1, 2, 3, 4}
166
167 def test_parse_steps(self):
168 assert crontab_parser(8).parse('*/2') == {0, 2, 4, 6}
169 assert crontab_parser().parse('*/2') == {i * 2 for i in range(30)}
170 assert crontab_parser().parse('*/3') == {i * 3 for i in range(20)}
171 assert crontab_parser(8, 1).parse('*/2') == {1, 3, 5, 7}
172 assert crontab_parser(min_=1).parse('*/2') == {
173 i * 2 + 1 for i in range(30)
174 }
175 assert crontab_parser(min_=1).parse('*/3') == {
176 i * 3 + 1 for i in range(20)
177 }
178
179 def test_parse_composite(self):
180 assert crontab_parser(8).parse('*/2') == {0, 2, 4, 6}
181 assert crontab_parser().parse('2-9/5') == {2, 7}
182 assert crontab_parser().parse('2-10/5') == {2, 7}
183 assert crontab_parser(min_=1).parse('55-5/3') == {55, 58, 1, 4}
184 assert crontab_parser().parse('2-11/5,3') == {2, 3, 7}
185 assert crontab_parser().parse('2-4/3,*/5,0-21/4') == {
186 0, 2, 4, 5, 8, 10, 12, 15, 16, 20, 25, 30, 35, 40, 45, 50, 55,
187 }
188 assert crontab_parser().parse('1-9/2') == {1, 3, 5, 7, 9}
189 assert crontab_parser(8, 1).parse('*/2') == {1, 3, 5, 7}
190 assert crontab_parser(min_=1).parse('2-9/5') == {2, 7}
191 assert crontab_parser(min_=1).parse('2-10/5') == {2, 7}
192 assert crontab_parser(min_=1).parse('2-11/5,3') == {2, 3, 7}
193 assert crontab_parser(min_=1).parse('2-4/3,*/5,1-21/4') == {
194 1, 2, 5, 6, 9, 11, 13, 16, 17, 21, 26, 31, 36, 41, 46, 51, 56,
195 }
196 assert crontab_parser(min_=1).parse('1-9/2') == {1, 3, 5, 7, 9}
197
198 def test_parse_errors_on_empty_string(self):
199 with pytest.raises(ParseException):
200 crontab_parser(60).parse('')
201
202 def test_parse_errors_on_empty_group(self):
203 with pytest.raises(ParseException):
204 crontab_parser(60).parse('1,,2')
205
206 def test_parse_errors_on_empty_steps(self):
207 with pytest.raises(ParseException):
208 crontab_parser(60).parse('*/')
209
210 def test_parse_errors_on_negative_number(self):
211 with pytest.raises(ParseException):
212 crontab_parser(60).parse('-20')
213
214 def test_parse_errors_on_lt_min(self):
215 crontab_parser(min_=1).parse('1')
216 with pytest.raises(ValueError):
217 crontab_parser(12, 1).parse('0')
218 with pytest.raises(ValueError):
219 crontab_parser(24, 1).parse('12-0')
220
221 def test_parse_errors_on_gt_max(self):
222 crontab_parser(1).parse('0')
223 with pytest.raises(ValueError):
224 crontab_parser(1).parse('1')
225 with pytest.raises(ValueError):
226 crontab_parser(60).parse('61-0')
227
228 def test_expand_cronspec_eats_iterables(self):
229 assert crontab._expand_cronspec(iter([1, 2, 3]), 100) == {1, 2, 3}
230 assert crontab._expand_cronspec(iter([1, 2, 3]), 100, 1) == {1, 2, 3}
231
232 def test_expand_cronspec_invalid_type(self):
233 with pytest.raises(TypeError):
234 crontab._expand_cronspec(object(), 100)
235
236 def test_repr(self):
237 assert '*' in repr(self.crontab('*'))
238
239 def test_eq(self):
240 assert (self.crontab(day_of_week='1, 2') ==
241 self.crontab(day_of_week='1-2'))
242 assert (self.crontab(day_of_month='1, 16, 31') ==
243 self.crontab(day_of_month='*/15'))
244 assert (
245 self.crontab(
246 minute='1', hour='2', day_of_week='5',
247 day_of_month='10', month_of_year='5') ==
248 self.crontab(
249 minute='1', hour='2', day_of_week='5',
250 day_of_month='10', month_of_year='5'))
251 assert crontab(minute='1') != crontab(minute='2')
252 assert (self.crontab(month_of_year='1') !=
253 self.crontab(month_of_year='2'))
254 assert object() != self.crontab(minute='1')
255 assert self.crontab(minute='1') != object()
256 assert crontab(month_of_year='1') != schedule(10)
257
258
259 class test_crontab_from_string:
260
261 def test_every_minute(self):
262 assert crontab.from_string('* * * * *') == crontab()
263
264 def test_every_minute_on_sunday(self):
265 assert crontab.from_string('* * * * SUN') == crontab(day_of_week='SUN')
266
267 def test_once_per_month(self):
268 assert crontab.from_string('0 8 5 * *') == crontab(minute=0, hour=8, day_of_month=5)
269
270 def test_invalid_crontab_string(self):
271 with pytest.raises(ValueError):
272 crontab.from_string('*')
273
274
275 class test_crontab_remaining_estimate:
276
277 def crontab(self, *args, **kwargs):
278 return crontab(*args, **dict(kwargs, app=self.app))
279
280 def next_occurrence(self, crontab, now):
281 crontab.nowfun = lambda: now
282 return now + crontab.remaining_estimate(now)
283
284 def test_next_minute(self):
285 next = self.next_occurrence(
286 self.crontab(), datetime(2010, 9, 11, 14, 30, 15),
287 )
288 assert next == datetime(2010, 9, 11, 14, 31)
289
290 def test_not_next_minute(self):
291 next = self.next_occurrence(
292 self.crontab(), datetime(2010, 9, 11, 14, 59, 15),
293 )
294 assert next == datetime(2010, 9, 11, 15, 0)
295
296 def test_this_hour(self):
297 next = self.next_occurrence(
298 self.crontab(minute=[5, 42]), datetime(2010, 9, 11, 14, 30, 15),
299 )
300 assert next == datetime(2010, 9, 11, 14, 42)
301
302 def test_not_this_hour(self):
303 next = self.next_occurrence(
304 self.crontab(minute=[5, 10, 15]),
305 datetime(2010, 9, 11, 14, 30, 15),
306 )
307 assert next == datetime(2010, 9, 11, 15, 5)
308
309 def test_today(self):
310 next = self.next_occurrence(
311 self.crontab(minute=[5, 42], hour=[12, 17]),
312 datetime(2010, 9, 11, 14, 30, 15),
313 )
314 assert next == datetime(2010, 9, 11, 17, 5)
315
316 def test_not_today(self):
317 next = self.next_occurrence(
318 self.crontab(minute=[5, 42], hour=[12]),
319 datetime(2010, 9, 11, 14, 30, 15),
320 )
321 assert next == datetime(2010, 9, 12, 12, 5)
322
323 def test_weekday(self):
324 next = self.next_occurrence(
325 self.crontab(minute=30, hour=14, day_of_week='sat'),
326 datetime(2010, 9, 11, 14, 30, 15),
327 )
328 assert next == datetime(2010, 9, 18, 14, 30)
329
330 def test_not_weekday(self):
331 next = self.next_occurrence(
332 self.crontab(minute=[5, 42], day_of_week='mon-fri'),
333 datetime(2010, 9, 11, 14, 30, 15),
334 )
335 assert next == datetime(2010, 9, 13, 0, 5)
336
337 def test_monthyear(self):
338 next = self.next_occurrence(
339 self.crontab(minute=30, hour=14, month_of_year='oct', day_of_month=18),
340 datetime(2010, 9, 11, 14, 30, 15),
341 )
342 assert next == datetime(2010, 10, 18, 14, 30)
343
344 def test_not_monthyear(self):
345 next = self.next_occurrence(
346 self.crontab(minute=[5, 42], month_of_year='nov-dec', day_of_month=13),
347 datetime(2010, 9, 11, 14, 30, 15),
348 )
349 assert next == datetime(2010, 11, 13, 0, 5)
350
351 def test_monthday(self):
352 next = self.next_occurrence(
353 self.crontab(minute=30, hour=14, day_of_month=18),
354 datetime(2010, 9, 11, 14, 30, 15),
355 )
356 assert next == datetime(2010, 9, 18, 14, 30)
357
358 def test_not_monthday(self):
359 next = self.next_occurrence(
360 self.crontab(minute=[5, 42], day_of_month=29),
361 datetime(2010, 1, 22, 14, 30, 15),
362 )
363 assert next == datetime(2010, 1, 29, 0, 5)
364
365 def test_weekday_monthday(self):
366 next = self.next_occurrence(
367 self.crontab(minute=30, hour=14,
368 day_of_week='mon', day_of_month=18),
369 datetime(2010, 1, 18, 14, 30, 15),
370 )
371 assert next == datetime(2010, 10, 18, 14, 30)
372
373 def test_monthday_not_weekday(self):
374 next = self.next_occurrence(
375 self.crontab(minute=[5, 42], day_of_week='sat', day_of_month=29),
376 datetime(2010, 1, 29, 0, 5, 15),
377 )
378 assert next == datetime(2010, 5, 29, 0, 5)
379
380 def test_weekday_not_monthday(self):
381 next = self.next_occurrence(
382 self.crontab(minute=[5, 42], day_of_week='mon', day_of_month=18),
383 datetime(2010, 1, 11, 0, 5, 15),
384 )
385 assert next == datetime(2010, 1, 18, 0, 5)
386
387 def test_not_weekday_not_monthday(self):
388 next = self.next_occurrence(
389 self.crontab(minute=[5, 42], day_of_week='mon', day_of_month=18),
390 datetime(2010, 1, 10, 0, 5, 15),
391 )
392 assert next == datetime(2010, 1, 18, 0, 5)
393
394 def test_leapday(self):
395 next = self.next_occurrence(
396 self.crontab(minute=30, hour=14, day_of_month=29),
397 datetime(2012, 1, 29, 14, 30, 15),
398 )
399 assert next == datetime(2012, 2, 29, 14, 30)
400
401 def test_not_leapday(self):
402 next = self.next_occurrence(
403 self.crontab(minute=30, hour=14, day_of_month=29),
404 datetime(2010, 1, 29, 14, 30, 15),
405 )
406 assert next == datetime(2010, 3, 29, 14, 30)
407
408 def test_weekmonthdayyear(self):
409 next = self.next_occurrence(
410 self.crontab(minute=30, hour=14, day_of_week='fri',
411 day_of_month=29, month_of_year=1),
412 datetime(2010, 1, 22, 14, 30, 15),
413 )
414 assert next == datetime(2010, 1, 29, 14, 30)
415
416 def test_monthdayyear_not_week(self):
417 next = self.next_occurrence(
418 self.crontab(minute=[5, 42], day_of_week='wed,thu',
419 day_of_month=29, month_of_year='1,4,7'),
420 datetime(2010, 1, 29, 14, 30, 15),
421 )
422 assert next == datetime(2010, 4, 29, 0, 5)
423
424 def test_weekdaymonthyear_not_monthday(self):
425 next = self.next_occurrence(
426 self.crontab(minute=30, hour=14, day_of_week='fri',
427 day_of_month=29, month_of_year='1-10'),
428 datetime(2010, 1, 29, 14, 30, 15),
429 )
430 assert next == datetime(2010, 10, 29, 14, 30)
431
432 def test_weekmonthday_not_monthyear(self):
433 next = self.next_occurrence(
434 self.crontab(minute=[5, 42], day_of_week='fri',
435 day_of_month=29, month_of_year='2-10'),
436 datetime(2010, 1, 29, 14, 30, 15),
437 )
438 assert next == datetime(2010, 10, 29, 0, 5)
439
440 def test_weekday_not_monthdayyear(self):
441 next = self.next_occurrence(
442 self.crontab(minute=[5, 42], day_of_week='mon',
443 day_of_month=18, month_of_year='2-10'),
444 datetime(2010, 1, 11, 0, 5, 15),
445 )
446 assert next == datetime(2010, 10, 18, 0, 5)
447
448 def test_monthday_not_weekdaymonthyear(self):
449 next = self.next_occurrence(
450 self.crontab(minute=[5, 42], day_of_week='mon',
451 day_of_month=29, month_of_year='2-4'),
452 datetime(2010, 1, 29, 0, 5, 15),
453 )
454 assert next == datetime(2010, 3, 29, 0, 5)
455
456 def test_monthyear_not_weekmonthday(self):
457 next = self.next_occurrence(
458 self.crontab(minute=[5, 42], day_of_week='mon',
459 day_of_month=29, month_of_year='2-4'),
460 datetime(2010, 2, 28, 0, 5, 15),
461 )
462 assert next == datetime(2010, 3, 29, 0, 5)
463
464 def test_not_weekmonthdayyear(self):
465 next = self.next_occurrence(
466 self.crontab(minute=[5, 42], day_of_week='fri,sat',
467 day_of_month=29, month_of_year='2-10'),
468 datetime(2010, 1, 28, 14, 30, 15),
469 )
470 assert next == datetime(2010, 5, 29, 0, 5)
471
472 def test_invalid_specification(self):
473 # *** WARNING ***
474 # This test triggers an infinite loop in case of a regression
475 with pytest.raises(RuntimeError):
476 self.next_occurrence(
477 self.crontab(day_of_month=31, month_of_year=4),
478 datetime(2010, 1, 28, 14, 30, 15),
479 )
480
481 def test_leapyear(self):
482 next = self.next_occurrence(
483 self.crontab(minute=30, hour=14, day_of_month=29, month_of_year=2),
484 datetime(2012, 2, 29, 14, 30),
485 )
486 assert next == datetime(2016, 2, 29, 14, 30)
487
488 def test_day_after_dst_end(self):
489 # Test for #1604 issue with region configuration using DST
490 tzname = "Europe/Paris"
491 self.app.timezone = tzname
492 tz = ZoneInfo(tzname)
493 crontab = self.crontab(minute=0, hour=9)
494
495 # Set last_run_at Before DST end
496 last_run_at = datetime(2017, 10, 28, 9, 0, tzinfo=tz)
497 # Set now after DST end
498 now = datetime(2017, 10, 29, 7, 0, tzinfo=tz)
499 crontab.nowfun = lambda: now
500 next = now + crontab.remaining_estimate(last_run_at)
501
502 assert next.utcoffset().seconds == 3600
503 assert next == datetime(2017, 10, 29, 9, 0, tzinfo=tz)
504
505 def test_day_after_dst_start(self):
506 # Test for #1604 issue with region configuration using DST
507 tzname = "Europe/Paris"
508 self.app.timezone = tzname
509 tz = ZoneInfo(tzname)
510 crontab = self.crontab(minute=0, hour=9)
511
512 # Set last_run_at Before DST start
513 last_run_at = datetime(2017, 3, 25, 9, 0, tzinfo=tz)
514 # Set now after DST start
515 now = datetime(2017, 3, 26, 7, 0, tzinfo=tz)
516 crontab.nowfun = lambda: now
517 next = now + crontab.remaining_estimate(last_run_at)
518
519 assert next.utcoffset().seconds == 7200
520 assert next == datetime(2017, 3, 26, 9, 0, tzinfo=tz)
521
522 def test_negative_utc_timezone_with_day_of_month(self):
523 # UTC-8
524 tzname = "America/Los_Angeles"
525 self.app.timezone = tzname
526 tz = ZoneInfo(tzname)
527
528 # set day_of_month to test on _delta_to_next
529 crontab = self.crontab(minute=0, day_of_month='27-31')
530
531 # last_run_at: '2023/01/28T23:00:00-08:00'
532 last_run_at = datetime(2023, 1, 28, 23, 0, tzinfo=tz)
533
534 # now: '2023/01/29T00:00:00-08:00'
535 now = datetime(2023, 1, 29, 0, 0, tzinfo=tz)
536
537 crontab.nowfun = lambda: now
538 next = now + crontab.remaining_estimate(last_run_at)
539
540 assert next == datetime(2023, 1, 29, 0, 0, tzinfo=tz)
541
542
543 class test_crontab_is_due:
544
545 def setup_method(self):
546 self.now = self.app.now()
547 self.next_minute = 60 - self.now.second - 1e-6 * self.now.microsecond
548 self.every_minute = self.crontab()
549 self.quarterly = self.crontab(minute='*/15')
550 self.hourly = self.crontab(minute=30)
551 self.daily = self.crontab(hour=7, minute=30)
552 self.weekly = self.crontab(hour=7, minute=30, day_of_week='thursday')
553 self.monthly = self.crontab(
554 hour=7, minute=30, day_of_week='thursday', day_of_month='8-14',
555 )
556 self.monthly_moy = self.crontab(
557 hour=22, day_of_week='*', month_of_year='2',
558 day_of_month='26,27,28',
559 )
560 self.yearly = self.crontab(
561 hour=7, minute=30, day_of_week='thursday',
562 day_of_month='8-14', month_of_year=3,
563 )
564
565 def crontab(self, *args, **kwargs):
566 return crontab(*args, app=self.app, **kwargs)
567
568 def test_default_crontab_spec(self):
569 c = self.crontab()
570 assert c.minute == set(range(60))
571 assert c.hour == set(range(24))
572 assert c.day_of_week == set(range(7))
573 assert c.day_of_month == set(range(1, 32))
574 assert c.month_of_year == set(range(1, 13))
575
576 def test_simple_crontab_spec(self):
577 c = self.crontab(minute=30)
578 assert c.minute == {30}
579 assert c.hour == set(range(24))
580 assert c.day_of_week == set(range(7))
581 assert c.day_of_month == set(range(1, 32))
582 assert c.month_of_year == set(range(1, 13))
583
584 @pytest.mark.parametrize('minute,expected', [
585 (30, {30}),
586 ('30', {30}),
587 ((30, 40, 50), {30, 40, 50}),
588 ((30, 40, 50, 51), {30, 40, 50, 51})
589 ])
590 def test_crontab_spec_minute_formats(self, minute, expected):
591 c = self.crontab(minute=minute)
592 assert c.minute == expected
593
594 @pytest.mark.parametrize('minute', [60, '0-100'])
595 def test_crontab_spec_invalid_minute(self, minute):
596 with pytest.raises(ValueError):
597 self.crontab(minute=minute)
598
599 @pytest.mark.parametrize('hour,expected', [
600 (6, {6}),
601 ('5', {5}),
602 ((4, 8, 12), {4, 8, 12}),
603 ])
604 def test_crontab_spec_hour_formats(self, hour, expected):
605 c = self.crontab(hour=hour)
606 assert c.hour == expected
607
608 @pytest.mark.parametrize('hour', [24, '0-30'])
609 def test_crontab_spec_invalid_hour(self, hour):
610 with pytest.raises(ValueError):
611 self.crontab(hour=hour)
612
613 @pytest.mark.parametrize('day_of_week,expected', [
614 (5, {5}),
615 ('5', {5}),
616 ('fri', {5}),
617 ('tuesday,sunday,fri', {0, 2, 5}),
618 ('mon-fri', {1, 2, 3, 4, 5}),
619 ('*/2', {0, 2, 4, 6}),
620 ])
621 def test_crontab_spec_dow_formats(self, day_of_week, expected):
622 c = self.crontab(day_of_week=day_of_week)
623 assert c.day_of_week == expected
624
625 @pytest.mark.parametrize('day_of_week', [
626 'fooday-barday', '1,4,foo', '7', '12',
627 ])
628 def test_crontab_spec_invalid_dow(self, day_of_week):
629 with pytest.raises(ValueError):
630 self.crontab(day_of_week=day_of_week)
631
632 @pytest.mark.parametrize('day_of_month,expected', [
633 (5, {5}),
634 ('5', {5}),
635 ('2,4,6', {2, 4, 6}),
636 ('*/5', {1, 6, 11, 16, 21, 26, 31}),
637 ])
638 def test_crontab_spec_dom_formats(self, day_of_month, expected):
639 c = self.crontab(day_of_month=day_of_month)
640 assert c.day_of_month == expected
641
642 @pytest.mark.parametrize('day_of_month', [0, '0-10', 32, '31,32'])
643 def test_crontab_spec_invalid_dom(self, day_of_month):
644 with pytest.raises(ValueError):
645 self.crontab(day_of_month=day_of_month)
646
647 @pytest.mark.parametrize('month_of_year,expected', [
648 (1, {1}),
649 ('1', {1}),
650 ('feb', {2}),
651 ('Mar', {3}),
652 ('april', {4}),
653 ('may,jun,jul', {5, 6, 7}),
654 ('aug-oct', {8, 9, 10}),
655 ('2,4,6', {2, 4, 6}),
656 ('*/2', {1, 3, 5, 7, 9, 11}),
657 ('2-12/2', {2, 4, 6, 8, 10, 12}),
658 ])
659 def test_crontab_spec_moy_formats(self, month_of_year, expected):
660 c = self.crontab(month_of_year=month_of_year)
661 assert c.month_of_year == expected
662
663 @pytest.mark.parametrize('month_of_year', [0, '0-5', 13, '12,13', 'jaan', 'sebtember'])
664 def test_crontab_spec_invalid_moy(self, month_of_year):
665 with pytest.raises(ValueError):
666 self.crontab(month_of_year=month_of_year)
667
668 def seconds_almost_equal(self, a, b, precision):
669 for index, skew in enumerate((+1, -1, 0)):
670 try:
671 assertions.assertAlmostEqual(a, b + skew, precision)
672 except Exception as exc:
673 # AssertionError != builtins.AssertionError in pytest
674 if 'AssertionError' in str(exc):
675 if index + 1 >= 3:
676 raise
677 else:
678 break
679
680 def test_every_minute_execution_is_due(self):
681 last_ran = self.now - timedelta(seconds=61)
682 due, remaining = self.every_minute.is_due(last_ran)
683 self.assert_relativedelta(self.every_minute, last_ran)
684 assert due
685 self.seconds_almost_equal(remaining, self.next_minute, 1)
686
687 def assert_relativedelta(self, due, last_ran):
688 try:
689 from dateutil.relativedelta import relativedelta
690 except ImportError:
691 return
692 l1, d1, n1 = due.remaining_delta(last_ran)
693 l2, d2, n2 = due.remaining_delta(last_ran, ffwd=relativedelta)
694 if not isinstance(d1, relativedelta):
695 assert l1 == l2
696 for field, value in d1._fields().items():
697 assert getattr(d1, field) == value
698 assert not d2.years
699 assert not d2.months
700 assert not d2.days
701 assert not d2.leapdays
702 assert not d2.hours
703 assert not d2.minutes
704 assert not d2.seconds
705 assert not d2.microseconds
706
707 def test_every_minute_execution_is_not_due(self):
708 last_ran = self.now - timedelta(seconds=self.now.second)
709 due, remaining = self.every_minute.is_due(last_ran)
710 assert not due
711 self.seconds_almost_equal(remaining, self.next_minute, 1)
712
713 def test_execution_is_due_on_saturday(self):
714 # 29th of May 2010 is a saturday
715 with patch_crontab_nowfun(self.hourly, datetime(2010, 5, 29, 10, 30)):
716 last_ran = self.now - timedelta(seconds=61)
717 due, remaining = self.every_minute.is_due(last_ran)
718 assert due
719 self.seconds_almost_equal(remaining, self.next_minute, 1)
720
721 def test_execution_is_due_on_sunday(self):
722 # 30th of May 2010 is a sunday
723 with patch_crontab_nowfun(self.hourly, datetime(2010, 5, 30, 10, 30)):
724 last_ran = self.now - timedelta(seconds=61)
725 due, remaining = self.every_minute.is_due(last_ran)
726 assert due
727 self.seconds_almost_equal(remaining, self.next_minute, 1)
728
729 def test_execution_is_due_on_monday(self):
730 # 31st of May 2010 is a monday
731 with patch_crontab_nowfun(self.hourly, datetime(2010, 5, 31, 10, 30)):
732 last_ran = self.now - timedelta(seconds=61)
733 due, remaining = self.every_minute.is_due(last_ran)
734 assert due
735 self.seconds_almost_equal(remaining, self.next_minute, 1)
736
737 def test_every_hour_execution_is_due(self):
738 with patch_crontab_nowfun(self.hourly, datetime(2010, 5, 10, 10, 30)):
739 due, remaining = self.hourly.is_due(datetime(2010, 5, 10, 6, 30))
740 assert due
741 assert remaining == 60 * 60
742
743 def test_every_hour_execution_is_not_due(self):
744 with patch_crontab_nowfun(self.hourly, datetime(2010, 5, 10, 10, 29)):
745 due, remaining = self.hourly.is_due(datetime(2010, 5, 10, 9, 30))
746 assert not due
747 assert remaining == 60
748
749 def test_first_quarter_execution_is_due(self):
750 with patch_crontab_nowfun(
751 self.quarterly, datetime(2010, 5, 10, 10, 15)):
752 due, remaining = self.quarterly.is_due(
753 datetime(2010, 5, 10, 6, 30),
754 )
755 assert due
756 assert remaining == 15 * 60
757
758 def test_second_quarter_execution_is_due(self):
759 with patch_crontab_nowfun(
760 self.quarterly, datetime(2010, 5, 10, 10, 30)):
761 due, remaining = self.quarterly.is_due(
762 datetime(2010, 5, 10, 6, 30),
763 )
764 assert due
765 assert remaining == 15 * 60
766
767 def test_first_quarter_execution_is_not_due(self):
768 with patch_crontab_nowfun(
769 self.quarterly, datetime(2010, 5, 10, 10, 14)):
770 due, remaining = self.quarterly.is_due(
771 datetime(2010, 5, 10, 10, 0),
772 )
773 assert not due
774 assert remaining == 60
775
776 def test_second_quarter_execution_is_not_due(self):
777 with patch_crontab_nowfun(
778 self.quarterly, datetime(2010, 5, 10, 10, 29)):
779 due, remaining = self.quarterly.is_due(
780 datetime(2010, 5, 10, 10, 15),
781 )
782 assert not due
783 assert remaining == 60
784
785 def test_daily_execution_is_due(self):
786 with patch_crontab_nowfun(self.daily, datetime(2010, 5, 10, 7, 30)):
787 due, remaining = self.daily.is_due(datetime(2010, 5, 9, 7, 30))
788 assert due
789 assert remaining == 24 * 60 * 60
790
791 def test_daily_execution_is_not_due(self):
792 with patch_crontab_nowfun(self.daily, datetime(2010, 5, 10, 10, 30)):
793 due, remaining = self.daily.is_due(datetime(2010, 5, 10, 7, 30))
794 assert not due
795 assert remaining == 21 * 60 * 60
796
797 def test_weekly_execution_is_due(self):
798 with patch_crontab_nowfun(self.weekly, datetime(2010, 5, 6, 7, 30)):
799 due, remaining = self.weekly.is_due(datetime(2010, 4, 30, 7, 30))
800 assert due
801 assert remaining == 7 * 24 * 60 * 60
802
803 def test_weekly_execution_is_not_due(self):
804 with patch_crontab_nowfun(self.weekly, datetime(2010, 5, 7, 10, 30)):
805 due, remaining = self.weekly.is_due(datetime(2010, 5, 6, 7, 30))
806 assert not due
807 assert remaining == 6 * 24 * 60 * 60 - 3 * 60 * 60
808
809 def test_monthly_execution_is_due(self):
810 with patch_crontab_nowfun(self.monthly, datetime(2010, 5, 13, 7, 30)):
811 due, remaining = self.monthly.is_due(datetime(2010, 4, 8, 7, 30))
812 assert due
813 assert remaining == 28 * 24 * 60 * 60
814
815 def test_monthly_execution_is_not_due(self):
816 with patch_crontab_nowfun(self.monthly, datetime(2010, 5, 9, 10, 30)):
817 due, remaining = self.monthly.is_due(datetime(2010, 4, 8, 7, 30))
818 assert not due
819 assert remaining == 4 * 24 * 60 * 60 - 3 * 60 * 60
820
821 def test_monthly_moy_execution_is_due(self):
822 with patch_crontab_nowfun(
823 self.monthly_moy, datetime(2014, 2, 26, 22, 0)):
824 due, remaining = self.monthly_moy.is_due(
825 datetime(2013, 7, 4, 10, 0),
826 )
827 assert due
828 assert remaining == 60.0
829
830 @pytest.mark.skip('TODO: unstable test')
831 def test_monthly_moy_execution_is_not_due(self):
832 with patch_crontab_nowfun(
833 self.monthly_moy, datetime(2013, 6, 28, 14, 30)):
834 due, remaining = self.monthly_moy.is_due(
835 datetime(2013, 6, 28, 22, 14),
836 )
837 assert not due
838 attempt = (
839 time.mktime(datetime(2014, 2, 26, 22, 0).timetuple()) -
840 time.mktime(datetime(2013, 6, 28, 14, 30).timetuple()) -
841 60 * 60
842 )
843 assert remaining == attempt
844
845 def test_monthly_moy_execution_is_due2(self):
846 with patch_crontab_nowfun(
847 self.monthly_moy, datetime(2014, 2, 26, 22, 0)):
848 due, remaining = self.monthly_moy.is_due(
849 datetime(2013, 2, 28, 10, 0),
850 )
851 assert due
852 assert remaining == 60.0
853
854 def test_monthly_moy_execution_is_not_due2(self):
855 with patch_crontab_nowfun(
856 self.monthly_moy, datetime(2014, 2, 26, 21, 0)):
857 due, remaining = self.monthly_moy.is_due(
858 datetime(2013, 6, 28, 22, 14),
859 )
860 assert not due
861 attempt = 60 * 60
862 assert remaining == attempt
863
864 def test_yearly_execution_is_due(self):
865 with patch_crontab_nowfun(self.yearly, datetime(2010, 3, 11, 7, 30)):
866 due, remaining = self.yearly.is_due(datetime(2009, 3, 12, 7, 30))
867 assert due
868 assert remaining == 364 * 24 * 60 * 60
869
870 def test_yearly_execution_is_not_due(self):
871 with patch_crontab_nowfun(self.yearly, datetime(2010, 3, 7, 10, 30)):
872 due, remaining = self.yearly.is_due(datetime(2009, 3, 12, 7, 30))
873 assert not due
874 assert remaining == 4 * 24 * 60 * 60 - 3 * 60 * 60
875
876 def test_execution_not_due_if_task_not_run_at_last_feasible_time_outside_deadline(
877 self):
878 """If the crontab schedule was added after the task was due, don't
879 immediately fire the task again"""
880 # could have feasibly been run on 12/5 at 7:30, but wasn't.
881 self.app.conf.beat_cron_starting_deadline = 3600
882 last_run = datetime(2022, 12, 4, 10, 30)
883 now = datetime(2022, 12, 5, 10, 30)
884 expected_next_execution_time = datetime(2022, 12, 6, 7, 30)
885 expected_remaining = (
886 expected_next_execution_time - now).total_seconds()
887
888 # Run the daily (7:30) crontab with the current date
889 with patch_crontab_nowfun(self.daily, now):
890 due, remaining = self.daily.is_due(last_run)
891 assert remaining == expected_remaining
892 assert not due
893
894 def test_execution_not_due_if_task_not_run_at_last_feasible_time_no_deadline_set(
895 self):
896 """Same as above test except there's no deadline set, so it should be
897 due"""
898 last_run = datetime(2022, 12, 4, 10, 30)
899 now = datetime(2022, 12, 5, 10, 30)
900 expected_next_execution_time = datetime(2022, 12, 6, 7, 30)
901 expected_remaining = (
902 expected_next_execution_time - now).total_seconds()
903
904 # Run the daily (7:30) crontab with the current date
905 with patch_crontab_nowfun(self.daily, now):
906 due, remaining = self.daily.is_due(last_run)
907 assert remaining == expected_remaining
908 assert due
909
910 def test_execution_due_if_task_not_run_at_last_feasible_time_within_deadline(
911 self):
912 # Could have feasibly been run on 12/5 at 7:30, but wasn't. We are
913 # still within a 1 hour deadline from the
914 # last feasible run, so the task should still be due.
915 self.app.conf.beat_cron_starting_deadline = 3600
916 last_run = datetime(2022, 12, 4, 10, 30)
917 now = datetime(2022, 12, 5, 8, 0)
918 expected_next_execution_time = datetime(2022, 12, 6, 7, 30)
919 expected_remaining = (
920 expected_next_execution_time - now).total_seconds()
921
922 # run the daily (7:30) crontab with the current date
923 with patch_crontab_nowfun(self.daily, now):
924 due, remaining = self.daily.is_due(last_run)
925 assert remaining == expected_remaining
926 assert due
927
928 def test_execution_due_if_task_not_run_at_any_feasible_time_within_deadline(
929 self):
930 # Could have feasibly been run on 12/4 at 7:30, or 12/5 at 7:30,
931 # but wasn't. We are still within a 1 hour
932 # deadline from the last feasible run (12/5), so the task should
933 # still be due.
934 self.app.conf.beat_cron_starting_deadline = 3600
935 last_run = datetime(2022, 12, 3, 10, 30)
936 now = datetime(2022, 12, 5, 8, 0)
937 expected_next_execution_time = datetime(2022, 12, 6, 7, 30)
938 expected_remaining = (
939 expected_next_execution_time - now).total_seconds()
940
941 # Run the daily (7:30) crontab with the current date
942 with patch_crontab_nowfun(self.daily, now):
943 due, remaining = self.daily.is_due(last_run)
944 assert remaining == expected_remaining
945 assert due
946
947 def test_execution_not_due_if_task_not_run_at_any_feasible_time_outside_deadline(
948 self):
949 """Verifies that remaining is still the time to the next
950 feasible run date even though the original feasible date
951 was passed over in favor of a newer one."""
952 # Could have feasibly been run on 12/4 or 12/5 at 7:30,
953 # but wasn't.
954 self.app.conf.beat_cron_starting_deadline = 3600
955 last_run = datetime(2022, 12, 3, 10, 30)
956 now = datetime(2022, 12, 5, 11, 0)
957 expected_next_execution_time = datetime(2022, 12, 6, 7, 30)
958 expected_remaining = (
959 expected_next_execution_time - now).total_seconds()
960
961 # run the daily (7:30) crontab with the current date
962 with patch_crontab_nowfun(self.daily, now):
963 due, remaining = self.daily.is_due(last_run)
964 assert remaining == expected_remaining
965 assert not due
966
967 def test_execution_not_due_if_last_run_in_future(self):
968 # Should not run if the last_run hasn't happened yet.
969 last_run = datetime(2022, 12, 6, 7, 30)
970 now = datetime(2022, 12, 5, 10, 30)
971 expected_next_execution_time = datetime(2022, 12, 7, 7, 30)
972 expected_remaining = (
973 expected_next_execution_time - now).total_seconds()
974
975 # Run the daily (7:30) crontab with the current date
976 with patch_crontab_nowfun(self.daily, now):
977 due, remaining = self.daily.is_due(last_run)
978 assert not due
979 assert remaining == expected_remaining
980
981 def test_execution_not_due_if_last_run_at_last_feasible_time(self):
982 # Last feasible time is 12/5 at 7:30
983 last_run = datetime(2022, 12, 5, 7, 30)
984 now = datetime(2022, 12, 5, 10, 30)
985 expected_next_execution_time = datetime(2022, 12, 6, 7, 30)
986 expected_remaining = (
987 expected_next_execution_time - now).total_seconds()
988
989 # Run the daily (7:30) crontab with the current date
990 with patch_crontab_nowfun(self.daily, now):
991 due, remaining = self.daily.is_due(last_run)
992 assert remaining == expected_remaining
993 assert not due
994
995 def test_execution_not_due_if_last_run_past_last_feasible_time(self):
996 # Last feasible time is 12/5 at 7:30
997 last_run = datetime(2022, 12, 5, 8, 30)
998 now = datetime(2022, 12, 5, 10, 30)
999 expected_next_execution_time = datetime(2022, 12, 6, 7, 30)
1000 expected_remaining = (
1001 expected_next_execution_time - now).total_seconds()
1002
1003 # Run the daily (7:30) crontab with the current date
1004 with patch_crontab_nowfun(self.daily, now):
1005 due, remaining = self.daily.is_due(last_run)
1006 assert remaining == expected_remaining
1007 assert not due
1008
1009 def test_execution_due_for_negative_utc_timezone_with_day_of_month(self):
1010 # UTC-8
1011 tzname = "America/Los_Angeles"
1012 self.app.timezone = tzname
1013 tz = ZoneInfo(tzname)
1014
1015 # set day_of_month to test on _delta_to_next
1016 crontab = self.crontab(minute=0, day_of_month='27-31')
1017
1018 # last_run_at: '2023/01/28T23:00:00-08:00'
1019 last_run_at = datetime(2023, 1, 28, 23, 0, tzinfo=tz)
1020
1021 # now: '2023/01/29T00:00:00-08:00'
1022 now = datetime(2023, 1, 29, 0, 0, tzinfo=tz)
1023
1024 with patch_crontab_nowfun(crontab, now):
1025 due, remaining = crontab.is_due(last_run_at)
1026 assert (due, remaining) == (True, 3600)