Debian Codegraph @

t/integration/test_tasks.py

raw
1 import logging
2 import platform
3 import time
4 from datetime import datetime, timedelta, timezone
5 from uuid import uuid4
6
7 import billiard as multiprocessing
8 import pytest
9
10 import celery
11 from celery import chain, chord, group
12 from celery.canvas import StampingVisitor
13 from celery.signals import task_received
14 from celery.utils.serialization import UnpickleableExceptionWrapper
15 from celery.worker import state as worker_state
16
17 from .conftest import TEST_BACKEND, get_active_redis_channels, get_redis_connection
18 from .tasks import (ClassBasedAutoRetryTask, ExpectedException, add, add_ignore_result, add_not_typed, add_pydantic,
19 add_pydantic_string_annotations, fail, fail_unpickleable, print_unicode, retry, retry_once,
20 retry_once_headers, retry_once_priority, retry_unpickleable, return_properties,
21 second_order_replace1, sleeping, soft_time_limit_must_exceed_time_limit)
22
23 TIMEOUT = 10
24
25 _flaky = pytest.mark.flaky(reruns=5, reruns_delay=2)
26 _timeout = pytest.mark.timeout(timeout=300)
27
28
29 def flaky(fn):
30 return _timeout(_flaky(fn))
31
32
33 def set_multiprocessing_start_method():
34 """Set multiprocessing start method to 'fork' if not on Linux."""
35 if platform.system() != "Linux":
36 try:
37 multiprocessing.set_start_method("fork")
38 except RuntimeError:
39 # The method is already set
40 pass
41
42
43 class test_class_based_tasks:
44
45 @flaky
46 def test_class_based_task_retried(self, celery_session_app,
47 celery_session_worker):
48 task = ClassBasedAutoRetryTask()
49 celery_session_app.register_task(task)
50 res = task.delay()
51 assert res.get(timeout=TIMEOUT) == 1
52
53
54 def _producer(j):
55 """Single producer helper function"""
56 results = []
57 for i in range(20):
58 results.append([i + j, add.delay(i, j)])
59 for expected, result in results:
60 value = result.get(timeout=10)
61 assert value == expected
62 assert result.status == 'SUCCESS'
63 assert result.ready() is True
64 assert result.successful() is True
65 return j
66
67
68 class test_tasks:
69
70 def test_simple_call(self):
71 """Tests direct simple call of task"""
72 assert add(1, 1) == 2
73 assert add(1, 1, z=1) == 3
74
75 @flaky
76 def test_basic_task(self, manager):
77 """Tests basic task call"""
78 results = []
79 # Tests calling task only with args
80 for i in range(10):
81 results.append([i + i, add.delay(i, i)])
82 for expected, result in results:
83 value = result.get(timeout=10)
84 assert value == expected
85 assert result.status == 'SUCCESS'
86 assert result.ready() is True
87 assert result.successful() is True
88
89 results = []
90 # Tests calling task with args and kwargs
91 for i in range(10):
92 results.append([3*i, add.delay(i, i, z=i)])
93 for expected, result in results:
94 value = result.get(timeout=10)
95 assert value == expected
96 assert result.status == 'SUCCESS'
97 assert result.ready() is True
98 assert result.successful() is True
99
100 @flaky
101 @pytest.mark.skip(reason="Broken test")
102 def test_multiprocess_producer(self, manager):
103 """Testing multiple processes calling tasks."""
104 set_multiprocessing_start_method()
105
106 from multiprocessing import Pool
107 pool = Pool(20)
108 ret = pool.map(_producer, range(120))
109 assert list(ret) == list(range(120))
110
111 @flaky
112 @pytest.mark.skip(reason="Broken test")
113 def test_multithread_producer(self, manager):
114 """Testing multiple threads calling tasks."""
115 set_multiprocessing_start_method()
116
117 from multiprocessing.pool import ThreadPool
118 pool = ThreadPool(20)
119 ret = pool.map(_producer, range(120))
120 assert list(ret) == list(range(120))
121
122 @flaky
123 def test_ignore_result(self, manager):
124 """Testing calling task with ignoring results."""
125 result = add.apply_async((1, 2), ignore_result=True)
126 assert result.get() is None
127 # We wait since it takes a bit of time for the result to be
128 # persisted in the result backend.
129 time.sleep(1)
130 assert result.result is None
131
132 @flaky
133 def test_pydantic_annotations(self, manager):
134 """Tests task call with Pydantic model serialization."""
135 results = []
136 # Tests calling task only with args
137 for i in range(10):
138 results.append([i + i, add_pydantic.delay({'x': i, 'y': i})])
139 for expected, result in results:
140 value = result.get(timeout=10)
141 assert value == {'result': expected}
142 assert result.status == 'SUCCESS'
143 assert result.ready() is True
144 assert result.successful() is True
145
146 @flaky
147 def test_pydantic_string_annotations(self, manager):
148 """Tests task call with string-annotated Pydantic model."""
149 results = []
150 # Tests calling task only with args
151 for i in range(10):
152 results.append([i + i, add_pydantic_string_annotations.delay({'x': i, 'y': i})])
153 for expected, result in results:
154 value = result.get(timeout=10)
155 assert value == {'result': expected}
156 assert result.status == 'SUCCESS'
157 assert result.ready() is True
158 assert result.successful() is True
159
160 @flaky
161 def test_timeout(self, manager):
162 """Testing timeout of getting results from tasks."""
163 result = sleeping.delay(10)
164 with pytest.raises(celery.exceptions.TimeoutError):
165 result.get(timeout=5)
166
167 @pytest.mark.timeout(60)
168 @flaky
169 def test_expired(self, manager):
170 """Testing expiration of task."""
171 # Fill the queue with tasks which took > 1 sec to process
172 for _ in range(4):
173 sleeping.delay(2)
174 # Execute task with expiration = 1 sec
175 result = add.apply_async((1, 1), expires=1)
176 with pytest.raises(celery.exceptions.TaskRevokedError):
177 result.get()
178 assert result.status == 'REVOKED'
179 assert result.ready() is True
180 assert result.failed() is False
181 assert result.successful() is False
182
183 # Fill the queue with tasks which took > 1 sec to process
184 for _ in range(4):
185 sleeping.delay(2)
186 # Execute task with expiration at now + 1 sec
187 result = add.apply_async((1, 1), expires=datetime.now(timezone.utc) + timedelta(seconds=1))
188 with pytest.raises(celery.exceptions.TaskRevokedError):
189 result.get()
190 assert result.status == 'REVOKED'
191 assert result.ready() is True
192 assert result.failed() is False
193 assert result.successful() is False
194
195 @flaky
196 def test_eta(self, manager):
197 """Tests tasks scheduled at some point in future."""
198 start = time.perf_counter()
199 # Schedule task to be executed in 3 seconds
200 result = add.apply_async((1, 1), countdown=3)
201 time.sleep(1)
202 assert result.status == 'PENDING'
203 assert result.ready() is False
204 assert result.get() == 2
205 end = time.perf_counter()
206 assert result.status == 'SUCCESS'
207 assert result.ready() is True
208 # Difference between calling the task and result must be bigger than 3 secs
209 assert (end - start) > 3
210
211 start = time.perf_counter()
212 # Schedule task to be executed at time now + 3 seconds
213 result = add.apply_async((2, 2), eta=datetime.now(timezone.utc) + timedelta(seconds=3))
214 time.sleep(1)
215 assert result.status == 'PENDING'
216 assert result.ready() is False
217 assert result.get() == 4
218 end = time.perf_counter()
219 assert result.status == 'SUCCESS'
220 assert result.ready() is True
221 # Difference between calling the task and result must be bigger than 3 secs
222 assert (end - start) > 3
223
224 @flaky
225 def test_fail(self, manager):
226 """Tests that the failing task propagates back correct exception."""
227 result = fail.delay()
228 with pytest.raises(ExpectedException):
229 result.get(timeout=5)
230 assert result.status == 'FAILURE'
231 assert result.ready() is True
232 assert result.failed() is True
233 assert result.successful() is False
234
235 @flaky
236 def test_revoked(self, manager):
237 """Testing revoking of task"""
238 # Fill the queue with tasks to fill the queue
239 for _ in range(4):
240 sleeping.delay(2)
241 # Execute task and revoke it
242 result = add.apply_async((1, 1))
243 result.revoke()
244 with pytest.raises(celery.exceptions.TaskRevokedError):
245 result.get()
246 assert result.status == 'REVOKED'
247 assert result.ready() is True
248 assert result.failed() is False
249 assert result.successful() is False
250
251 def test_revoked_by_headers_simple_canvas(self, manager):
252 """Testing revoking of task using a stamped header"""
253 target_monitoring_id = uuid4().hex
254
255 class MonitoringIdStampingVisitor(StampingVisitor):
256 def on_signature(self, sig, **headers) -> dict:
257 return {'monitoring_id': target_monitoring_id}
258
259 for monitoring_id in [target_monitoring_id, uuid4().hex, 4242, None]:
260 stamped_task = add.si(1, 1)
261 stamped_task.stamp(visitor=MonitoringIdStampingVisitor())
262 result = stamped_task.freeze()
263 result.revoke_by_stamped_headers(headers={'monitoring_id': [monitoring_id]})
264 stamped_task.apply_async()
265 if monitoring_id == target_monitoring_id:
266 with pytest.raises(celery.exceptions.TaskRevokedError):
267 result.get()
268 assert result.status == 'REVOKED'
269 assert result.ready() is True
270 assert result.failed() is False
271 assert result.successful() is False
272 else:
273 assert result.get() == 2
274 assert result.status == 'SUCCESS'
275 assert result.ready() is True
276 assert result.failed() is False
277 assert result.successful() is True
278
279 # Clear the set of revoked stamps in the worker state.
280 # This step is performed in each iteration of the loop to ensure that only tasks
281 # stamped with a specific monitoring ID will be revoked.
282 # For subsequent iterations with different monitoring IDs, the revoked stamps will
283 # not match the task's stamps, allowing those tasks to proceed successfully.
284 worker_state.revoked_stamps.clear()
285
286 @pytest.mark.timeout(20)
287 @pytest.mark.flaky(reruns=2)
288 def test_revoked_by_headers_complex_canvas(self, manager, subtests):
289 """Testing revoking of task using a stamped header"""
290 try:
291 manager.app.backend.ensure_chords_allowed()
292 except NotImplementedError as e:
293 raise pytest.skip(e.args[0])
294
295 for monitoring_id in ["4242", [1234, uuid4().hex]]:
296
297 # Try to purge the queue before we start
298 # to attempt to avoid interference from other tests
299 manager.wait_until_idle()
300
301 target_monitoring_id = isinstance(monitoring_id, list) and monitoring_id[0] or monitoring_id
302
303 class MonitoringIdStampingVisitor(StampingVisitor):
304 def on_signature(self, sig, **headers) -> dict:
305 return {'monitoring_id': target_monitoring_id, 'stamped_headers': ['monitoring_id']}
306
307 stamped_task = sleeping.si(4)
308 stamped_task.stamp(visitor=MonitoringIdStampingVisitor())
309 result = stamped_task.freeze()
310
311 canvas = [
312 group([stamped_task]),
313 chord(group([stamped_task]), sleeping.si(2)),
314 chord(group([sleeping.si(2)]), stamped_task),
315 chain(stamped_task),
316 group([sleeping.si(2), stamped_task, sleeping.si(2)]),
317 chord([sleeping.si(2), stamped_task], sleeping.si(2)),
318 chord([sleeping.si(2), sleeping.si(2)], stamped_task),
319 chain(sleeping.si(2), stamped_task),
320 chain(sleeping.si(2), group([sleeping.si(2), stamped_task, sleeping.si(2)])),
321 chain(sleeping.si(2), group([sleeping.si(2), stamped_task]), sleeping.si(2)),
322 chain(sleeping.si(2), group([sleeping.si(2), sleeping.si(2)]), stamped_task),
323 ]
324
325 result.revoke_by_stamped_headers(headers={'monitoring_id': monitoring_id})
326
327 for sig in canvas:
328 sig_result = sig.apply_async()
329 with subtests.test(msg='Testing if task was revoked'):
330 with pytest.raises(celery.exceptions.TaskRevokedError):
331 sig_result.get()
332 assert result.status == 'REVOKED'
333 assert result.ready() is True
334 assert result.failed() is False
335 assert result.successful() is False
336 worker_state.revoked_stamps.clear()
337
338 @flaky
339 def test_revoke_by_stamped_headers_no_match(self, manager):
340 response = manager.app.control.revoke_by_stamped_headers(
341 {"myheader": ["myvalue"]},
342 terminate=False,
343 reply=True,
344 )
345
346 expected_response = "headers {'myheader': ['myvalue']} flagged as revoked, but not terminated"
347 assert response[0][list(response[0].keys())[0]]["ok"] == expected_response
348
349 @flaky
350 def test_wrong_arguments(self, manager):
351 """Tests that proper exceptions are raised when task is called with wrong arguments."""
352 with pytest.raises(TypeError):
353 add(5)
354
355 with pytest.raises(TypeError):
356 add(5, 5, wrong_arg=5)
357
358 with pytest.raises(TypeError):
359 add.delay(5)
360
361 with pytest.raises(TypeError):
362 add.delay(5, wrong_arg=5)
363
364 # Tasks with typing=False are not checked but execution should fail
365 result = add_not_typed.delay(5)
366 with pytest.raises(TypeError):
367 result.get(timeout=5)
368 assert result.status == 'FAILURE'
369
370 result = add_not_typed.delay(5, wrong_arg=5)
371 with pytest.raises(TypeError):
372 result.get(timeout=5)
373 assert result.status == 'FAILURE'
374
375 @pytest.mark.xfail(
376 condition=TEST_BACKEND == "rpc",
377 reason="Retry failed on rpc backend",
378 strict=False,
379 )
380 def test_retry(self, manager):
381 """Tests retrying of task."""
382 # Tests when max. retries is reached
383 result = retry.delay()
384
385 tik = time.monotonic()
386 while time.monotonic() < tik + 5:
387 status = result.status
388 if status != 'PENDING':
389 break
390 time.sleep(0.1)
391 else:
392 raise AssertionError("Timeout while waiting for the task to be retried")
393 assert status == 'RETRY'
394 with pytest.raises(ExpectedException):
395 result.get()
396 assert result.status == 'FAILURE'
397
398 # Tests when task is retried but after returns correct result
399 result = retry.delay(return_value='bar')
400
401 tik = time.monotonic()
402 while time.monotonic() < tik + 5:
403 status = result.status
404 if status != 'PENDING':
405 break
406 time.sleep(0.1)
407 else:
408 raise AssertionError("Timeout while waiting for the task to be retried")
409 assert status == 'RETRY'
410 assert result.get() == 'bar'
411 assert result.status == 'SUCCESS'
412
413 def test_retry_with_unpickleable_exception(self, manager):
414 """Test a task that retries with an unpickleable exception.
415
416 We expect to be able to fetch the result (exception) correctly.
417 """
418
419 job = retry_unpickleable.delay(
420 "foo",
421 "bar",
422 retry_kwargs={"countdown": 10, "max_retries": 1},
423 )
424
425 # Wait for the task to raise the Retry exception
426 tik = time.monotonic()
427 while time.monotonic() < tik + 5:
428 status = job.status
429 if status != 'PENDING':
430 break
431 time.sleep(0.1)
432 else:
433 raise AssertionError("Timeout while waiting for the task to be retried")
434
435 assert status == 'RETRY'
436
437 # Get the exception
438 res = job.result
439 assert job.status == 'RETRY' # make sure that it wasn't completed yet
440
441 # Check it. Accept both the dedicated wrapper and plain Exception
442 # (some environments may return a stringified Exception instead).
443 if isinstance(res, UnpickleableExceptionWrapper):
444 assert res.exc_cls_name == "UnpickleableException"
445 assert res.exc_args == ("foo",)
446 else:
447 # Fallback: ensure the exception string mentions the class and argument
448 res_str = str(res)
449 assert "UnpickleableException" in res_str
450 assert "foo" in res_str
451
452 job.revoke()
453
454 def test_fail_with_unpickleable_exception(self, manager):
455 """Test a task that fails with an unpickleable exception.
456
457 We expect to be able to fetch the result (exception) correctly.
458 """
459 result = fail_unpickleable.delay("foo", "bar")
460
461 # Accept either the dedicated wrapper exception or a plain Exception
462 # whose string contains the class name and args (some backends
463 # may return a stringified exception).
464 try:
465 result.get()
466 pytest.fail("Expected an exception when getting result")
467 except UnpickleableExceptionWrapper as exc_wrapper:
468 assert exc_wrapper.exc_cls_name == "UnpickleableException"
469 assert exc_wrapper.exc_args == ("foo",)
470 except Exception as exc:
471 # Fallback: ensure the exception string mentions the class and argument
472 exc_str = str(exc)
473 assert "UnpickleableException" in exc_str
474 assert "foo" in exc_str
475
476 assert result.status == 'FAILURE'
477
478 # Requires investigation why it randomly succeeds/fails
479 @pytest.mark.skip(reason="Randomly fails")
480 def test_task_accepted(self, manager, sleep=1):
481 r1 = sleeping.delay(sleep)
482 sleeping.delay(sleep)
483 manager.assert_accepted([r1.id])
484
485 @flaky
486 def test_task_retried_once(self, manager):
487 res = retry_once.delay()
488 assert res.get(timeout=TIMEOUT) == 1 # retried once
489
490 @flaky
491 def test_task_retried_once_with_expires(self, manager):
492 res = retry_once.delay(expires=60)
493 assert res.get(timeout=TIMEOUT) == 1 # retried once
494
495 @flaky
496 def test_task_retried_priority(self, manager):
497 res = retry_once_priority.apply_async(priority=7)
498 assert res.get(timeout=TIMEOUT) == 7 # retried once with priority 7
499
500 @flaky
501 def test_task_retried_headers(self, manager):
502 res = retry_once_headers.apply_async(headers={'x-test-header': 'test-value'})
503 headers = res.get(timeout=TIMEOUT)
504 assert headers is not None # retried once with headers
505 assert 'x-test-header' in headers # retry keeps custom headers
506
507 @flaky
508 def test_unicode_task(self, manager):
509 manager.join(
510 group(print_unicode.s() for _ in range(5))(),
511 timeout=TIMEOUT, propagate=True,
512 )
513
514 @flaky
515 def test_properties(self, celery_session_worker):
516 res = return_properties.apply_async(app_id="1234")
517 assert res.get(timeout=TIMEOUT)["app_id"] == "1234"
518
519 @flaky
520 def test_soft_time_limit_exceeding_time_limit(self):
521
522 with pytest.raises(ValueError, match='soft_time_limit must be less than or equal to time_limit'):
523 result = soft_time_limit_must_exceed_time_limit.apply_async()
524 result.get(timeout=5)
525
526 assert result.status == 'FAILURE'
527
528
529 class test_apply_tasks:
530 """Tests for tasks called via apply() method."""
531
532 def test_apply_single_task_ids(self, manager):
533 """Test that a single task called via apply() has correct IDs."""
534 @manager.app.task(bind=True)
535 def single_apply_task(self):
536 return {
537 'task_id': self.request.id,
538 'parent_id': self.request.parent_id,
539 'root_id': self.request.root_id,
540 }
541
542 result = single_apply_task.apply()
543 data = result.get()
544
545 # Single task should have no parent and root_id should equal task_id
546 assert data['parent_id'] is None
547 assert data['root_id'] == data['task_id']
548
549 def test_apply_nested_parent_child_relationship(self, manager):
550 """Test parent-child relationship when one task calls another via apply()."""
551
552 @manager.app.task(bind=True)
553 def grandchild_task(task_self):
554 return {
555 'task_id': task_self.request.id,
556 'parent_id': task_self.request.parent_id,
557 'root_id': task_self.request.root_id,
558 'name': 'grandchild_task'
559 }
560
561 @manager.app.task(bind=True)
562 def child_task(task_self):
563
564 # Call grandchild task via apply()
565 grandchild_data = grandchild_task.apply().get()
566 return {
567 'task_id': task_self.request.id,
568 'parent_id': task_self.request.parent_id,
569 'root_id': task_self.request.root_id,
570 'name': 'child_task',
571 'grandchild_data': grandchild_data
572 }
573
574 @manager.app.task(bind=True)
575 def parent_task(task_self):
576 # Call child task via apply()
577 child_data = child_task.apply().get()
578 parent_data = {
579 'task_id': task_self.request.id,
580 'parent_id': task_self.request.parent_id,
581 'root_id': task_self.request.root_id,
582 'name': 'parent_task',
583 'child_data': child_data
584 }
585 return parent_data
586
587 result = parent_task.apply()
588
589 parent_data = result.get()
590 child_data = parent_data['child_data']
591 grandchild_data = child_data['grandchild_data']
592
593 # Verify parent task
594 assert parent_data['name'] == 'parent_task'
595 assert parent_data['parent_id'] is None
596 assert parent_data['root_id'] == parent_data['task_id']
597
598 # Verify child task
599 assert child_data['name'] == 'child_task'
600 assert child_data['parent_id'] == parent_data['task_id']
601 assert child_data['root_id'] == parent_data['task_id']
602
603 # Verify grandchild task
604 assert grandchild_data['name'] == 'grandchild_task'
605 assert grandchild_data['parent_id'] == child_data['task_id']
606 assert grandchild_data['root_id'] == parent_data['task_id']
607
608
609 class test_trace_log_arguments:
610 args = "CUSTOM ARGS"
611 kwargs = "CUSTOM KWARGS"
612
613 def assert_trace_log(self, caplog, result, expected):
614 # wait for logs from worker
615 time.sleep(.01)
616
617 records = [(r.name, r.levelno, r.msg, r.data["args"], r.data["kwargs"])
618 for r in caplog.records
619 if r.name in {'celery.worker.strategy', 'celery.app.trace'}
620 if r.data["id"] == result.task_id
621 ]
622 assert records == [(*e, self.args, self.kwargs) for e in expected]
623
624 def call_task_with_reprs(self, task):
625 return task.set(argsrepr=self.args, kwargsrepr=self.kwargs).delay()
626
627 @flaky
628 def test_task_success(self, caplog):
629 result = self.call_task_with_reprs(add.s(2, 2))
630 value = result.get()
631 assert value == 4
632 assert result.successful() is True
633
634 self.assert_trace_log(caplog, result, [
635 ('celery.worker.strategy', logging.INFO,
636 celery.app.trace.LOG_RECEIVED,
637 ),
638 ('celery.app.trace', logging.INFO,
639 celery.app.trace.LOG_SUCCESS,
640 ),
641 ])
642
643 @flaky
644 def test_task_failed(self, caplog):
645 result = self.call_task_with_reprs(fail.s(2, 2))
646 with pytest.raises(ExpectedException):
647 result.get(timeout=5)
648 assert result.failed() is True
649
650 self.assert_trace_log(caplog, result, [
651 ('celery.worker.strategy', logging.INFO,
652 celery.app.trace.LOG_RECEIVED,
653 ),
654 ('celery.app.trace', logging.ERROR,
655 celery.app.trace.LOG_FAILURE,
656 ),
657 ])
658
659
660 class test_task_redis_result_backend:
661 @pytest.fixture()
662 def manager(self, manager):
663 if not manager.app.conf.result_backend.startswith('redis'):
664 raise pytest.skip('Requires redis result backend.')
665
666 return manager
667
668 def test_ignoring_result_no_subscriptions(self, manager):
669 channels_before_test = get_active_redis_channels()
670
671 result = add_ignore_result.delay(1, 2)
672 assert result.ignored is True
673
674 new_channels = [channel for channel in get_active_redis_channels() if channel not in channels_before_test]
675 assert new_channels == []
676
677 @flaky
678 def test_asyncresult_forget_cancels_subscription(self, manager):
679 channels_before_test = get_active_redis_channels()
680
681 result = add.delay(1, 2)
682 assert set(get_active_redis_channels()) == {
683 f"celery-task-meta-{result.id}".encode(), *channels_before_test
684 }
685 result.forget()
686
687 new_channels = [channel for channel in get_active_redis_channels() if channel not in channels_before_test]
688 assert new_channels == []
689
690 @flaky
691 def test_asyncresult_get_cancels_subscription(self, manager):
692 channels_before_test = get_active_redis_channels()
693
694 result = add.delay(1, 2)
695 assert set(get_active_redis_channels()) == {
696 f"celery-task-meta-{result.id}".encode(), *channels_before_test
697 }
698 assert result.get(timeout=3) == 3
699
700 new_channels = [channel for channel in get_active_redis_channels() if channel not in channels_before_test]
701 assert new_channels == []
702
703
704 class test_task_replacement:
705 def test_replaced_task_nesting_level_0(self, manager):
706 @task_received.connect
707 def task_received_handler(request, **kwargs):
708 nonlocal assertion_result
709
710 try:
711 # This tests mainly that the field even exists and set to default 0
712 assertion_result = request.replaced_task_nesting < 1
713 except Exception:
714 assertion_result = False
715
716 non_replaced_task = add.si(4, 2)
717 res = non_replaced_task.delay()
718 assertion_result = False
719 assert res.get(timeout=TIMEOUT) == 6
720 assert assertion_result
721
722 def test_replaced_task_nesting_level_1(self, manager):
723 if not manager.app.conf.result_backend.startswith("redis"):
724 raise pytest.skip("Requires redis result backend.")
725
726 redis_connection = get_redis_connection()
727 redis_connection.delete("redis-echo")
728
729 @task_received.connect
730 def task_received_handler(request, **kwargs):
731 nonlocal assertion_result
732
733 try:
734 assertion_result = request.replaced_task_nesting <= 2
735 except Exception:
736 assertion_result = False
737
738 replaced_task = second_order_replace1.si()
739 res = replaced_task.delay()
740 assertion_result = False
741 res.get(timeout=TIMEOUT)
742 assert assertion_result
743 redis_messages = list(redis_connection.lrange("redis-echo", 0, -1))
744 expected_messages = [b"In A", b"In B", b"In/Out C", b"Out B", b"Out A"]
745 assert redis_messages == expected_messages
746
747 def test_replaced_task_nesting_chain(self, manager):
748 if not manager.app.conf.result_backend.startswith("redis"):
749 raise pytest.skip("Requires redis result backend.")
750
751 redis_connection = get_redis_connection()
752 redis_connection.delete("redis-echo")
753
754 @task_received.connect
755 def task_received_handler(request, **kwargs):
756 nonlocal assertion_result
757
758 try:
759 assertion_result = request.replaced_task_nesting <= 3
760 except Exception:
761 assertion_result = False
762
763 assertion_result = False
764 chain_task = second_order_replace1.si() | add.si(4, 2)
765 res = chain_task.delay()
766 res.get(timeout=TIMEOUT)
767 assert assertion_result
768 redis_messages = list(redis_connection.lrange("redis-echo", 0, -1))
769 expected_messages = [b"In A", b"In B", b"In/Out C", b"Out B", b"Out A"]
770 assert redis_messages == expected_messages