Debian Codegraph @

t/unit/backends/test_asynchronous.py

raw
1 import logging
2 import os
3 import socket
4 import sys
5 import threading
6 import time
7 from unittest.mock import Mock, patch
8
9 import pytest
10 from vine import promise
11
12 from celery.backends.asynchronous import E_CELERY_RESTART_REQUIRED, BaseResultConsumer, greenletDrainer
13 from celery.backends.base import Backend
14 from celery.utils import cached_property
15
16 # ---- helpers ---------------------------------------------------------------
17
18
19 def _make_consumer(app, environment='default'):
20 """Create a BaseResultConsumer with a mocked drainer environment."""
21 with patch('celery.backends.asynchronous.detect_environment') as det:
22 det.return_value = environment
23 backend = Backend(app)
24 consumer = BaseResultConsumer(
25 backend, app, backend.accept,
26 pending_results={}, pending_messages={},
27 )
28 return consumer
29
30
31 # ---------------------------------------------------------------------------
32 # 1. Drainer (default / synchronous) -- no gevent / eventlet needed
33 # ---------------------------------------------------------------------------
34
35 class test_Drainer_without_greenlets:
36
37 # -- drain_events_until: normal flow ------------------------------------
38
39 def test_drain_fulfils_promise(self, app):
40 """Loop exits once the promise is fulfilled."""
41 consumer = _make_consumer(app)
42 drainer = consumer.drainer
43 p = promise()
44 calls = [0]
45
46 def wait(timeout=None):
47 calls[0] += 1
48 if calls[0] >= 3:
49 p('done')
50
51 for _ in drainer.drain_events_until(
52 p, wait=wait, interval=0.01, timeout=5):
53 pass
54
55 assert p.ready
56 assert calls[0] >= 3
57
58 def test_drain_calls_on_interval(self, app):
59 """on_interval callback is invoked every iteration."""
60 consumer = _make_consumer(app)
61 drainer = consumer.drainer
62 p = promise()
63 on_interval = Mock()
64 calls = [0]
65
66 def wait(timeout=None):
67 calls[0] += 1
68 if calls[0] >= 3:
69 p('done')
70
71 for _ in drainer.drain_events_until(
72 p, wait=wait, interval=0.01, timeout=5,
73 on_interval=on_interval):
74 pass
75
76 assert on_interval.call_count >= 2
77
78 def test_drain_raises_timeout(self, app):
79 """socket.timeout raised when total elapsed time exceeds *timeout*."""
80 consumer = _make_consumer(app)
81 drainer = consumer.drainer
82 p = promise()
83
84 def wait(timeout=None):
85 time.sleep(0.02)
86
87 with pytest.raises(socket.timeout):
88 for _ in drainer.drain_events_until(
89 p, wait=wait, interval=0.01, timeout=0.05):
90 pass
91
92 assert not p.ready
93
94 def test_drain_uses_result_consumer_drain_events_by_default(self, app):
95 """When *wait* is None, result_consumer.drain_events is used."""
96 consumer = _make_consumer(app)
97 drainer = consumer.drainer
98 p = promise()
99 calls = [0]
100
101 def mock_drain(timeout=None):
102 calls[0] += 1
103 if calls[0] >= 2:
104 p('done')
105
106 consumer.drain_events = mock_drain
107
108 for _ in drainer.drain_events_until(p, interval=0.01, timeout=5):
109 pass
110
111 assert p.ready
112 assert calls[0] >= 2
113
114 # -- drain_events_until: socket.timeout from wait -----------------------
115
116 def test_drain_swallows_socket_timeout_from_wait(self, app):
117 """socket.timeout raised inside wait() must be silently caught."""
118 consumer = _make_consumer(app)
119 drainer = consumer.drainer
120 p = promise()
121 calls = [0]
122
123 def wait(timeout=None):
124 calls[0] += 1
125 if calls[0] <= 2:
126 raise socket.timeout('idle')
127 p('done')
128
129 for _ in drainer.drain_events_until(
130 p, wait=wait, interval=0.01, timeout=5):
131 pass
132
133 assert p.ready
134
135 # -- drain_events_until: OSError from wait ------------------------------
136
137 def test_drain_catches_oserror_and_logs(self, app):
138 """OSError from wait() must be caught, logged, loop continues."""
139 consumer = _make_consumer(app)
140 drainer = consumer.drainer
141 p = promise()
142 calls = [0]
143
144 def wait(timeout=None):
145 calls[0] += 1
146 if calls[0] <= 2:
147 raise OSError('broker away')
148 p('done')
149
150 with patch.object(logging, 'warning') as mock_warn:
151 for _ in drainer.drain_events_until(
152 p, wait=wait, interval=0.01, timeout=5):
153 pass
154
155 assert p.ready
156 assert mock_warn.call_count >= 2
157
158 # -- wait_for -----------------------------------------------------------
159
160 def test_wait_for_calls_wait_with_timeout(self, app):
161 """Drainer.wait_for delegates to the wait callback."""
162 consumer = _make_consumer(app)
163 drainer = consumer.drainer
164 p = promise()
165 wait = Mock()
166 drainer.wait_for(p, wait, timeout=0.5)
167 wait.assert_called_once_with(timeout=0.5)
168
169
170 # ---------------------------------------------------------------------------
171 # 2. greenletDrainer -- tested synchronously (no real greenlet spawning)
172 # ---------------------------------------------------------------------------
173
174 class test_greenletDrainer:
175
176 def _make_greenlet_drainer(self, app):
177 consumer = _make_consumer(app)
178 drainer = greenletDrainer(consumer)
179 return drainer
180
181 # -- run: normal stop ---------------------------------------------------
182
183 def test_run_exits_when_stopped(self, app):
184 """run() exits cleanly when _stopped is set."""
185 drainer = self._make_greenlet_drainer(app)
186 calls = [0]
187
188 def drain(timeout=None):
189 calls[0] += 1
190 if calls[0] >= 3:
191 drainer._stopped.set()
192
193 drainer.result_consumer.drain_events = Mock(side_effect=drain)
194 drainer.run()
195
196 assert drainer._shutdown.is_set()
197 assert drainer._exc is None
198
199 # -- run: socket.timeout is swallowed -----------------------------------
200
201 def test_run_swallows_socket_timeout(self, app):
202 """socket.timeout inside run() must be silently caught."""
203 drainer = self._make_greenlet_drainer(app)
204 calls = [0]
205
206 def drain(timeout=None):
207 calls[0] += 1
208 if calls[0] <= 3:
209 raise socket.timeout('idle')
210 drainer._stopped.set()
211
212 drainer.result_consumer.drain_events = Mock(side_effect=drain)
213 drainer.run()
214
215 assert calls[0] >= 4
216 assert drainer._exc is None
217
218 # -- run: OSError is caught and logged ----------------------------------
219
220 def test_run_catches_oserror_and_logs(self, app):
221 """OSError in run() must be caught/logged, loop continues."""
222 drainer = self._make_greenlet_drainer(app)
223 calls = [0]
224
225 def drain(timeout=None):
226 calls[0] += 1
227 if calls[0] <= 3:
228 raise OSError('connection reset')
229 drainer._stopped.set()
230
231 drainer.result_consumer.drain_events = Mock(side_effect=drain)
232
233 with patch.object(logging, 'warning') as mock_warn, \
234 patch('celery.backends.asynchronous.time.sleep') as mock_sleep:
235 drainer.run()
236
237 assert calls[0] >= 4
238 assert mock_warn.call_count >= 3
239 # backoff sleep should have been called once per OSError
240 assert mock_sleep.call_count >= 3
241 assert drainer._exc is None
242
243 # -- run: unexpected Exception is stored and re-raised ------------------
244
245 def test_run_stores_and_reraises_unexpected_exception(self, app):
246 """Non-OSError / non-timeout exceptions must propagate and be stored."""
247 drainer = self._make_greenlet_drainer(app)
248
249 def drain(timeout=None):
250 raise RuntimeError('unexpected')
251
252 drainer.result_consumer.drain_events = Mock(side_effect=drain)
253
254 with pytest.raises(RuntimeError, match='unexpected'):
255 drainer.run()
256
257 assert drainer._exc is not None
258 assert drainer._shutdown.is_set()
259
260 # -- _ensure_not_shut_down ----------------------------------------------
261
262 def test_ensure_not_shut_down_raises_stored_exc(self, app):
263 """If run() failed, _ensure_not_shut_down re-raises the exception."""
264 drainer = self._make_greenlet_drainer(app)
265 drainer._shutdown.set()
266 drainer._exc = ValueError('boom')
267
268 with pytest.raises(ValueError, match='boom'):
269 drainer._ensure_not_shut_down()
270
271 def test_ensure_not_shut_down_raises_restart_msg(self, app):
272 """If stopped cleanly, _ensure_not_shut_down raises restart msg."""
273 drainer = self._make_greenlet_drainer(app)
274 drainer._shutdown.set()
275 drainer._exc = None
276
277 with pytest.raises(Exception, match=E_CELERY_RESTART_REQUIRED):
278 drainer._ensure_not_shut_down()
279
280 def test_ensure_not_shut_down_noop_when_running(self, app):
281 """No-op when _shutdown is not set."""
282 drainer = self._make_greenlet_drainer(app)
283 # Should not raise
284 drainer._ensure_not_shut_down()
285
286 # -- start / stop -------------------------------------------------------
287
288 def test_start_spawns_and_waits(self, app):
289 """start() calls spawn(run) and waits for _started."""
290 drainer = self._make_greenlet_drainer(app)
291
292 def fake_spawn(func):
293 # Run synchronously with immediate stop.
294 drainer._stopped.set()
295 func()
296
297 drainer.spawn = fake_spawn
298 drainer.result_consumer.drain_events = Mock(
299 side_effect=lambda timeout=None: drainer._stopped.set()
300 )
301 drainer.start()
302
303 assert drainer._started.is_set()
304 assert drainer._shutdown.is_set()
305
306 def test_start_raises_if_already_shut_down(self, app):
307 """start() raises if drainer already completed."""
308 drainer = self._make_greenlet_drainer(app)
309 drainer._shutdown.set()
310
311 with pytest.raises(Exception, match=E_CELERY_RESTART_REQUIRED):
312 drainer.start()
313
314 def test_stop_signals_and_waits(self, app):
315 """stop() sets _stopped and waits for _shutdown."""
316 drainer = self._make_greenlet_drainer(app)
317 # Pre-set _shutdown so wait returns immediately.
318 drainer._shutdown.set()
319 drainer.stop()
320
321 assert drainer._stopped.is_set()
322
323
324 # ---------------------------------------------------------------------------
325 # 3. Integration tests with real greenlet runtimes (gevent + eventlet)
326 # ---------------------------------------------------------------------------
327
328
329 @pytest.fixture(autouse=True)
330 def setup_eventlet():
331 os.environ.update(EVENTLET_NO_GREENDNS='yes')
332
333
334 class DrainerTests:
335 """
336 Base test class for the Default / Gevent / Eventlet drainers.
337 """
338
339 interval = 0.1 # Check every tenth of a second
340 MAX_TIMEOUT = 10 # Specify a max timeout so it doesn't run forever
341
342 def get_drainer(self, environment):
343 with patch('celery.backends.asynchronous.detect_environment') as d:
344 d.return_value = environment
345 backend = Backend(self.app)
346 consumer = BaseResultConsumer(backend, self.app, backend.accept,
347 pending_results={},
348 pending_messages={})
349 consumer.drain_events = Mock(side_effect=self.result_consumer_drain_events)
350 return consumer.drainer
351
352 @pytest.fixture(autouse=True)
353 def setup_drainer(self):
354 raise NotImplementedError
355
356 @cached_property
357 def sleep(self):
358 """
359 Sleep on the event loop.
360 """
361 raise NotImplementedError
362
363 def schedule_thread(self, thread):
364 """
365 Set up a thread that runs on the event loop.
366 """
367 raise NotImplementedError
368
369 def teardown_thread(self, thread):
370 """
371 Wait for a thread to stop.
372 """
373 raise NotImplementedError
374
375 def result_consumer_drain_events(self, timeout=None):
376 """
377 Subclasses should override this method to define the behavior of
378 drainer.result_consumer.drain_events.
379 """
380 raise NotImplementedError
381
382 def test_drain_checks_on_interval(self):
383 p = promise()
384
385 def fulfill_promise_thread():
386 self.sleep(self.interval * 2)
387 p('done')
388
389 fulfill_thread = self.schedule_thread(fulfill_promise_thread)
390
391 on_interval = Mock()
392 for _ in self.drainer.drain_events_until(p,
393 on_interval=on_interval,
394 interval=self.interval,
395 timeout=self.MAX_TIMEOUT):
396 pass
397
398 self.teardown_thread(fulfill_thread)
399
400 assert p.ready, 'Should have terminated with promise being ready'
401 assert on_interval.call_count < 20, 'Should have limited number of calls to on_interval'
402
403 def test_drain_does_not_block_event_loop(self):
404 """
405 This test makes sure that other greenlets can still operate while drain_events_until is
406 running.
407 """
408 p = promise()
409 liveness_mock = Mock()
410
411 def fulfill_promise_thread():
412 self.sleep(self.interval * 2)
413 p('done')
414
415 def liveness_thread():
416 while 1:
417 if p.ready:
418 return
419 self.sleep(self.interval / 10)
420 liveness_mock()
421
422 fulfill_thread = self.schedule_thread(fulfill_promise_thread)
423 liveness_thread = self.schedule_thread(liveness_thread)
424
425 on_interval = Mock()
426 for _ in self.drainer.drain_events_until(p,
427 on_interval=on_interval,
428 interval=self.interval,
429 timeout=self.MAX_TIMEOUT):
430 pass
431
432 self.teardown_thread(fulfill_thread)
433 self.teardown_thread(liveness_thread)
434
435 assert p.ready, 'Should have terminated with promise being ready'
436 assert on_interval.call_count <= liveness_mock.call_count, \
437 'Should have served liveness_mock while waiting for event'
438
439 def test_drain_timeout(self):
440 p = promise()
441 on_interval = Mock()
442
443 with pytest.raises(socket.timeout):
444 for _ in self.drainer.drain_events_until(p,
445 on_interval=on_interval,
446 interval=self.interval,
447 timeout=self.interval * 5):
448 pass
449
450 assert not p.ready, 'Promise should remain un-fulfilled'
451 assert on_interval.call_count < 20, 'Should have limited number of calls to on_interval'
452
453 def test_drain_catches_and_logs_oserror(self):
454 p = promise()
455
456 def fulfill():
457 self.sleep(self.interval * 2)
458 p('done')
459
460 t = self.schedule_thread(fulfill)
461
462 state = {'n': 0}
463
464 def flaky(*args, **kwargs):
465 state['n'] += 1
466 if state['n'] == 1:
467 raise OSError('simulated broker restart')
468 # Yield to hub so the promise thread can run.
469 self.result_consumer_drain_events(
470 timeout=kwargs.get('timeout', None),
471 )
472
473 with patch.object(
474 self.drainer.result_consumer, 'drain_events',
475 side_effect=flaky,
476 ):
477 with patch('logging.warning') as mock_warn:
478 for _ in self.drainer.drain_events_until(
479 p, interval=self.interval,
480 timeout=self.MAX_TIMEOUT):
481 pass
482
483 self.teardown_thread(t)
484 assert p.ready
485 assert mock_warn.called
486
487
488 class GreenletDrainerTests(DrainerTests):
489 def test_drain_raises_when_greenlet_already_exited(self):
490 with patch.object(self.drainer.result_consumer, 'drain_events', side_effect=Exception("Test Exception")):
491 thread = self.schedule_thread(self.drainer.run)
492
493 with pytest.raises(Exception, match="Test Exception"):
494 p = promise()
495
496 for _ in self.drainer.drain_events_until(p, interval=self.interval):
497 pass
498
499 self.teardown_thread(thread)
500
501 def test_drain_raises_while_waiting_on_exiting_greenlet(self):
502 with patch.object(self.drainer.result_consumer, 'drain_events', side_effect=Exception("Test Exception")):
503 with pytest.raises(Exception, match="Test Exception"):
504 p = promise()
505
506 for _ in self.drainer.drain_events_until(p, interval=self.interval):
507 pass
508
509 def test_start_raises_if_previous_error_in_run(self):
510 with patch.object(self.drainer.result_consumer, 'drain_events', side_effect=Exception("Test Exception")):
511 thread = self.schedule_thread(self.drainer.run)
512
513 with pytest.raises(Exception, match="Test Exception"):
514 self.drainer.start()
515
516 self.teardown_thread(thread)
517
518 def test_start_raises_if_drainer_already_stopped(self):
519 with patch.object(self.drainer.result_consumer, 'drain_events', side_effect=lambda **_: self.sleep(0)):
520 thread = self.schedule_thread(self.drainer.run)
521 self.drainer.stop()
522
523 with pytest.raises(Exception, match=E_CELERY_RESTART_REQUIRED):
524 self.drainer.start()
525
526 self.teardown_thread(thread)
527
528 def test_run_catches_and_logs_oserror(self):
529 def flaky(*args, **kwargs):
530 if not hasattr(flaky, '_raised'):
531 flaky._raised = True
532 raise OSError('simulated broker restart in greenlet')
533 self.drainer._stopped.set()
534
535 with patch.object(
536 self.drainer.result_consumer, 'drain_events',
537 side_effect=flaky,
538 ):
539 with patch('logging.warning') as mock_warn:
540 t = self.schedule_thread(self.drainer.run)
541 self.teardown_thread(t)
542
543 assert mock_warn.called
544 assert 'connection error during drain_events' in mock_warn.call_args[0][0]
545 assert self.drainer._exc is None
546
547
548 @pytest.mark.skipif(
549 sys.platform == "win32",
550 reason="hangs forever intermittently on windows"
551 )
552 class test_EventletDrainer(GreenletDrainerTests):
553 @pytest.fixture(autouse=True)
554 def setup_drainer(self):
555 pytest.importorskip('eventlet')
556 self.drainer = self.get_drainer('eventlet')
557
558 @cached_property
559 def sleep(self):
560 from eventlet import sleep
561 return sleep
562
563 def result_consumer_drain_events(self, timeout=None):
564 import eventlet
565
566 # `drain_events` of asynchronous backends with pubsub have to sleep
567 # while waiting events for not more then `interval` timeout,
568 # but events may coming sooner
569 eventlet.sleep(timeout/10)
570
571 def schedule_thread(self, thread):
572 import eventlet
573 g = eventlet.spawn(thread)
574 eventlet.sleep(0)
575 return g
576
577 def teardown_thread(self, thread):
578 try:
579 # eventlet's wait() propagates any errors on the green thread, unlike
580 # similar methods in gevent or python's threading library
581 thread.wait()
582 except Exception:
583 pass
584
585
586 class test_Drainer(DrainerTests):
587 @pytest.fixture(autouse=True)
588 def setup_drainer(self):
589 self.drainer = self.get_drainer('default')
590
591 @cached_property
592 def sleep(self):
593 from time import sleep
594 return sleep
595
596 def result_consumer_drain_events(self, timeout=None):
597 time.sleep(timeout)
598
599 def schedule_thread(self, thread):
600 t = threading.Thread(target=thread)
601 t.start()
602 return t
603
604 def teardown_thread(self, thread):
605 thread.join()
606
607
608 class test_GeventDrainer(GreenletDrainerTests):
609 @pytest.fixture(autouse=True)
610 def setup_drainer(self):
611 pytest.importorskip('gevent')
612 self.drainer = self.get_drainer('gevent')
613
614 @cached_property
615 def sleep(self):
616 from gevent import sleep
617 return sleep
618
619 def result_consumer_drain_events(self, timeout=None):
620 import gevent
621
622 # `drain_events` of asynchronous backends with pubsub have to sleep
623 # while waiting events for not more then `interval` timeout,
624 # but events may coming sooner
625 gevent.sleep(timeout/10)
626
627 def schedule_thread(self, thread):
628 import gevent
629 g = gevent.spawn(thread)
630 gevent.sleep(0)
631 return g
632
633 def teardown_thread(self, thread):
634 import gevent
635 gevent.wait([thread])
636
637
638 class test_BaseResultConsumer_reconnect:
639
640 def _make_consumer(self, app):
641 return _make_consumer(app)
642
643 def test_reconnect_on_error_no_exception_passes_through(self, app):
644 consumer = self._make_consumer(app)
645 result = []
646 with consumer.reconnect_on_error():
647 result.append('ok')
648 assert result == ['ok']
649
650 def test_reconnect_on_error_ignores_non_connection_error(self, app):
651 consumer = self._make_consumer(app)
652 with pytest.raises(ValueError):
653 with consumer.reconnect_on_error():
654 raise ValueError('unrelated')
655
656 def test_reconnect_on_error_default_connection_errors_empty(self, app):
657 consumer = self._make_consumer(app)
658 assert consumer._connection_errors == ()
659
660 class FakeConnError(Exception):
661 pass
662
663 with pytest.raises(FakeConnError):
664 with consumer.reconnect_on_error():
665 raise FakeConnError('dropped')
666
667 def test_reconnect_on_error_calls_reconnect_on_connection_error(self, app):
668 consumer = self._make_consumer(app)
669
670 class FakeConnError(Exception):
671 pass
672
673 consumer._connection_errors = (FakeConnError,)
674 consumer._reconnect = Mock()
675
676 with consumer.reconnect_on_error():
677 raise FakeConnError('dropped')
678
679 consumer._reconnect.assert_called_once_with()
680
681 def test_reconnect_on_error_raises_runtime_when_reconnect_also_fails(self, app):
682 consumer = self._make_consumer(app)
683
684 class FakeConnError(Exception):
685 pass
686
687 consumer._connection_errors = (FakeConnError,)
688 consumer._reconnect = Mock(side_effect=FakeConnError('still down'))
689
690 with pytest.raises(RuntimeError, match='Retry limit exceeded'):
691 with consumer.reconnect_on_error():
692 raise FakeConnError('dropped')
693
694 def test_reconnect_on_error_runtime_chained_from_connection_error(self, app):
695 consumer = self._make_consumer(app)
696
697 class FakeConnError(Exception):
698 pass
699
700 consumer._connection_errors = (FakeConnError,)
701 original = FakeConnError('still down')
702 consumer._reconnect = Mock(side_effect=original)
703
704 with pytest.raises(RuntimeError) as exc_info:
705 with consumer.reconnect_on_error():
706 raise FakeConnError('dropped')
707
708 assert exc_info.value.__cause__ is original
709
710 def test_reconnect_base_implementation_is_noop(self, app):
711 consumer = self._make_consumer(app)
712
713 assert consumer._reconnect() is None