Debian Codegraph @

t/unit/tasks/test_result.py

raw
1 import copy
2 import datetime
3 import platform
4 import traceback
5 from contextlib import contextmanager
6 from unittest.mock import Mock, call, patch
7
8 import pytest
9
10 from celery import states, uuid
11 from celery.app.task import Context
12 from celery.backends.base import Backend, SyncBackendMixin
13 from celery.exceptions import ImproperlyConfigured, IncompleteStream, TimeoutError
14 from celery.result import AsyncResult, EagerResult, GroupResult, ResultSet, assert_will_not_block, result_from_tuple
15 from celery.utils.serialization import pickle
16
17 PYTRACEBACK = """\
18 Traceback (most recent call last):
19 File "foo.py", line 2, in foofunc
20 don't matter
21 File "bar.py", line 3, in barfunc
22 don't matter
23 Doesn't matter: really!\
24 """
25
26
27 def mock_task(name, state, result, traceback=None):
28 return {
29 'id': uuid(), 'name': name, 'state': state,
30 'result': result, 'traceback': traceback,
31 }
32
33
34 def save_result(app, task):
35 traceback = task.get('traceback') or 'Some traceback'
36 if task['state'] == states.SUCCESS:
37 app.backend.mark_as_done(task['id'], task['result'])
38 elif task['state'] == states.RETRY:
39 app.backend.mark_as_retry(
40 task['id'], task['result'], traceback=traceback,
41 )
42 else:
43 app.backend.mark_as_failure(
44 task['id'], task['result'], traceback=traceback,
45 )
46
47
48 def make_mock_group(app, size=10):
49 tasks = [mock_task('ts%d' % i, states.SUCCESS, i) for i in range(size)]
50 [save_result(app, task) for task in tasks]
51 return [app.AsyncResult(task['id']) for task in tasks]
52
53
54 class _MockBackend:
55 def add_pending_result(self, *args, **kwargs):
56 return True
57
58 def wait_for_pending(self, *args, **kwargs):
59 return True
60
61 def remove_pending_result(self, *args, **kwargs):
62 return True
63
64
65 class test_AsyncResult:
66
67 def setup_method(self):
68 self.app.conf.result_cache_max = 100
69 self.app.conf.result_serializer = 'pickle'
70 self.app.conf.result_extended = True
71 self.task1 = mock_task('task1', states.SUCCESS, 'the')
72 self.task2 = mock_task('task2', states.SUCCESS, 'quick')
73 self.task3 = mock_task('task3', states.FAILURE, KeyError('brown'))
74 self.task4 = mock_task('task3', states.RETRY, KeyError('red'))
75 self.task5 = mock_task(
76 'task3', states.FAILURE, KeyError('blue'), PYTRACEBACK,
77 )
78 self.task6 = mock_task('task6', states.SUCCESS, None)
79 for task in (self.task1, self.task2,
80 self.task3, self.task4, self.task5, self.task6):
81 save_result(self.app, task)
82
83 @self.app.task(shared=False)
84 def mytask():
85 pass
86 self.mytask = mytask
87
88 def test_forget(self):
89 first = Mock()
90 second = self.app.AsyncResult(self.task1['id'], parent=first)
91 third = self.app.AsyncResult(self.task2['id'], parent=second)
92 last = self.app.AsyncResult(self.task3['id'], parent=third)
93 last.forget()
94 first.forget.assert_called_once()
95 assert last.result is None
96 assert second.result is None
97
98 def test_ignored_getter(self):
99 result = self.app.AsyncResult(uuid())
100 assert result.ignored is False
101 result.__delattr__('_ignored')
102 assert result.ignored is False
103
104 @patch('celery.result.task_join_will_block')
105 def test_assert_will_not_block(self, task_join_will_block):
106 task_join_will_block.return_value = True
107 with pytest.raises(RuntimeError):
108 assert_will_not_block()
109 task_join_will_block.return_value = False
110 assert_will_not_block()
111
112 @patch('celery.result.task_join_will_block')
113 def test_get_sync_subtask_option(self, task_join_will_block):
114 task_join_will_block.return_value = True
115 tid = uuid()
116 backend = _MockBackend()
117 res_subtask_async = AsyncResult(tid, backend=backend)
118 with pytest.raises(RuntimeError):
119 res_subtask_async.get()
120 res_subtask_async.get(disable_sync_subtasks=False)
121
122 def test_without_id(self):
123 with pytest.raises(ValueError):
124 AsyncResult(None, app=self.app)
125
126 def test_compat_properties(self):
127 x = self.app.AsyncResult('1')
128 assert x.task_id == x.id
129 x.task_id = '2'
130 assert x.id == '2'
131
132 @pytest.mark.usefixtures('depends_on_current_app')
133 def test_reduce_direct(self):
134 x = AsyncResult('1', app=self.app)
135 fun, args = x.__reduce__()
136 assert fun(*args) == x
137
138 def test_children(self):
139 x = self.app.AsyncResult('1')
140 children = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
141 x._cache = {'children': children, 'status': states.SUCCESS}
142 x.backend = Mock()
143 assert x.children
144 assert len(x.children) == 3
145
146 def test_propagates_for_parent(self):
147 x = self.app.AsyncResult(uuid())
148 x.backend = Mock(name='backend')
149 x.backend.get_task_meta.return_value = {}
150 x.backend.wait_for_pending.return_value = 84
151 x.parent = EagerResult(uuid(), KeyError('foo'), states.FAILURE)
152 with pytest.raises(KeyError):
153 x.get(propagate=True)
154 x.backend.wait_for_pending.assert_not_called()
155
156 x.parent = EagerResult(uuid(), 42, states.SUCCESS)
157 assert x.get(propagate=True) == 84
158 x.backend.wait_for_pending.assert_called()
159
160 def test_get_children(self):
161 tid = uuid()
162 x = self.app.AsyncResult(tid)
163 child = [self.app.AsyncResult(uuid()).as_tuple()
164 for i in range(10)]
165 x._cache = {'children': child}
166 assert x.children
167 assert len(x.children) == 10
168
169 x._cache = {'status': states.SUCCESS}
170 x.backend._cache[tid] = {'result': None}
171 assert x.children is None
172
173 def test_build_graph_get_leaf_collect(self):
174 x = self.app.AsyncResult('1')
175 x.backend._cache['1'] = {'status': states.SUCCESS, 'result': None}
176 c = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
177 x.iterdeps = Mock()
178 x.iterdeps.return_value = (
179 (None, x),
180 (x, c[0]),
181 (c[0], c[1]),
182 (c[1], c[2])
183 )
184 x.backend.READY_STATES = states.READY_STATES
185 assert x.graph
186 assert x.get_leaf() == 2
187
188 it = x.collect()
189 assert list(it) == [
190 (x, None),
191 (c[0], 0),
192 (c[1], 1),
193 (c[2], 2),
194 ]
195
196 def test_iterdeps(self):
197 x = self.app.AsyncResult('1')
198 c = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
199 x._cache = {'status': states.SUCCESS, 'result': None, 'children': c}
200 for child in c:
201 child.backend = Mock()
202 child.backend.get_children.return_value = []
203 it = x.iterdeps()
204 assert list(it) == [
205 (None, x),
206 (x, c[0]),
207 (x, c[1]),
208 (x, c[2]),
209 ]
210 x._cache = None
211 x.ready = Mock()
212 x.ready.return_value = False
213 with pytest.raises(IncompleteStream):
214 list(x.iterdeps())
215 list(x.iterdeps(intermediate=True))
216
217 def test_eq_not_implemented(self):
218 assert self.app.AsyncResult('1') != object()
219
220 @pytest.mark.usefixtures('depends_on_current_app')
221 def test_reduce(self):
222 a1 = self.app.AsyncResult('uuid')
223 restored = pickle.loads(pickle.dumps(a1))
224 assert restored.id == 'uuid'
225
226 a2 = self.app.AsyncResult('uuid')
227 assert pickle.loads(pickle.dumps(a2)).id == 'uuid'
228
229 def test_maybe_set_cache_empty(self):
230 self.app.AsyncResult('uuid')._maybe_set_cache(None)
231
232 def test_set_cache__children(self):
233 r1 = self.app.AsyncResult('id1')
234 r2 = self.app.AsyncResult('id2')
235 r1._set_cache({'children': [r2.as_tuple()]})
236 assert r2 in r1.children
237
238 def test_successful(self):
239 ok_res = self.app.AsyncResult(self.task1['id'])
240 nok_res = self.app.AsyncResult(self.task3['id'])
241 nok_res2 = self.app.AsyncResult(self.task4['id'])
242
243 assert ok_res.successful()
244 assert not nok_res.successful()
245 assert not nok_res2.successful()
246
247 pending_res = self.app.AsyncResult(uuid())
248 assert not pending_res.successful()
249
250 def test_raising(self):
251 notb = self.app.AsyncResult(self.task3['id'])
252 withtb = self.app.AsyncResult(self.task5['id'])
253
254 with pytest.raises(KeyError):
255 notb.get()
256 with pytest.raises(KeyError) as excinfo:
257 withtb.get()
258
259 tb = [t.strip() for t in traceback.format_tb(excinfo.tb)]
260 assert 'File "foo.py", line 2, in foofunc' not in tb
261 assert 'File "bar.py", line 3, in barfunc' not in tb
262 assert excinfo.value.args[0] == 'blue'
263 assert excinfo.typename == 'KeyError'
264
265 def test_raising_remote_tracebacks(self):
266 pytest.importorskip('tblib')
267
268 withtb = self.app.AsyncResult(self.task5['id'])
269 self.app.conf.task_remote_tracebacks = True
270 with pytest.raises(KeyError) as excinfo:
271 withtb.get()
272 tb = [t.strip() for t in traceback.format_tb(excinfo.tb)]
273 assert 'File "foo.py", line 2, in foofunc' in tb
274 assert 'File "bar.py", line 3, in barfunc' in tb
275 assert excinfo.value.args[0] == 'blue'
276 assert excinfo.typename == 'KeyError'
277
278 def test_str(self):
279 ok_res = self.app.AsyncResult(self.task1['id'])
280 ok2_res = self.app.AsyncResult(self.task2['id'])
281 nok_res = self.app.AsyncResult(self.task3['id'])
282 assert str(ok_res) == self.task1['id']
283 assert str(ok2_res) == self.task2['id']
284 assert str(nok_res) == self.task3['id']
285
286 pending_id = uuid()
287 pending_res = self.app.AsyncResult(pending_id)
288 assert str(pending_res) == pending_id
289
290 def test_repr(self):
291 ok_res = self.app.AsyncResult(self.task1['id'])
292 ok2_res = self.app.AsyncResult(self.task2['id'])
293 nok_res = self.app.AsyncResult(self.task3['id'])
294 assert repr(ok_res) == f"<AsyncResult: {self.task1['id']}>"
295 assert repr(ok2_res) == f"<AsyncResult: {self.task2['id']}>"
296 assert repr(nok_res) == f"<AsyncResult: {self.task3['id']}>"
297
298 pending_id = uuid()
299 pending_res = self.app.AsyncResult(pending_id)
300 assert repr(pending_res) == f'<AsyncResult: {pending_id}>'
301
302 def test_hash(self):
303 assert (hash(self.app.AsyncResult('x0w991')) ==
304 hash(self.app.AsyncResult('x0w991')))
305 assert (hash(self.app.AsyncResult('x0w991')) !=
306 hash(self.app.AsyncResult('x1w991')))
307
308 def test_get_traceback(self):
309 ok_res = self.app.AsyncResult(self.task1['id'])
310 nok_res = self.app.AsyncResult(self.task3['id'])
311 nok_res2 = self.app.AsyncResult(self.task4['id'])
312 assert not ok_res.traceback
313 assert nok_res.traceback
314 assert nok_res2.traceback
315
316 pending_res = self.app.AsyncResult(uuid())
317 assert not pending_res.traceback
318
319 def test_get__backend_gives_None(self):
320 res = self.app.AsyncResult(self.task1['id'])
321 res.backend.wait_for = Mock(name='wait_for')
322 res.backend.wait_for.return_value = None
323 assert res.get() is None
324
325 def test_get(self):
326 ok_res = self.app.AsyncResult(self.task1['id'])
327 ok2_res = self.app.AsyncResult(self.task2['id'])
328 nok_res = self.app.AsyncResult(self.task3['id'])
329 nok2_res = self.app.AsyncResult(self.task4['id'])
330 none_res = self.app.AsyncResult(self.task6['id'])
331
332 callback = Mock(name='callback')
333
334 assert ok_res.get(callback=callback) == 'the'
335 callback.assert_called_with(ok_res.id, 'the')
336 assert ok2_res.get() == 'quick'
337 with pytest.raises(KeyError):
338 nok_res.get()
339 assert nok_res.get(propagate=False)
340 assert isinstance(nok2_res.result, KeyError)
341 assert ok_res.info == 'the'
342 assert none_res.get() is None
343 assert none_res.state == states.SUCCESS
344
345 def test_get_when_ignored(self):
346 result = self.app.AsyncResult(uuid())
347 result.ignored = True
348 # Does not block
349 assert result.get() is None
350
351 def test_eq_ne(self):
352 r1 = self.app.AsyncResult(self.task1['id'])
353 r2 = self.app.AsyncResult(self.task1['id'])
354 r3 = self.app.AsyncResult(self.task2['id'])
355 assert r1 == r2
356 assert r1 != r3
357 assert r1 == r2.id
358 assert r1 != r3.id
359
360 @pytest.mark.usefixtures('depends_on_current_app')
361 def test_reduce_restore(self):
362 r1 = self.app.AsyncResult(self.task1['id'])
363 fun, args = r1.__reduce__()
364 assert fun(*args) == r1
365
366 def test_get_timeout(self):
367 res = self.app.AsyncResult(self.task4['id']) # has RETRY state
368 with pytest.raises(TimeoutError):
369 res.get(timeout=0.001)
370
371 pending_res = self.app.AsyncResult(uuid())
372 with patch('celery.result.time') as _time:
373 with pytest.raises(TimeoutError):
374 pending_res.get(timeout=0.001, interval=0.001)
375 _time.sleep.assert_called_with(0.001)
376
377 def test_get_timeout_longer(self):
378 res = self.app.AsyncResult(self.task4['id']) # has RETRY state
379 with patch('celery.result.time') as _time:
380 with pytest.raises(TimeoutError):
381 res.get(timeout=1, interval=1)
382 _time.sleep.assert_called_with(1)
383
384 def test_ready(self):
385 oks = (self.app.AsyncResult(self.task1['id']),
386 self.app.AsyncResult(self.task2['id']),
387 self.app.AsyncResult(self.task3['id']))
388 assert all(result.ready() for result in oks)
389 assert not self.app.AsyncResult(self.task4['id']).ready()
390
391 assert not self.app.AsyncResult(uuid()).ready()
392
393 @pytest.mark.skipif(
394 platform.python_implementation() == "PyPy",
395 reason="Mocking here doesn't play well with PyPy",
396 )
397 def test_del(self):
398 with patch('celery.result.AsyncResult.backend') as backend:
399 result = self.app.AsyncResult(self.task1['id'])
400 result.backend = backend
401 result_clone = copy.copy(result)
402 del result
403 backend.remove_pending_result.assert_called_once_with(
404 result_clone
405 )
406
407 result = self.app.AsyncResult(self.task1['id'])
408 result.backend = None
409 del result
410
411 def test_get_request_meta(self):
412
413 x = self.app.AsyncResult('1')
414 request = Context(
415 task='foo',
416 children=None,
417 args=['one', 'two'],
418 kwargs={'kwarg1': 'three'},
419 hostname="foo",
420 retries=1,
421 delivery_info={'routing_key': 'celery'}
422 )
423 x.backend.store_result(task_id="1", result='foo', state=states.SUCCESS,
424 traceback=None, request=request)
425 assert x.name == 'foo'
426 assert x.args == ['one', 'two']
427 assert x.kwargs == {'kwarg1': 'three'}
428 assert x.worker == 'foo'
429 assert x.retries == 1
430 assert x.queue == 'celery'
431 assert isinstance(x.date_done, datetime.datetime)
432 assert x.task_id == "1"
433 assert x.state == "SUCCESS"
434 result = self.app.AsyncResult(self.task4['id'])
435 assert result.date_done is None
436
437 @patch('celery.app.base.to_utc')
438 @pytest.mark.parametrize('timezone, date', [
439 ("UTC", "2024-08-24T00:00:00+00:00"),
440 ("America/Los_Angeles", "2024-08-23T17:00:00-07:00"),
441 ("Pacific/Kwajalein", "2024-08-24T12:00:00+12:00"),
442 ("Europe/Berlin", "2024-08-24T02:00:00+02:00"),
443 ])
444 def test_date_done(self, utc_datetime_mock, timezone, date):
445 utc_datetime_mock.return_value = datetime.datetime(2024, 8, 24, 0, 0, 0, 0, datetime.timezone.utc)
446 self.app.conf.timezone = timezone
447 del self.app.timezone # reset cached timezone
448
449 result = Backend(app=self.app)._get_result_meta(None, states.SUCCESS, None, None)
450 assert result.get('date_done') == date
451
452 def test_forget_remove_pending_result(self):
453 with patch('celery.result.AsyncResult.backend') as backend:
454 result = self.app.AsyncResult(self.task1['id'])
455 result.backend = backend
456 result_clone = copy.copy(result)
457 result.forget()
458 backend.remove_pending_result.assert_called_once_with(
459 result_clone
460 )
461
462 result = self.app.AsyncResult(self.task1['id'])
463 result.backend = None
464 del result
465
466
467 class test_ResultSet:
468
469 def test_resultset_repr(self):
470 assert repr(self.app.ResultSet(
471 [self.app.AsyncResult(t) for t in ['1', '2', '3']]))
472
473 def test_eq_other(self):
474 assert self.app.ResultSet([
475 self.app.AsyncResult(t) for t in [1, 3, 3]]) != 1
476 rs1 = self.app.ResultSet([self.app.AsyncResult(1)])
477 rs2 = self.app.ResultSet([self.app.AsyncResult(1)])
478 assert rs1 == rs2
479
480 def test_get(self):
481 x = self.app.ResultSet([self.app.AsyncResult(t) for t in [1, 2, 3]])
482 b = x.results[0].backend = Mock()
483 b.supports_native_join = False
484 x.join_native = Mock()
485 x.join = Mock()
486 x.get()
487 x.join.assert_called()
488 b.supports_native_join = True
489 x.get()
490 x.join_native.assert_called()
491
492 @patch('celery.result.task_join_will_block')
493 def test_get_sync_subtask_option(self, task_join_will_block):
494 task_join_will_block.return_value = True
495 x = self.app.ResultSet([self.app.AsyncResult(str(t)) for t in [1, 2, 3]])
496 b = x.results[0].backend = Mock()
497 b.supports_native_join = False
498 with pytest.raises(RuntimeError):
499 x.get()
500 with pytest.raises(TimeoutError):
501 x.get(disable_sync_subtasks=False, timeout=0.1)
502
503 def test_join_native_with_group_chain_group(self):
504 """Test group(chain(group)) case, join_native can be run correctly.
505 In group(chain(group)) case, GroupResult has no _cache property, and
506 AsyncBackendMixin.iter_native returns a node instead of node._cache,
507 this test make sure ResultSet.join_native can process correctly both
508 values of AsyncBackendMixin.iter_native returns.
509 """
510 def _get_meta(tid, result=None, children=None):
511 return {
512 'status': states.SUCCESS,
513 'result': result,
514 'children': children,
515 'task_id': tid,
516 }
517
518 results = [self.app.AsyncResult(t) for t in [1, 2, 3]]
519 values = [(_.id, _get_meta(_.id, _)) for _ in results]
520 g_res = GroupResult(6, [self.app.AsyncResult(t) for t in [4, 5]])
521 results += [g_res]
522 values += [(6, g_res.children)]
523 x = self.app.ResultSet(results)
524 x.results[0].backend = Mock()
525 x.results[0].backend.join = Mock()
526 x.results[3][0].get = Mock()
527 x.results[3][0].get.return_value = g_res.results[0]
528 x.results[3][1].get = Mock()
529 x.results[3][1].get.return_value = g_res.results[1]
530 x.iter_native = Mock()
531 x.iter_native.return_value = values.__iter__()
532 x.join_native()
533 x.iter_native.assert_called()
534
535 def test_eq_ne(self):
536 g1 = self.app.ResultSet([
537 self.app.AsyncResult('id1'),
538 self.app.AsyncResult('id2'),
539 ])
540 g2 = self.app.ResultSet([
541 self.app.AsyncResult('id1'),
542 self.app.AsyncResult('id2'),
543 ])
544 g3 = self.app.ResultSet([
545 self.app.AsyncResult('id3'),
546 self.app.AsyncResult('id1'),
547 ])
548 assert g1 == g2
549 assert g1 != g3
550 assert g1 != object()
551
552 def test_takes_app_from_first_task(self):
553 x = ResultSet([self.app.AsyncResult('id1')])
554 assert x.app is x.results[0].app
555 x.app = self.app
556 assert x.app is self.app
557
558 def test_get_empty(self):
559 x = self.app.ResultSet([])
560 assert x.supports_native_join is None
561 x.join = Mock(name='join')
562 x.get()
563 x.join.assert_called()
564
565 def test_add(self):
566 x = self.app.ResultSet([self.app.AsyncResult(1)])
567 x.add(self.app.AsyncResult(2))
568 assert len(x) == 2
569 x.add(self.app.AsyncResult(2))
570 assert len(x) == 2
571
572 @contextmanager
573 def dummy_copy(self):
574 with patch('celery.result.copy') as copy:
575
576 def pass_value(arg):
577 return arg
578 copy.side_effect = pass_value
579
580 yield
581
582 def test_add_discard(self):
583 x = self.app.ResultSet([])
584 x.add(self.app.AsyncResult('1'))
585 assert self.app.AsyncResult('1') in x.results
586 x.discard(self.app.AsyncResult('1'))
587 x.discard(self.app.AsyncResult('1'))
588 x.discard('1')
589 assert self.app.AsyncResult('1') not in x.results
590
591 x.update([self.app.AsyncResult('2')])
592
593 def test_clear(self):
594 x = self.app.ResultSet([])
595 r = x.results
596 x.clear()
597 assert x.results is r
598
599
600 class MockAsyncResultFailure(AsyncResult):
601
602 @property
603 def result(self):
604 return KeyError('baz')
605
606 @property
607 def state(self):
608 return states.FAILURE
609
610 def get(self, propagate=True, **kwargs):
611 if propagate:
612 raise self.result
613 return self.result
614
615
616 class MockAsyncResultSuccess(AsyncResult):
617 forgotten = False
618
619 def __init__(self, *args, **kwargs):
620 self._result = kwargs.pop('result', 42)
621 super().__init__(*args, **kwargs)
622
623 def forget(self):
624 self.forgotten = True
625
626 @property
627 def result(self):
628 return self._result
629
630 @property
631 def state(self):
632 return states.SUCCESS
633
634 def get(self, **kwargs):
635 return self.result
636
637
638 class SimpleBackend(SyncBackendMixin):
639 ids = []
640
641 def __init__(self, ids=[]):
642 self.ids = ids
643
644 def _ensure_not_eager(self):
645 pass
646
647 def get_many(self, *args, **kwargs):
648 return ((id, {'result': i, 'status': states.SUCCESS})
649 for i, id in enumerate(self.ids))
650
651
652 class test_GroupResult:
653
654 def setup_method(self):
655 self.size = 10
656 self.ts = self.app.GroupResult(
657 uuid(), make_mock_group(self.app, self.size),
658 )
659
660 @pytest.mark.usefixtures('depends_on_current_app')
661 def test_is_pickleable(self):
662 ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
663 assert pickle.loads(pickle.dumps(ts)) == ts
664 ts2 = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
665 assert pickle.loads(pickle.dumps(ts2)) == ts2
666
667 @pytest.mark.usefixtures('depends_on_current_app')
668 def test_reduce(self):
669 ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
670 fun, args = ts.__reduce__()
671 ts2 = fun(*args)
672 assert ts2.id == ts.id
673 assert ts == ts2
674
675 def test_eq_ne(self):
676 ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
677 ts2 = self.app.GroupResult(ts.id, ts.results)
678 ts3 = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
679 ts4 = self.app.GroupResult(ts.id, [self.app.AsyncResult(uuid())])
680 assert ts == ts2
681 assert ts != ts3
682 assert ts != ts4
683 assert ts != object()
684
685 def test_len(self):
686 assert len(self.ts) == self.size
687
688 def test_eq_other(self):
689 assert self.ts != 1
690
691 def test_eq_with_parent(self):
692 # GroupResult instances with different .parent are not equal
693 grp_res = self.app.GroupResult(
694 uuid(), [self.app.AsyncResult(uuid()) for _ in range(10)],
695 parent=self.app.AsyncResult(uuid())
696 )
697 grp_res_2 = self.app.GroupResult(grp_res.id, grp_res.results)
698 assert grp_res != grp_res_2
699
700 grp_res_2.parent = self.app.AsyncResult(uuid())
701 assert grp_res != grp_res_2
702
703 grp_res_2.parent = grp_res.parent
704 assert grp_res == grp_res_2
705
706 @pytest.mark.usefixtures('depends_on_current_app')
707 def test_pickleable(self):
708 assert pickle.loads(pickle.dumps(self.ts))
709
710 def test_forget(self):
711 subs = [MockAsyncResultSuccess(uuid(), app=self.app),
712 MockAsyncResultSuccess(uuid(), app=self.app)]
713 ts = self.app.GroupResult(uuid(), subs)
714 ts.forget()
715 for sub in subs:
716 assert sub.forgotten
717
718 def test_get_nested_without_native_join(self):
719 backend = SimpleBackend()
720 backend.supports_native_join = False
721 ts = self.app.GroupResult(uuid(), [
722 MockAsyncResultSuccess(uuid(), result='1.1',
723 app=self.app, backend=backend),
724 self.app.GroupResult(uuid(), [
725 MockAsyncResultSuccess(uuid(), result='2.1',
726 app=self.app, backend=backend),
727 self.app.GroupResult(uuid(), [
728 MockAsyncResultSuccess(uuid(), result='3.1',
729 app=self.app, backend=backend),
730 MockAsyncResultSuccess(uuid(), result='3.2',
731 app=self.app, backend=backend),
732 ]),
733 ]),
734 ])
735
736 with patch('celery.Celery.backend', new=backend):
737 vals = ts.get()
738 assert vals == [
739 '1.1',
740 [
741 '2.1',
742 [
743 '3.1',
744 '3.2',
745 ]
746 ],
747 ]
748
749 def test_getitem(self):
750 subs = [MockAsyncResultSuccess(uuid(), app=self.app),
751 MockAsyncResultSuccess(uuid(), app=self.app)]
752 ts = self.app.GroupResult(uuid(), subs)
753 assert ts[0] is subs[0]
754
755 def test_save_restore(self):
756 subs = [MockAsyncResultSuccess(uuid(), app=self.app),
757 MockAsyncResultSuccess(uuid(), app=self.app)]
758 ts = self.app.GroupResult(uuid(), subs)
759 ts.save()
760 with pytest.raises(AttributeError):
761 ts.save(backend=object())
762 assert self.app.GroupResult.restore(ts.id).results == ts.results
763 ts.delete()
764 assert self.app.GroupResult.restore(ts.id) is None
765 with pytest.raises(AttributeError):
766 self.app.GroupResult.restore(ts.id, backend=object())
767
768 def test_save_restore_empty(self):
769 subs = []
770 ts = self.app.GroupResult(uuid(), subs)
771 ts.save()
772 assert isinstance(
773 self.app.GroupResult.restore(ts.id),
774 self.app.GroupResult,
775 )
776 assert self.app.GroupResult.restore(ts.id).results == ts.results == []
777
778 def test_restore_app(self):
779 subs = [MockAsyncResultSuccess(uuid(), app=self.app)]
780 ts = self.app.GroupResult(uuid(), subs)
781 ts.save()
782 restored = GroupResult.restore(ts.id, app=self.app)
783 assert restored.id == ts.id
784
785 def test_restore_current_app_fallback(self):
786 subs = [MockAsyncResultSuccess(uuid(), app=self.app)]
787 ts = self.app.GroupResult(uuid(), subs)
788 ts.save()
789 with pytest.raises(RuntimeError,
790 match="Test depends on current_app"):
791 GroupResult.restore(ts.id)
792
793 def test_join_native(self):
794 backend = SimpleBackend()
795 results = [self.app.AsyncResult(uuid(), backend=backend)
796 for i in range(10)]
797 ts = self.app.GroupResult(uuid(), results)
798
799 with patch('celery.Celery.backend', new=backend):
800 backend.ids = [result.id for result in results]
801 res = ts.join_native()
802 assert res == list(range(10))
803 callback = Mock(name='callback')
804 assert not ts.join_native(callback=callback)
805 callback.assert_has_calls([
806 call(r.id, i) for i, r in enumerate(ts.results)
807 ])
808
809 def test_join_native_raises(self):
810 ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
811 ts.iter_native = Mock()
812 ts.iter_native.return_value = iter([
813 (uuid(), {'status': states.FAILURE, 'result': KeyError()})
814 ])
815 with pytest.raises(KeyError):
816 ts.join_native(propagate=True)
817
818 def test_failed_join_report(self):
819 res = Mock()
820 ts = self.app.GroupResult(uuid(), [res])
821 res.state = states.FAILURE
822 res.backend.is_cached.return_value = True
823 assert next(ts._failed_join_report()) is res
824 res.backend.is_cached.return_value = False
825 with pytest.raises(StopIteration):
826 next(ts._failed_join_report())
827
828 def test_repr(self):
829 assert repr(
830 self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())]))
831
832 def test_children_is_results(self):
833 ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
834 assert ts.children is ts.results
835
836 def test_iter_native(self):
837 backend = SimpleBackend()
838 results = [self.app.AsyncResult(uuid(), backend=backend)
839 for i in range(10)]
840 ts = self.app.GroupResult(uuid(), results)
841 with patch('celery.Celery.backend', new=backend):
842 backend.ids = [result.id for result in results]
843 assert len(list(ts.iter_native())) == 10
844
845 def test_join_timeout(self):
846 ar = MockAsyncResultSuccess(uuid(), app=self.app)
847 ar2 = MockAsyncResultSuccess(uuid(), app=self.app)
848 ar3 = self.app.AsyncResult(uuid())
849 ts = self.app.GroupResult(uuid(), [ar, ar2, ar3])
850 with pytest.raises(TimeoutError):
851 ts.join(timeout=0.0000001)
852
853 ar4 = self.app.AsyncResult(uuid())
854 ar4.get = Mock()
855 ts2 = self.app.GroupResult(uuid(), [ar4])
856 assert ts2.join(timeout=0.1)
857 callback = Mock(name='callback')
858 assert not ts2.join(timeout=0.1, callback=callback)
859 callback.assert_called_with(ar4.id, ar4.get())
860
861 def test_iter_native_when_empty_group(self):
862 ts = self.app.GroupResult(uuid(), [])
863 assert list(ts.iter_native()) == []
864
865 def test___iter__(self):
866 assert list(iter(self.ts)) == self.ts.results
867
868 def test_join(self):
869 joined = self.ts.join()
870 assert joined == list(range(self.size))
871
872 def test_successful(self):
873 assert self.ts.successful()
874
875 def test_failed(self):
876 assert not self.ts.failed()
877
878 def test_maybe_throw(self):
879 self.ts.results = [Mock(name='r1')]
880 self.ts.maybe_throw()
881 self.ts.results[0].maybe_throw.assert_called_with(
882 callback=None, propagate=True,
883 )
884
885 def test_join__on_message(self):
886 with pytest.raises(ImproperlyConfigured):
887 self.ts.join(on_message=Mock())
888
889 def test_waiting(self):
890 assert not self.ts.waiting()
891
892 def test_ready(self):
893 assert self.ts.ready()
894
895 def test_completed_count(self):
896 assert self.ts.completed_count() == len(self.ts)
897
898
899 class test_pending_AsyncResult:
900
901 def test_result(self, app):
902 res = app.AsyncResult(uuid())
903 assert res.result is None
904
905
906 class test_failed_AsyncResult:
907
908 def setup_method(self):
909 self.size = 11
910 self.app.conf.result_serializer = 'pickle'
911 results = make_mock_group(self.app, 10)
912 failed = mock_task('ts11', states.FAILURE, KeyError('Baz'))
913 save_result(self.app, failed)
914 failed_res = self.app.AsyncResult(failed['id'])
915 self.ts = self.app.GroupResult(uuid(), results + [failed_res])
916
917 def test_completed_count(self):
918 assert self.ts.completed_count() == len(self.ts) - 1
919
920 def test_join(self):
921 with pytest.raises(KeyError):
922 self.ts.join()
923
924 def test_successful(self):
925 assert not self.ts.successful()
926
927 def test_failed(self):
928 assert self.ts.failed()
929
930
931 class test_pending_Group:
932
933 def setup_method(self):
934 self.ts = self.app.GroupResult(
935 uuid(), [self.app.AsyncResult(uuid()),
936 self.app.AsyncResult(uuid())])
937
938 def test_completed_count(self):
939 assert self.ts.completed_count() == 0
940
941 def test_ready(self):
942 assert not self.ts.ready()
943
944 def test_waiting(self):
945 assert self.ts.waiting()
946
947 def test_join(self):
948 with pytest.raises(TimeoutError):
949 self.ts.join(timeout=0.001)
950
951 def test_join_longer(self):
952 with pytest.raises(TimeoutError):
953 self.ts.join(timeout=1)
954
955
956 class test_EagerResult:
957
958 def setup_method(self):
959 @self.app.task(shared=False)
960 def raising(x, y):
961 raise KeyError(x, y)
962 self.raising = raising
963
964 def test_wait_raises(self):
965 res = self.raising.apply(args=[3, 3])
966 with pytest.raises(KeyError):
967 res.wait()
968 assert res.wait(propagate=False)
969
970 def test_wait(self):
971 res = EagerResult('x', 'x', states.RETRY)
972 res.wait()
973 assert res.state == states.RETRY
974 assert res.status == states.RETRY
975
976 def test_forget(self):
977 res = EagerResult('x', 'x', states.RETRY)
978 res.forget()
979
980 def test_revoke(self):
981 res = self.raising.apply(args=[3, 3])
982 assert not res.revoke()
983
984 @patch('celery.result.task_join_will_block')
985 def test_get_sync_subtask_option(self, task_join_will_block):
986 task_join_will_block.return_value = True
987 tid = uuid()
988 res_subtask_async = EagerResult(tid, 'x', 'x', states.SUCCESS)
989 with pytest.raises(RuntimeError):
990 res_subtask_async.get()
991 res_subtask_async.get(disable_sync_subtasks=False)
992
993 def test_populate_name(self):
994 res = EagerResult('x', 'x', states.SUCCESS, None, 'test_task')
995 assert res.name == 'test_task'
996
997 res = EagerResult('x', 'x', states.SUCCESS, name='test_task_named_argument')
998 assert res.name == 'test_task_named_argument'
999
1000
1001 class test_tuples:
1002
1003 def test_AsyncResult(self):
1004 x = self.app.AsyncResult(uuid())
1005 assert x, result_from_tuple(x.as_tuple() == self.app)
1006 assert x, result_from_tuple(x == self.app)
1007
1008 def test_with_parent(self):
1009 x = self.app.AsyncResult(uuid())
1010 x.parent = self.app.AsyncResult(uuid())
1011 y = result_from_tuple(x.as_tuple(), self.app)
1012 assert y == x
1013 assert y.parent == x.parent
1014 assert isinstance(y.parent, AsyncResult)
1015
1016 def test_compat(self):
1017 uid = uuid()
1018 x = result_from_tuple([uid, []], app=self.app)
1019 assert x.id == uid
1020
1021 def test_as_list(self):
1022 uid = uuid()
1023 x = self.app.AsyncResult(uid)
1024 assert x.id == x.as_list()[0]
1025 assert isinstance(x.as_list(), list)
1026
1027 def test_GroupResult(self):
1028 x = self.app.GroupResult(
1029 uuid(), [self.app.AsyncResult(uuid()) for _ in range(10)],
1030 )
1031 assert x, result_from_tuple(x.as_tuple() == self.app)
1032 assert x, result_from_tuple(x == self.app)
1033
1034 def test_GroupResult_with_parent(self):
1035 parent = self.app.AsyncResult(uuid())
1036 result = self.app.GroupResult(
1037 uuid(), [self.app.AsyncResult(uuid()) for _ in range(10)],
1038 parent
1039 )
1040 second_result = result_from_tuple(result.as_tuple(), self.app)
1041 assert second_result == result
1042 assert second_result.parent == parent
1043
1044 def test_GroupResult_as_tuple(self):
1045 parent = self.app.AsyncResult(uuid())
1046 result = self.app.GroupResult(
1047 'group-result-1',
1048 [self.app.AsyncResult(f'async-result-{i}')
1049 for i in range(2)],
1050 parent
1051 )
1052 (result_id, parent_tuple), group_results = result.as_tuple()
1053 assert result_id == result.id
1054 assert parent_tuple == parent.as_tuple()
1055 assert parent_tuple[0][0] == parent.id
1056 assert isinstance(group_results, list)
1057 expected_grp_res = [((f'async-result-{i}', None), None)
1058 for i in range(2)]
1059 assert group_results == expected_grp_res