Debian Codegraph @

t/unit/app/test_beat.py

raw
1 import dbm
2 import errno
3 import pickle
4 import sys
5 from datetime import datetime, timedelta, timezone
6 from pickle import dumps, loads
7 from unittest.mock import MagicMock, Mock, call, patch
8
9 import pytest
10
11 from celery import __version__, beat, uuid
12 from celery.beat import BeatLazyFunc, event_t
13 from celery.schedules import crontab, schedule
14 from celery.utils.objects import Bunch
15
16 if sys.version_info >= (3, 9):
17 from zoneinfo import ZoneInfo
18 else:
19 from backports.zoneinfo import ZoneInfo
20
21
22 class MockShelve(dict):
23 closed = False
24 synced = False
25
26 def close(self):
27 self.closed = True
28
29 def sync(self):
30 self.synced = True
31
32
33 class MockService:
34 started = False
35 stopped = False
36
37 def __init__(self, *args, **kwargs):
38 pass
39
40 def start(self, **kwargs):
41 self.started = True
42
43 def stop(self, **kwargs):
44 self.stopped = True
45
46
47 class test_BeatLazyFunc:
48
49 def test_beat_lazy_func(self):
50 def add(a, b):
51 return a + b
52 result = BeatLazyFunc(add, 1, 2)
53 assert add(1, 2) == result()
54 assert add(1, 2) == result.delay()
55
56
57 class test_ScheduleEntry:
58 Entry = beat.ScheduleEntry
59
60 def create_entry(self, **kwargs):
61 entry = {
62 'name': 'celery.unittest.add',
63 'schedule': timedelta(seconds=10),
64 'args': (2, 2),
65 'options': {'routing_key': 'cpu'},
66 'app': self.app,
67 }
68 return self.Entry(**dict(entry, **kwargs))
69
70 def test_next(self):
71 entry = self.create_entry(schedule=10)
72 assert entry.last_run_at
73 assert isinstance(entry.last_run_at, datetime)
74 assert entry.total_run_count == 0
75
76 next_run_at = entry.last_run_at + timedelta(seconds=10)
77 next_entry = entry.next(next_run_at)
78 assert next_entry.last_run_at >= next_run_at
79 assert next_entry.total_run_count == 1
80
81 def test_is_due(self):
82 entry = self.create_entry(schedule=timedelta(seconds=10))
83 assert entry.app is self.app
84 assert entry.schedule.app is self.app
85 due1, next_time_to_run1 = entry.is_due()
86 assert not due1
87 assert next_time_to_run1 > 9
88
89 next_run_at = entry.last_run_at - timedelta(seconds=10)
90 next_entry = entry.next(next_run_at)
91 due2, next_time_to_run2 = next_entry.is_due()
92 assert due2
93 assert next_time_to_run2 > 9
94
95 def test_repr(self):
96 entry = self.create_entry()
97 assert '<ScheduleEntry:' in repr(entry)
98
99 def test_reduce(self):
100 entry = self.create_entry(schedule=timedelta(seconds=10))
101 fun, args = entry.__reduce__()
102 res = fun(*args)
103 assert res.schedule == entry.schedule
104
105 def test_lt(self):
106 e1 = self.create_entry(schedule=timedelta(seconds=10))
107 e2 = self.create_entry(schedule=timedelta(seconds=2))
108 # order doesn't matter, see comment in __lt__
109 res1 = e1 < e2 # noqa
110 try:
111 res2 = e1 < object() # noqa
112 except TypeError:
113 pass
114
115 def test_update(self):
116 entry = self.create_entry()
117 assert entry.schedule == timedelta(seconds=10)
118 assert entry.args == (2, 2)
119 assert entry.kwargs == {}
120 assert entry.options == {'routing_key': 'cpu'}
121
122 entry2 = self.create_entry(schedule=timedelta(minutes=20),
123 args=(16, 16),
124 kwargs={'callback': 'foo.bar.baz'},
125 options={'routing_key': 'urgent'})
126 entry.update(entry2)
127 assert entry.schedule == schedule(timedelta(minutes=20))
128 assert entry.args == (16, 16)
129 assert entry.kwargs == {'callback': 'foo.bar.baz'}
130 assert entry.options == {'routing_key': 'urgent'}
131
132
133 class mScheduler(beat.Scheduler):
134
135 def __init__(self, *args, **kwargs):
136 self.sent = []
137 super().__init__(*args, **kwargs)
138
139 def send_task(self, name=None, args=None, kwargs=None, **options):
140 self.sent.append({'name': name,
141 'args': args,
142 'kwargs': kwargs,
143 'options': options})
144 return self.app.AsyncResult(uuid())
145
146
147 class mSchedulerSchedulingError(mScheduler):
148
149 def send_task(self, *args, **kwargs):
150 raise beat.SchedulingError('Could not apply task')
151
152
153 class mSchedulerRuntimeError(mScheduler):
154
155 def is_due(self, *args, **kwargs):
156 raise RuntimeError('dict modified while itervalues')
157
158
159 class mocked_schedule(schedule):
160
161 def now_func():
162 return datetime.now(timezone.utc)
163
164 def __init__(self, is_due, next_run_at, nowfun=now_func):
165 self._is_due = is_due
166 self._next_run_at = next_run_at
167 self.run_every = timedelta(seconds=1)
168 self.nowfun = nowfun
169 self.default_now = self.nowfun
170
171 def is_due(self, last_run_at):
172 return self._is_due, self._next_run_at
173
174
175 always_due = mocked_schedule(True, 1)
176 always_pending = mocked_schedule(False, 1)
177 always_pending_left_10_milliseconds = mocked_schedule(False, 0.01)
178
179
180 class test_Scheduler:
181
182 def test_custom_schedule_dict(self):
183 custom = {'foo': 'bar'}
184 scheduler = mScheduler(app=self.app, schedule=custom, lazy=True)
185 assert scheduler.data is custom
186
187 def test_apply_async_uses_registered_task_instances(self):
188
189 @self.app.task(shared=False)
190 def foo():
191 pass
192 foo.apply_async = Mock(name='foo.apply_async')
193 assert foo.name in foo._get_app().tasks
194
195 scheduler = mScheduler(app=self.app)
196 scheduler.apply_async(scheduler.Entry(task=foo.name, app=self.app))
197 foo.apply_async.assert_called()
198
199 def test_apply_async_with_null_args(self):
200
201 @self.app.task(shared=False)
202 def foo():
203 pass
204 foo.apply_async = Mock(name='foo.apply_async')
205
206 scheduler = mScheduler(app=self.app)
207 scheduler.apply_async(
208 scheduler.Entry(
209 task=foo.name, app=self.app, args=None, kwargs=None))
210 foo.apply_async.assert_called()
211
212 def test_apply_async_with_null_args_set_to_none(self):
213
214 @self.app.task(shared=False)
215 def foo():
216 pass
217 foo.apply_async = Mock(name='foo.apply_async')
218
219 scheduler = mScheduler(app=self.app)
220 entry = scheduler.Entry(task=foo.name, app=self.app, args=None,
221 kwargs=None)
222 entry.args = None
223 entry.kwargs = None
224
225 scheduler.apply_async(entry, advance=False)
226 foo.apply_async.assert_called()
227
228 def test_apply_async_without_null_args(self):
229
230 @self.app.task(shared=False)
231 def foo(moo: int):
232 return moo
233 foo.apply_async = Mock(name='foo.apply_async')
234
235 scheduler = mScheduler(app=self.app)
236 entry = scheduler.Entry(task=foo.name, app=self.app, args=None,
237 kwargs=None)
238 entry.args = (101,)
239 entry.kwargs = None
240
241 scheduler.apply_async(entry, advance=False)
242 foo.apply_async.assert_called()
243 assert foo.apply_async.call_args[0][0] == [101]
244
245 def test_should_sync(self):
246
247 @self.app.task(shared=False)
248 def not_sync():
249 pass
250 not_sync.apply_async = Mock()
251
252 s = mScheduler(app=self.app)
253 s._do_sync = Mock()
254 s.should_sync = Mock()
255 s.should_sync.return_value = True
256 s.apply_async(s.Entry(task=not_sync.name, app=self.app))
257 s._do_sync.assert_called_with()
258
259 s._do_sync = Mock()
260 s.should_sync.return_value = False
261 s.apply_async(s.Entry(task=not_sync.name, app=self.app))
262 s._do_sync.assert_not_called()
263
264 def test_should_sync_increments_sync_every_counter(self):
265 self.app.conf.beat_sync_every = 2
266
267 @self.app.task(shared=False)
268 def not_sync():
269 pass
270 not_sync.apply_async = Mock()
271
272 s = mScheduler(app=self.app)
273 assert s.sync_every_tasks == 2
274 s._do_sync = Mock()
275
276 s.apply_async(s.Entry(task=not_sync.name, app=self.app))
277 assert s._tasks_since_sync == 1
278 s.apply_async(s.Entry(task=not_sync.name, app=self.app))
279 s._do_sync.assert_called_with()
280
281 self.app.conf.beat_sync_every = 0
282
283 def test_sync_task_counter_resets_on_do_sync(self):
284 self.app.conf.beat_sync_every = 1
285
286 @self.app.task(shared=False)
287 def not_sync():
288 pass
289 not_sync.apply_async = Mock()
290
291 s = mScheduler(app=self.app)
292 assert s.sync_every_tasks == 1
293
294 s.apply_async(s.Entry(task=not_sync.name, app=self.app))
295 assert s._tasks_since_sync == 0
296
297 self.app.conf.beat_sync_every = 0
298
299 @patch('celery.app.base.Celery.send_task')
300 def test_send_task(self, send_task):
301 b = beat.Scheduler(app=self.app)
302 b.send_task('tasks.add', countdown=10)
303 send_task.assert_called_with('tasks.add', countdown=10)
304
305 def test_info(self):
306 scheduler = mScheduler(app=self.app)
307 assert isinstance(scheduler.info, str)
308
309 def test_apply_entry_handles_empty_result(self):
310 s = mScheduler(app=self.app)
311 entry = s.Entry(name='a name', task='foo', app=self.app)
312
313 with patch.object(s, 'apply_async') as mock_apply_async:
314 with patch("celery.beat.debug") as mock_debug:
315 mock_apply_async.return_value = None
316 s.apply_entry(entry)
317 mock_debug.assert_called_once_with('%s sent.', entry.task)
318
319 with patch.object(s, 'apply_async') as mock_apply_async:
320 with patch("celery.beat.debug") as mock_debug:
321 mock_apply_async.return_value = object()
322 s.apply_entry(entry)
323 mock_debug.assert_called_once_with('%s sent.', entry.task)
324
325 task_id = 'taskId123456'
326 with patch.object(s, 'apply_async') as mock_apply_async:
327 with patch("celery.beat.debug") as mock_debug:
328 mock_apply_async.return_value = self.app.AsyncResult(task_id)
329 s.apply_entry(entry)
330 mock_debug.assert_called_once_with('%s sent. id->%s', entry.task, task_id)
331
332 def test_maybe_entry(self):
333 s = mScheduler(app=self.app)
334 entry = s.Entry(name='add every', task='tasks.add', app=self.app)
335 assert s._maybe_entry(entry.name, entry) is entry
336 assert s._maybe_entry('add every', {'task': 'tasks.add'})
337
338 def test_set_schedule(self):
339 s = mScheduler(app=self.app)
340 s.schedule = {'foo': 'bar'}
341 assert s.data == {'foo': 'bar'}
342
343 @patch('kombu.connection.Connection.ensure_connection')
344 def test_ensure_connection_error_handler(self, ensure):
345 s = mScheduler(app=self.app)
346 assert s._ensure_connected()
347 ensure.assert_called()
348 callback = ensure.call_args[0][0]
349
350 callback(KeyError(), 5)
351
352 def test_install_default_entries(self):
353 self.app.conf.result_expires = None
354 self.app.conf.beat_schedule = {}
355 s = mScheduler(app=self.app)
356 s.install_default_entries({})
357 assert 'celery.backend_cleanup' not in s.data
358 self.app.backend.supports_autoexpire = False
359
360 self.app.conf.result_expires = 30
361 s = mScheduler(app=self.app)
362 s.install_default_entries({})
363 assert 'celery.backend_cleanup' in s.data
364
365 self.app.backend.supports_autoexpire = True
366 self.app.conf.result_expires = 31
367 s = mScheduler(app=self.app)
368 s.install_default_entries({})
369 assert 'celery.backend_cleanup' not in s.data
370
371 def test_due_tick(self):
372 scheduler = mScheduler(app=self.app)
373 scheduler.add(name='test_due_tick',
374 schedule=always_due,
375 args=(1, 2),
376 kwargs={'foo': 'bar'})
377 assert scheduler.tick() == 0
378
379 @patch('celery.beat.error')
380 def test_due_tick_SchedulingError(self, error):
381 scheduler = mSchedulerSchedulingError(app=self.app)
382 scheduler.add(name='test_due_tick_SchedulingError',
383 schedule=always_due)
384 assert scheduler.tick() == 0
385 error.assert_called()
386
387 def test_pending_tick(self):
388 scheduler = mScheduler(app=self.app)
389 scheduler.add(name='test_pending_tick',
390 schedule=always_pending)
391 assert scheduler.tick() == 1 - 0.010
392
393 def test_pending_left_10_milliseconds_tick(self):
394 scheduler = mScheduler(app=self.app)
395 scheduler.add(name='test_pending_left_10_milliseconds_tick',
396 schedule=always_pending_left_10_milliseconds)
397 assert scheduler.tick() == 0.010 - 0.010
398
399 def test_honors_max_interval(self):
400 scheduler = mScheduler(app=self.app)
401 maxi = scheduler.max_interval
402 scheduler.add(name='test_honors_max_interval',
403 schedule=mocked_schedule(False, maxi * 4))
404 assert scheduler.tick() == maxi
405
406 def test_ticks(self):
407 scheduler = mScheduler(app=self.app)
408 nums = [600, 300, 650, 120, 250, 36]
409 s = {'test_ticks%s' % i: {'schedule': mocked_schedule(False, j)}
410 for i, j in enumerate(nums)}
411 scheduler.update_from_dict(s)
412 assert scheduler.tick() == min(nums) - 0.010
413
414 def test_ticks_microseconds(self):
415 scheduler = mScheduler(app=self.app)
416
417 now_ts = 1514797200.2
418 now = datetime.utcfromtimestamp(now_ts)
419 schedule_half = schedule(timedelta(seconds=0.5), nowfun=lambda: now)
420 scheduler.add(name='half_second_schedule', schedule=schedule_half)
421
422 scheduler.tick()
423 # ensure those 0.2 seconds on now_ts don't get dropped
424 expected_time = now_ts + 0.5 - 0.010
425 assert scheduler._heap[0].time == expected_time
426
427 def test_ticks_schedule_change(self):
428 # initialise schedule and check heap is not initialized
429 scheduler = mScheduler(app=self.app)
430 assert scheduler._heap is None
431
432 # set initial schedule and check heap is updated
433 schedule_5 = schedule(5)
434 scheduler.add(name='test_schedule', schedule=schedule_5)
435 scheduler.tick()
436 assert scheduler._heap[0].entry.schedule == schedule_5
437
438 # update schedule and check heap is updated
439 schedule_10 = schedule(10)
440 scheduler.add(name='test_schedule', schedule=schedule(10))
441 scheduler.tick()
442 assert scheduler._heap[0].entry.schedule == schedule_10
443
444 def test_schedule_no_remain(self):
445 scheduler = mScheduler(app=self.app)
446 scheduler.add(name='test_schedule_no_remain',
447 schedule=mocked_schedule(False, None))
448 assert scheduler.tick() == scheduler.max_interval
449
450 def test_interface(self):
451 scheduler = mScheduler(app=self.app)
452 scheduler.sync()
453 scheduler.setup_schedule()
454 scheduler.close()
455
456 def test_merge_inplace(self):
457 a = mScheduler(app=self.app)
458 b = mScheduler(app=self.app)
459 a.update_from_dict({'foo': {'schedule': mocked_schedule(True, 10)},
460 'bar': {'schedule': mocked_schedule(True, 20)}})
461 b.update_from_dict({'bar': {'schedule': mocked_schedule(True, 40)},
462 'baz': {'schedule': mocked_schedule(True, 10)}})
463 a.merge_inplace(b.schedule)
464
465 assert 'foo' not in a.schedule
466 assert 'baz' in a.schedule
467 assert a.schedule['bar'].schedule._next_run_at == 40
468
469 def test_when(self):
470 now_time_utc = datetime(2000, 10, 10, 10, 10,
471 10, 10, tzinfo=ZoneInfo("UTC"))
472 now_time_casey = now_time_utc.astimezone(
473 ZoneInfo('Antarctica/Casey')
474 )
475 scheduler = mScheduler(app=self.app)
476 result_utc = scheduler._when(
477 mocked_schedule(True, 10, lambda: now_time_utc),
478 10
479 )
480 result_casey = scheduler._when(
481 mocked_schedule(True, 10, lambda: now_time_casey),
482 10
483 )
484 assert result_utc == result_casey
485
486 @patch('celery.beat.Scheduler._when', return_value=1)
487 def test_populate_heap(self, _when):
488 scheduler = mScheduler(app=self.app)
489 scheduler.update_from_dict(
490 {'foo': {'schedule': mocked_schedule(True, 10)}}
491 )
492 scheduler.populate_heap()
493 assert scheduler._heap == [event_t(1, 5, scheduler.schedule['foo'])]
494
495 def create_schedule_entry(self, schedule=None, args=(), kwargs={},
496 options={}, task=None):
497 entry = {
498 'name': 'celery.unittest.add',
499 'schedule': schedule,
500 'app': self.app,
501 'args': args,
502 'kwargs': kwargs,
503 'options': options,
504 'task': task
505 }
506 return beat.ScheduleEntry(**dict(entry))
507
508 def test_schedule_equal_schedule_vs_schedule_success(self):
509 scheduler = beat.Scheduler(app=self.app)
510 a = {'a': self.create_schedule_entry(schedule=schedule(5))}
511 b = {'a': self.create_schedule_entry(schedule=schedule(5))}
512 assert scheduler.schedules_equal(a, b)
513
514 def test_schedule_equal_schedule_vs_schedule_fail(self):
515 scheduler = beat.Scheduler(app=self.app)
516 a = {'a': self.create_schedule_entry(schedule=schedule(5))}
517 b = {'a': self.create_schedule_entry(schedule=schedule(10))}
518 assert not scheduler.schedules_equal(a, b)
519
520 def test_schedule_equal_crontab_vs_crontab_success(self):
521 scheduler = beat.Scheduler(app=self.app)
522 a = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
523 b = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
524 assert scheduler.schedules_equal(a, b)
525
526 def test_schedule_equal_crontab_vs_crontab_fail(self):
527 scheduler = beat.Scheduler(app=self.app)
528 a = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
529 b = {'a': self.create_schedule_entry(schedule=crontab(minute=10))}
530 assert not scheduler.schedules_equal(a, b)
531
532 def test_schedule_equal_crontab_vs_schedule_fail(self):
533 scheduler = beat.Scheduler(app=self.app)
534 a = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
535 b = {'a': self.create_schedule_entry(schedule=schedule(5))}
536 assert not scheduler.schedules_equal(a, b)
537
538 def test_schedule_equal_different_key_fail(self):
539 scheduler = beat.Scheduler(app=self.app)
540 a = {'a': self.create_schedule_entry(schedule=schedule(5))}
541 b = {'b': self.create_schedule_entry(schedule=schedule(5))}
542 assert not scheduler.schedules_equal(a, b)
543
544 def test_schedule_equal_args_vs_args_success(self):
545 scheduler = beat.Scheduler(app=self.app)
546 a = {'a': self.create_schedule_entry(args='a')}
547 b = {'a': self.create_schedule_entry(args='a')}
548 assert scheduler.schedules_equal(a, b)
549
550 def test_schedule_equal_args_vs_args_fail(self):
551 scheduler = beat.Scheduler(app=self.app)
552 a = {'a': self.create_schedule_entry(args='a')}
553 b = {'a': self.create_schedule_entry(args='b')}
554 assert not scheduler.schedules_equal(a, b)
555
556 def test_schedule_equal_kwargs_vs_kwargs_success(self):
557 scheduler = beat.Scheduler(app=self.app)
558 a = {'a': self.create_schedule_entry(kwargs={'a': 'a'})}
559 b = {'a': self.create_schedule_entry(kwargs={'a': 'a'})}
560 assert scheduler.schedules_equal(a, b)
561
562 def test_schedule_equal_kwargs_vs_kwargs_fail(self):
563 scheduler = beat.Scheduler(app=self.app)
564 a = {'a': self.create_schedule_entry(kwargs={'a': 'a'})}
565 b = {'a': self.create_schedule_entry(kwargs={'b': 'b'})}
566 assert not scheduler.schedules_equal(a, b)
567
568 def test_schedule_equal_options_vs_options_success(self):
569 scheduler = beat.Scheduler(app=self.app)
570 a = {'a': self.create_schedule_entry(options={'a': 'a'})}
571 b = {'a': self.create_schedule_entry(options={'a': 'a'})}
572 assert scheduler.schedules_equal(a, b)
573
574 def test_schedule_equal_options_vs_options_fail(self):
575 scheduler = beat.Scheduler(app=self.app)
576 a = {'a': self.create_schedule_entry(options={'a': 'a'})}
577 b = {'a': self.create_schedule_entry(options={'b': 'b'})}
578 assert not scheduler.schedules_equal(a, b)
579
580 def test_schedule_equal_task_vs_task_success(self):
581 scheduler = beat.Scheduler(app=self.app)
582 a = {'a': self.create_schedule_entry(task='a')}
583 b = {'a': self.create_schedule_entry(task='a')}
584 assert scheduler.schedules_equal(a, b)
585
586 def test_schedule_equal_task_vs_task_fail(self):
587 scheduler = beat.Scheduler(app=self.app)
588 a = {'a': self.create_schedule_entry(task='a')}
589 b = {'a': self.create_schedule_entry(task='b')}
590 assert not scheduler.schedules_equal(a, b)
591
592 def test_schedule_equal_none_entry_vs_entry(self):
593 scheduler = beat.Scheduler(app=self.app)
594 a = None
595 b = {'a': self.create_schedule_entry(task='b')}
596 assert not scheduler.schedules_equal(a, b)
597
598 def test_schedule_equal_entry_vs_none_entry(self):
599 scheduler = beat.Scheduler(app=self.app)
600 a = {'a': self.create_schedule_entry(task='a')}
601 b = None
602 assert not scheduler.schedules_equal(a, b)
603
604 def test_schedule_equal_none_entry_vs_none_entry(self):
605 scheduler = beat.Scheduler(app=self.app)
606 a = None
607 b = None
608 assert scheduler.schedules_equal(a, b)
609
610
611 def create_persistent_scheduler(shelv=None):
612 if shelv is None:
613 shelv = MockShelve()
614
615 class MockPersistentScheduler(beat.PersistentScheduler):
616 sh = shelv
617 persistence = Bunch(
618 open=lambda *a, **kw: shelv,
619 )
620 tick_raises_exit = False
621 shutdown_service = None
622
623 def tick(self):
624 if self.tick_raises_exit:
625 raise SystemExit()
626 if self.shutdown_service:
627 self.shutdown_service._is_shutdown.set()
628 return 0.0
629
630 return MockPersistentScheduler, shelv
631
632
633 def create_persistent_scheduler_w_call_logging(shelv=None):
634 if shelv is None:
635 shelv = MockShelve()
636
637 class MockPersistentScheduler(beat.PersistentScheduler):
638 sh = shelv
639 persistence = Bunch(
640 open=lambda *a, **kw: shelv,
641 )
642
643 def __init__(self, *args, **kwargs):
644 self.sent = []
645 super().__init__(*args, **kwargs)
646
647 def send_task(self, task=None, args=None, kwargs=None, **options):
648 self.sent.append({'task': task,
649 'args': args,
650 'kwargs': kwargs,
651 'options': options})
652 return self.app.AsyncResult(uuid())
653 return MockPersistentScheduler, shelv
654
655
656 class test_PersistentScheduler:
657
658 @patch('os.remove')
659 def test_remove_db(self, remove):
660 s = create_persistent_scheduler()[0](app=self.app,
661 schedule_filename='schedule')
662 s._remove_db()
663 remove.assert_has_calls(
664 [call('schedule' + suffix) for suffix in s.known_suffixes]
665 )
666 err = OSError()
667 err.errno = errno.ENOENT
668 remove.side_effect = err
669 s._remove_db()
670 err.errno = errno.EPERM
671 with pytest.raises(OSError):
672 s._remove_db()
673
674 def test_create_schedule_corrupted(self):
675 """
676 Test that any decoding errors that might happen when opening beat-schedule.db are caught
677 """
678 s = create_persistent_scheduler()[0](app=self.app,
679 schedule_filename='schedule')
680 s._store = MagicMock()
681 s._destroy_open_corrupted_schedule = Mock()
682 s._destroy_open_corrupted_schedule.return_value = MagicMock()
683
684 # self._store['entries'] will throw a KeyError
685 s._store.__getitem__.side_effect = KeyError()
686 # then, when _create_schedule tries to reset _store['entries'], throw another error
687 expected_error = UnicodeDecodeError("ascii", b"ordinal not in range(128)", 0, 0, "")
688 s._store.__setitem__.side_effect = expected_error
689
690 s._create_schedule()
691 s._destroy_open_corrupted_schedule.assert_called_with(expected_error)
692
693 def test_create_schedule_corrupted_dbm_error(self):
694 """
695 Test that any dbm.error that might happen when opening beat-schedule.db are caught
696 """
697 s = create_persistent_scheduler()[0](app=self.app,
698 schedule_filename='schedule')
699 s._store = MagicMock()
700 s._destroy_open_corrupted_schedule = Mock()
701 s._destroy_open_corrupted_schedule.return_value = MagicMock()
702
703 # self._store['entries'] = {} will throw a KeyError
704 s._store.__getitem__.side_effect = KeyError()
705 # then, when _create_schedule tries to reset _store['entries'], throw another error, specifically dbm.error
706 expected_error = dbm.error[0]()
707 s._store.__setitem__.side_effect = expected_error
708
709 s._create_schedule()
710 s._destroy_open_corrupted_schedule.assert_called_with(expected_error)
711
712 def test_create_schedule_corrupted_pickle_error(self):
713 """
714 Test that any UnpicklingError that might happen when opening beat-schedule.db is caught
715 """
716 s = create_persistent_scheduler()[0](app=self.app,
717 schedule_filename='schedule')
718 s._store = MagicMock()
719 s._destroy_open_corrupted_schedule = Mock()
720 s._destroy_open_corrupted_schedule.return_value = MagicMock()
721
722 # self._store['entries'] = {} will throw a pickle.UnpicklingError
723 s._store.__getitem__.side_effect = pickle.UnpicklingError("test")
724 # then, when _create_schedule tries to reset _store['entries'],
725 # throw another error, specifically pickle.UnpicklingError
726 expected_error = pickle.UnpicklingError("test")
727 s._store.__setitem__.side_effect = expected_error
728
729 s._create_schedule()
730 s._destroy_open_corrupted_schedule.assert_called_with(expected_error)
731
732 def test_create_schedule_missing_entries(self):
733 """
734 Test that if _create_schedule can't find the key "entries" in _store it will recreate it
735 """
736 s = create_persistent_scheduler()[0](app=self.app, schedule_filename="schedule")
737 s._store = MagicMock()
738
739 # self._store['entries'] will throw a KeyError
740 s._store.__getitem__.side_effect = TypeError()
741
742 s._create_schedule()
743 s._store.__setitem__.assert_called_with("entries", {})
744
745 def test_setup_schedule(self):
746 s = create_persistent_scheduler()[0](app=self.app,
747 schedule_filename='schedule')
748 opens = s.persistence.open = Mock()
749 s._remove_db = Mock()
750
751 def effect(*args, **kwargs):
752 if opens.call_count > 1:
753 return s.sh
754 raise OSError()
755 opens.side_effect = effect
756 s.setup_schedule()
757 s._remove_db.assert_called_with()
758
759 s._store = {'__version__': 1}
760 s.setup_schedule()
761
762 s._store.clear = Mock()
763 op = s.persistence.open = Mock()
764 op.return_value = s._store
765 s._store['tz'] = 'FUNKY'
766 s.setup_schedule()
767 op.assert_called_with(s.schedule_filename, writeback=True)
768 s._store.clear.assert_called_with()
769 s._store['utc_enabled'] = False
770 s._store.clear = Mock()
771 s.setup_schedule()
772 s._store.clear.assert_called_with()
773
774 def test_get_schedule(self):
775 s = create_persistent_scheduler()[0](
776 schedule_filename='schedule', app=self.app,
777 )
778 s._store = {'entries': {}}
779 s.schedule = {'foo': 'bar'}
780 assert s.schedule == {'foo': 'bar'}
781 assert s._store['entries'] == s.schedule
782
783 def test_run_all_due_tasks_after_restart(self):
784 scheduler_class, shelve = create_persistent_scheduler_w_call_logging()
785
786 shelve['tz'] = 'UTC'
787 shelve['utc_enabled'] = True
788 shelve['__version__'] = __version__
789 cur_seconds = 20
790
791 def now_func():
792 return datetime(2018, 1, 1, 1, 11, cur_seconds)
793 app_schedule = {
794 'first_missed': {'schedule': crontab(
795 minute='*/10', nowfun=now_func), 'task': 'first_missed'},
796 'second_missed': {'schedule': crontab(
797 minute='*/1', nowfun=now_func), 'task': 'second_missed'},
798 'non_missed': {'schedule': crontab(
799 minute='*/13', nowfun=now_func), 'task': 'non_missed'}
800 }
801 shelve['entries'] = {
802 'first_missed': beat.ScheduleEntry(
803 'first_missed', 'first_missed',
804 last_run_at=now_func() - timedelta(minutes=2),
805 total_run_count=10,
806 app=self.app,
807 schedule=app_schedule['first_missed']['schedule']),
808 'second_missed': beat.ScheduleEntry(
809 'second_missed', 'second_missed',
810 last_run_at=now_func() - timedelta(minutes=2),
811 total_run_count=10,
812 app=self.app,
813 schedule=app_schedule['second_missed']['schedule']),
814 'non_missed': beat.ScheduleEntry(
815 'non_missed', 'non_missed',
816 last_run_at=now_func() - timedelta(minutes=2),
817 total_run_count=10,
818 app=self.app,
819 schedule=app_schedule['non_missed']['schedule']),
820 }
821
822 self.app.conf.beat_schedule = app_schedule
823
824 scheduler = scheduler_class(self.app)
825
826 max_iter_number = 5
827 for i in range(max_iter_number):
828 delay = scheduler.tick()
829 if delay > 0:
830 break
831 assert {'first_missed', 'second_missed'} == {
832 item['task'] for item in scheduler.sent}
833 # ensure next call on the beginning of next min
834 assert abs(60 - cur_seconds - delay) < 1
835
836
837 class test_Service:
838
839 def get_service(self):
840 Scheduler, mock_shelve = create_persistent_scheduler()
841 return beat.Service(
842 app=self.app, scheduler_cls=Scheduler), mock_shelve
843
844 def test_pickleable(self):
845 s = beat.Service(app=self.app, scheduler_cls=Mock)
846 assert loads(dumps(s))
847
848 def test_start(self):
849 s, sh = self.get_service()
850 schedule = s.scheduler.schedule
851 assert isinstance(schedule, dict)
852 assert isinstance(s.scheduler, beat.Scheduler)
853 scheduled = list(schedule.keys())
854 for task_name in sh['entries'].keys():
855 assert task_name in scheduled
856
857 s.sync()
858 assert sh.closed
859 assert sh.synced
860 assert s._is_stopped.is_set()
861 s.sync()
862 s.stop(wait=False)
863 assert s._is_shutdown.is_set()
864 s.stop(wait=True)
865 assert s._is_shutdown.is_set()
866
867 p = s.scheduler._store
868 s.scheduler._store = None
869 try:
870 s.scheduler.sync()
871 finally:
872 s.scheduler._store = p
873
874 def test_start_embedded_process(self):
875 s, sh = self.get_service()
876 s._is_shutdown.set()
877 s.start(embedded_process=True)
878
879 def test_start_thread(self):
880 s, sh = self.get_service()
881 s._is_shutdown.set()
882 s.start(embedded_process=False)
883
884 def test_start_tick_raises_exit_error(self):
885 s, sh = self.get_service()
886 s.scheduler.tick_raises_exit = True
887 s.start()
888 assert s._is_shutdown.is_set()
889
890 def test_start_manages_one_tick_before_shutdown(self):
891 s, sh = self.get_service()
892 s.scheduler.shutdown_service = s
893 s.start()
894 assert s._is_shutdown.is_set()
895
896
897 class test_EmbeddedService:
898
899 def xxx_start_stop_process(self):
900 pytest.importorskip('_multiprocessing')
901 from billiard.process import Process
902
903 s = beat.EmbeddedService(self.app)
904 assert isinstance(s, Process)
905 assert isinstance(s.service, beat.Service)
906 s.service = MockService()
907
908 class _Popen:
909 terminated = False
910
911 def terminate(self):
912 self.terminated = True
913
914 with patch('celery.platforms.close_open_fds'):
915 s.run()
916 assert s.service.started
917
918 s._popen = _Popen()
919 s.stop()
920 assert s.service.stopped
921 assert s._popen.terminated
922
923 def test_start_stop_threaded(self):
924 s = beat.EmbeddedService(self.app, thread=True)
925 from threading import Thread
926 assert isinstance(s, Thread)
927 assert isinstance(s.service, beat.Service)
928 s.service = MockService()
929
930 s.run()
931 assert s.service.started
932
933 s.stop()
934 assert s.service.stopped
935
936
937 class test_schedule:
938
939 def test_maybe_make_aware(self):
940 x = schedule(10, app=self.app)
941 x.utc_enabled = True
942 d = x.maybe_make_aware(datetime.now(timezone.utc))
943 assert d.tzinfo
944 x.utc_enabled = False
945 d2 = x.maybe_make_aware(datetime.now(timezone.utc))
946 assert d2.tzinfo
947
948 def test_to_local(self):
949 x = schedule(10, app=self.app)
950 x.utc_enabled = True
951 d = x.to_local(datetime.now())
952 assert d.tzinfo is None
953 x.utc_enabled = False
954 d = x.to_local(datetime.now(timezone.utc))
955 assert d.tzinfo