test_result.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. from __future__ import absolute_import, unicode_literals
  2. import copy
  3. import traceback
  4. from contextlib import contextmanager
  5. import pytest
  6. from case import Mock, call, patch, skip
  7. from celery import states, uuid
  8. from celery.backends.base import SyncBackendMixin
  9. from celery.exceptions import (CPendingDeprecationWarning,
  10. ImproperlyConfigured, IncompleteStream,
  11. TimeoutError)
  12. from celery.five import range
  13. from celery.result import (AsyncResult, EagerResult, GroupResult, ResultSet,
  14. assert_will_not_block, result_from_tuple)
  15. from celery.utils.serialization import pickle
  16. PYTRACEBACK = """\
  17. Traceback (most recent call last):
  18. File "foo.py", line 2, in foofunc
  19. don't matter
  20. File "bar.py", line 3, in barfunc
  21. don't matter
  22. Doesn't matter: really!\
  23. """
  24. def mock_task(name, state, result, traceback=None):
  25. return {
  26. 'id': uuid(), 'name': name, 'state': state,
  27. 'result': result, 'traceback': traceback,
  28. }
  29. def save_result(app, task):
  30. traceback = task.get('traceback') or 'Some traceback'
  31. if task['state'] == states.SUCCESS:
  32. app.backend.mark_as_done(task['id'], task['result'])
  33. elif task['state'] == states.RETRY:
  34. app.backend.mark_as_retry(
  35. task['id'], task['result'], traceback=traceback,
  36. )
  37. else:
  38. app.backend.mark_as_failure(
  39. task['id'], task['result'], traceback=traceback,
  40. )
  41. def make_mock_group(app, size=10):
  42. tasks = [mock_task('ts%d' % i, states.SUCCESS, i) for i in range(size)]
  43. [save_result(app, task) for task in tasks]
  44. return [app.AsyncResult(task['id']) for task in tasks]
  45. class _MockBackend:
  46. def add_pending_result(self, *args, **kwargs):
  47. return True
  48. def wait_for_pending(self, *args, **kwargs):
  49. return True
  50. class test_AsyncResult:
  51. def setup(self):
  52. self.app.conf.result_cache_max = 100
  53. self.app.conf.result_serializer = 'pickle'
  54. self.task1 = mock_task('task1', states.SUCCESS, 'the')
  55. self.task2 = mock_task('task2', states.SUCCESS, 'quick')
  56. self.task3 = mock_task('task3', states.FAILURE, KeyError('brown'))
  57. self.task4 = mock_task('task3', states.RETRY, KeyError('red'))
  58. self.task5 = mock_task(
  59. 'task3', states.FAILURE, KeyError('blue'), PYTRACEBACK,
  60. )
  61. for task in (self.task1, self.task2,
  62. self.task3, self.task4, self.task5):
  63. save_result(self.app, task)
  64. @self.app.task(shared=False)
  65. def mytask():
  66. pass
  67. self.mytask = mytask
  68. def test_ignored_getter(self):
  69. result = self.app.AsyncResult(uuid())
  70. assert result.ignored is False
  71. result.__delattr__('_ignored')
  72. assert result.ignored is False
  73. @patch('celery.result.task_join_will_block')
  74. def test_assert_will_not_block(self, task_join_will_block):
  75. task_join_will_block.return_value = True
  76. with pytest.raises(RuntimeError):
  77. assert_will_not_block()
  78. task_join_will_block.return_value = False
  79. assert_will_not_block()
  80. @patch('celery.result.task_join_will_block')
  81. def test_get_sync_subtask_option(self, task_join_will_block):
  82. task_join_will_block.return_value = True
  83. tid = uuid()
  84. backend = _MockBackend()
  85. res_subtask_async = AsyncResult(tid, backend=backend)
  86. with pytest.raises(RuntimeError):
  87. res_subtask_async.get()
  88. res_subtask_async.get(disable_sync_subtasks=False)
  89. def test_without_id(self):
  90. with pytest.raises(ValueError):
  91. AsyncResult(None, app=self.app)
  92. def test_compat_properties(self):
  93. x = self.app.AsyncResult('1')
  94. assert x.task_id == x.id
  95. x.task_id = '2'
  96. assert x.id == '2'
  97. @pytest.mark.usefixtures('depends_on_current_app')
  98. def test_reduce_direct(self):
  99. x = AsyncResult('1', app=self.app)
  100. fun, args = x.__reduce__()
  101. assert fun(*args) == x
  102. def test_children(self):
  103. x = self.app.AsyncResult('1')
  104. children = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
  105. x._cache = {'children': children, 'status': states.SUCCESS}
  106. x.backend = Mock()
  107. assert x.children
  108. assert len(x.children) == 3
  109. def test_propagates_for_parent(self):
  110. x = self.app.AsyncResult(uuid())
  111. x.backend = Mock(name='backend')
  112. x.backend.get_task_meta.return_value = {}
  113. x.backend.wait_for_pending.return_value = 84
  114. x.parent = EagerResult(uuid(), KeyError('foo'), states.FAILURE)
  115. with pytest.raises(KeyError):
  116. x.get(propagate=True)
  117. x.backend.wait_for_pending.assert_not_called()
  118. x.parent = EagerResult(uuid(), 42, states.SUCCESS)
  119. assert x.get(propagate=True) == 84
  120. x.backend.wait_for_pending.assert_called()
  121. def test_get_children(self):
  122. tid = uuid()
  123. x = self.app.AsyncResult(tid)
  124. child = [self.app.AsyncResult(uuid()).as_tuple()
  125. for i in range(10)]
  126. x._cache = {'children': child}
  127. assert x.children
  128. assert len(x.children) == 10
  129. x._cache = {'status': states.SUCCESS}
  130. x.backend._cache[tid] = {'result': None}
  131. assert x.children is None
  132. def test_build_graph_get_leaf_collect(self):
  133. x = self.app.AsyncResult('1')
  134. x.backend._cache['1'] = {'status': states.SUCCESS, 'result': None}
  135. c = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
  136. x.iterdeps = Mock()
  137. x.iterdeps.return_value = (
  138. (None, x),
  139. (x, c[0]),
  140. (c[0], c[1]),
  141. (c[1], c[2])
  142. )
  143. x.backend.READY_STATES = states.READY_STATES
  144. assert x.graph
  145. assert x.get_leaf() is 2
  146. it = x.collect()
  147. assert list(it) == [
  148. (x, None),
  149. (c[0], 0),
  150. (c[1], 1),
  151. (c[2], 2),
  152. ]
  153. def test_iterdeps(self):
  154. x = self.app.AsyncResult('1')
  155. c = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
  156. x._cache = {'status': states.SUCCESS, 'result': None, 'children': c}
  157. for child in c:
  158. child.backend = Mock()
  159. child.backend.get_children.return_value = []
  160. it = x.iterdeps()
  161. assert list(it) == [
  162. (None, x),
  163. (x, c[0]),
  164. (x, c[1]),
  165. (x, c[2]),
  166. ]
  167. x._cache = None
  168. x.ready = Mock()
  169. x.ready.return_value = False
  170. with pytest.raises(IncompleteStream):
  171. list(x.iterdeps())
  172. list(x.iterdeps(intermediate=True))
  173. def test_eq_not_implemented(self):
  174. assert self.app.AsyncResult('1') != object()
  175. @pytest.mark.usefixtures('depends_on_current_app')
  176. def test_reduce(self):
  177. a1 = self.app.AsyncResult('uuid')
  178. restored = pickle.loads(pickle.dumps(a1))
  179. assert restored.id == 'uuid'
  180. a2 = self.app.AsyncResult('uuid')
  181. assert pickle.loads(pickle.dumps(a2)).id == 'uuid'
  182. def test_maybe_set_cache_empty(self):
  183. self.app.AsyncResult('uuid')._maybe_set_cache(None)
  184. def test_set_cache__children(self):
  185. r1 = self.app.AsyncResult('id1')
  186. r2 = self.app.AsyncResult('id2')
  187. r1._set_cache({'children': [r2.as_tuple()]})
  188. assert r2 in r1.children
  189. def test_successful(self):
  190. ok_res = self.app.AsyncResult(self.task1['id'])
  191. nok_res = self.app.AsyncResult(self.task3['id'])
  192. nok_res2 = self.app.AsyncResult(self.task4['id'])
  193. assert ok_res.successful()
  194. assert not nok_res.successful()
  195. assert not nok_res2.successful()
  196. pending_res = self.app.AsyncResult(uuid())
  197. assert not pending_res.successful()
  198. def test_raising(self):
  199. notb = self.app.AsyncResult(self.task3['id'])
  200. withtb = self.app.AsyncResult(self.task5['id'])
  201. with pytest.raises(KeyError):
  202. notb.get()
  203. try:
  204. withtb.get()
  205. except KeyError:
  206. tb = traceback.format_exc()
  207. assert ' File "foo.py", line 2, in foofunc' not in tb
  208. assert ' File "bar.py", line 3, in barfunc' not in tb
  209. assert 'KeyError:' in tb
  210. assert "'blue'" in tb
  211. else:
  212. raise AssertionError('Did not raise KeyError.')
  213. @skip.unless_module('tblib')
  214. def test_raising_remote_tracebacks(self):
  215. withtb = self.app.AsyncResult(self.task5['id'])
  216. self.app.conf.task_remote_tracebacks = True
  217. try:
  218. withtb.get()
  219. except KeyError:
  220. tb = traceback.format_exc()
  221. assert ' File "foo.py", line 2, in foofunc' in tb
  222. assert ' File "bar.py", line 3, in barfunc' in tb
  223. assert 'KeyError:' in tb
  224. assert "'blue'" in tb
  225. else:
  226. raise AssertionError('Did not raise KeyError.')
  227. def test_str(self):
  228. ok_res = self.app.AsyncResult(self.task1['id'])
  229. ok2_res = self.app.AsyncResult(self.task2['id'])
  230. nok_res = self.app.AsyncResult(self.task3['id'])
  231. assert str(ok_res) == self.task1['id']
  232. assert str(ok2_res) == self.task2['id']
  233. assert str(nok_res) == self.task3['id']
  234. pending_id = uuid()
  235. pending_res = self.app.AsyncResult(pending_id)
  236. assert str(pending_res) == pending_id
  237. def test_repr(self):
  238. ok_res = self.app.AsyncResult(self.task1['id'])
  239. ok2_res = self.app.AsyncResult(self.task2['id'])
  240. nok_res = self.app.AsyncResult(self.task3['id'])
  241. assert repr(ok_res) == '<AsyncResult: %s>' % (self.task1['id'],)
  242. assert repr(ok2_res) == '<AsyncResult: %s>' % (self.task2['id'],)
  243. assert repr(nok_res) == '<AsyncResult: %s>' % (self.task3['id'],)
  244. pending_id = uuid()
  245. pending_res = self.app.AsyncResult(pending_id)
  246. assert repr(pending_res) == '<AsyncResult: %s>' % (pending_id,)
  247. def test_hash(self):
  248. assert (hash(self.app.AsyncResult('x0w991')) ==
  249. hash(self.app.AsyncResult('x0w991')))
  250. assert (hash(self.app.AsyncResult('x0w991')) !=
  251. hash(self.app.AsyncResult('x1w991')))
  252. def test_get_traceback(self):
  253. ok_res = self.app.AsyncResult(self.task1['id'])
  254. nok_res = self.app.AsyncResult(self.task3['id'])
  255. nok_res2 = self.app.AsyncResult(self.task4['id'])
  256. assert not ok_res.traceback
  257. assert nok_res.traceback
  258. assert nok_res2.traceback
  259. pending_res = self.app.AsyncResult(uuid())
  260. assert not pending_res.traceback
  261. def test_get__backend_gives_None(self):
  262. res = self.app.AsyncResult(self.task1['id'])
  263. res.backend.wait_for = Mock(name='wait_for')
  264. res.backend.wait_for.return_value = None
  265. assert res.get() is None
  266. def test_get(self):
  267. ok_res = self.app.AsyncResult(self.task1['id'])
  268. ok2_res = self.app.AsyncResult(self.task2['id'])
  269. nok_res = self.app.AsyncResult(self.task3['id'])
  270. nok2_res = self.app.AsyncResult(self.task4['id'])
  271. callback = Mock(name='callback')
  272. assert ok_res.get(callback=callback) == 'the'
  273. callback.assert_called_with(ok_res.id, 'the')
  274. assert ok2_res.get() == 'quick'
  275. with pytest.raises(KeyError):
  276. nok_res.get()
  277. assert nok_res.get(propagate=False)
  278. assert isinstance(nok2_res.result, KeyError)
  279. assert ok_res.info == 'the'
  280. def test_get_when_ignored(self):
  281. result = self.app.AsyncResult(uuid())
  282. result.ignored = True
  283. # Does not block
  284. assert result.get() is None
  285. def test_eq_ne(self):
  286. r1 = self.app.AsyncResult(self.task1['id'])
  287. r2 = self.app.AsyncResult(self.task1['id'])
  288. r3 = self.app.AsyncResult(self.task2['id'])
  289. assert r1 == r2
  290. assert r1 != r3
  291. assert r1 == r2.id
  292. assert r1 != r3.id
  293. @pytest.mark.usefixtures('depends_on_current_app')
  294. def test_reduce_restore(self):
  295. r1 = self.app.AsyncResult(self.task1['id'])
  296. fun, args = r1.__reduce__()
  297. assert fun(*args) == r1
  298. def test_get_timeout(self):
  299. res = self.app.AsyncResult(self.task4['id']) # has RETRY state
  300. with pytest.raises(TimeoutError):
  301. res.get(timeout=0.001)
  302. pending_res = self.app.AsyncResult(uuid())
  303. with patch('celery.result.time') as _time:
  304. with pytest.raises(TimeoutError):
  305. pending_res.get(timeout=0.001, interval=0.001)
  306. _time.sleep.assert_called_with(0.001)
  307. def test_get_timeout_longer(self):
  308. res = self.app.AsyncResult(self.task4['id']) # has RETRY state
  309. with patch('celery.result.time') as _time:
  310. with pytest.raises(TimeoutError):
  311. res.get(timeout=1, interval=1)
  312. _time.sleep.assert_called_with(1)
  313. def test_ready(self):
  314. oks = (self.app.AsyncResult(self.task1['id']),
  315. self.app.AsyncResult(self.task2['id']),
  316. self.app.AsyncResult(self.task3['id']))
  317. assert all(result.ready() for result in oks)
  318. assert not self.app.AsyncResult(self.task4['id']).ready()
  319. assert not self.app.AsyncResult(uuid()).ready()
  320. def test_del(self):
  321. with patch('celery.result.AsyncResult.backend') as backend:
  322. result = self.app.AsyncResult(self.task1['id'])
  323. result_clone = copy.copy(result)
  324. del result
  325. assert backend.remove_pending_result.called_once_with(
  326. result_clone
  327. )
  328. result = self.app.AsyncResult(self.task1['id'])
  329. result.backend = None
  330. del result
  331. class test_ResultSet:
  332. def test_resultset_repr(self):
  333. assert repr(self.app.ResultSet(
  334. [self.app.AsyncResult(t) for t in ['1', '2', '3']]))
  335. def test_eq_other(self):
  336. assert self.app.ResultSet([
  337. self.app.AsyncResult(t) for t in [1, 3, 3]]) != 1
  338. rs1 = self.app.ResultSet([self.app.AsyncResult(1)])
  339. rs2 = self.app.ResultSet([self.app.AsyncResult(1)])
  340. assert rs1 == rs2
  341. def test_get(self):
  342. x = self.app.ResultSet([self.app.AsyncResult(t) for t in [1, 2, 3]])
  343. b = x.results[0].backend = Mock()
  344. b.supports_native_join = False
  345. x.join_native = Mock()
  346. x.join = Mock()
  347. x.get()
  348. x.join.assert_called()
  349. b.supports_native_join = True
  350. x.get()
  351. x.join_native.assert_called()
  352. def test_eq_ne(self):
  353. g1 = self.app.ResultSet([
  354. self.app.AsyncResult('id1'),
  355. self.app.AsyncResult('id2'),
  356. ])
  357. g2 = self.app.ResultSet([
  358. self.app.AsyncResult('id1'),
  359. self.app.AsyncResult('id2'),
  360. ])
  361. g3 = self.app.ResultSet([
  362. self.app.AsyncResult('id3'),
  363. self.app.AsyncResult('id1'),
  364. ])
  365. assert g1 == g2
  366. assert g1 != g3
  367. assert g1 != object()
  368. def test_takes_app_from_first_task(self):
  369. x = ResultSet([self.app.AsyncResult('id1')])
  370. assert x.app is x.results[0].app
  371. x.app = self.app
  372. assert x.app is self.app
  373. def test_get_empty(self):
  374. x = self.app.ResultSet([])
  375. assert x.supports_native_join is None
  376. x.join = Mock(name='join')
  377. x.get()
  378. x.join.assert_called()
  379. def test_add(self):
  380. x = self.app.ResultSet([self.app.AsyncResult(1)])
  381. x.add(self.app.AsyncResult(2))
  382. assert len(x) == 2
  383. x.add(self.app.AsyncResult(2))
  384. assert len(x) == 2
  385. @contextmanager
  386. def dummy_copy(self):
  387. with patch('celery.result.copy') as copy:
  388. def passt(arg):
  389. return arg
  390. copy.side_effect = passt
  391. yield
  392. def test_iterate_respects_subpolling_interval(self):
  393. r1 = self.app.AsyncResult(uuid())
  394. r2 = self.app.AsyncResult(uuid())
  395. backend = r1.backend = r2.backend = Mock()
  396. backend.subpolling_interval = 10
  397. ready = r1.ready = r2.ready = Mock()
  398. def se(*args, **kwargs):
  399. ready.side_effect = KeyError()
  400. return False
  401. ready.return_value = False
  402. ready.side_effect = se
  403. x = self.app.ResultSet([r1, r2])
  404. with self.dummy_copy():
  405. with patch('celery.result.time') as _time:
  406. with pytest.warns(CPendingDeprecationWarning):
  407. with pytest.raises(KeyError):
  408. list(x.iterate())
  409. _time.sleep.assert_called_with(10)
  410. backend.subpolling_interval = 0
  411. with patch('celery.result.time') as _time:
  412. with pytest.warns(CPendingDeprecationWarning):
  413. with pytest.raises(KeyError):
  414. ready.return_value = False
  415. ready.side_effect = se
  416. list(x.iterate())
  417. _time.sleep.assert_not_called()
  418. def test_times_out(self):
  419. r1 = self.app.AsyncResult(uuid)
  420. r1.ready = Mock()
  421. r1.ready.return_value = False
  422. x = self.app.ResultSet([r1])
  423. with self.dummy_copy():
  424. with patch('celery.result.time'):
  425. with pytest.warns(CPendingDeprecationWarning):
  426. with pytest.raises(TimeoutError):
  427. list(x.iterate(timeout=1))
  428. def test_add_discard(self):
  429. x = self.app.ResultSet([])
  430. x.add(self.app.AsyncResult('1'))
  431. assert self.app.AsyncResult('1') in x.results
  432. x.discard(self.app.AsyncResult('1'))
  433. x.discard(self.app.AsyncResult('1'))
  434. x.discard('1')
  435. assert self.app.AsyncResult('1') not in x.results
  436. x.update([self.app.AsyncResult('2')])
  437. def test_clear(self):
  438. x = self.app.ResultSet([])
  439. r = x.results
  440. x.clear()
  441. assert x.results is r
  442. class MockAsyncResultFailure(AsyncResult):
  443. @property
  444. def result(self):
  445. return KeyError('baz')
  446. @property
  447. def state(self):
  448. return states.FAILURE
  449. def get(self, propagate=True, **kwargs):
  450. if propagate:
  451. raise self.result
  452. return self.result
  453. class MockAsyncResultSuccess(AsyncResult):
  454. forgotten = False
  455. def __init__(self, *args, **kwargs):
  456. self._result = kwargs.pop('result', 42)
  457. super(MockAsyncResultSuccess, self).__init__(*args, **kwargs)
  458. def forget(self):
  459. self.forgotten = True
  460. @property
  461. def result(self):
  462. return self._result
  463. @property
  464. def state(self):
  465. return states.SUCCESS
  466. def get(self, **kwargs):
  467. return self.result
  468. class SimpleBackend(SyncBackendMixin):
  469. ids = []
  470. def __init__(self, ids=[]):
  471. self.ids = ids
  472. def _ensure_not_eager(self):
  473. pass
  474. def get_many(self, *args, **kwargs):
  475. return ((id, {'result': i, 'status': states.SUCCESS})
  476. for i, id in enumerate(self.ids))
  477. class test_GroupResult:
  478. def setup(self):
  479. self.size = 10
  480. self.ts = self.app.GroupResult(
  481. uuid(), make_mock_group(self.app, self.size),
  482. )
  483. @pytest.mark.usefixtures('depends_on_current_app')
  484. def test_is_pickleable(self):
  485. ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  486. assert pickle.loads(pickle.dumps(ts)) == ts
  487. ts2 = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  488. assert pickle.loads(pickle.dumps(ts2)) == ts2
  489. @pytest.mark.usefixtures('depends_on_current_app')
  490. def test_reduce(self):
  491. ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  492. fun, args = ts.__reduce__()
  493. ts2 = fun(*args)
  494. assert ts2.id == ts.id
  495. assert ts == ts2
  496. def test_eq_ne(self):
  497. ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  498. ts2 = self.app.GroupResult(ts.id, ts.results)
  499. ts3 = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  500. ts4 = self.app.GroupResult(ts.id, [self.app.AsyncResult(uuid())])
  501. assert ts == ts2
  502. assert ts != ts3
  503. assert ts != ts4
  504. assert ts != object()
  505. def test_len(self):
  506. assert len(self.ts) == self.size
  507. def test_eq_other(self):
  508. assert self.ts != 1
  509. def test_eq_with_parent(self):
  510. # GroupResult instances with different .parent are not equal
  511. grp_res = self.app.GroupResult(
  512. uuid(), [self.app.AsyncResult(uuid()) for _ in range(10)],
  513. parent=self.app.AsyncResult(uuid())
  514. )
  515. grp_res_2 = self.app.GroupResult(grp_res.id, grp_res.results)
  516. assert grp_res != grp_res_2
  517. grp_res_2.parent = self.app.AsyncResult(uuid())
  518. assert grp_res != grp_res_2
  519. grp_res_2.parent = grp_res.parent
  520. assert grp_res == grp_res_2
  521. @pytest.mark.usefixtures('depends_on_current_app')
  522. def test_pickleable(self):
  523. assert pickle.loads(pickle.dumps(self.ts))
  524. def test_iterate_raises(self):
  525. ar = MockAsyncResultFailure(uuid(), app=self.app)
  526. ts = self.app.GroupResult(uuid(), [ar])
  527. with pytest.warns(CPendingDeprecationWarning):
  528. it = ts.iterate()
  529. with pytest.raises(KeyError):
  530. next(it)
  531. def test_forget(self):
  532. subs = [MockAsyncResultSuccess(uuid(), app=self.app),
  533. MockAsyncResultSuccess(uuid(), app=self.app)]
  534. ts = self.app.GroupResult(uuid(), subs)
  535. ts.forget()
  536. for sub in subs:
  537. assert sub.forgotten
  538. def test_get_nested_without_native_join(self):
  539. backend = SimpleBackend()
  540. backend.supports_native_join = False
  541. ts = self.app.GroupResult(uuid(), [
  542. MockAsyncResultSuccess(uuid(), result='1.1',
  543. app=self.app, backend=backend),
  544. self.app.GroupResult(uuid(), [
  545. MockAsyncResultSuccess(uuid(), result='2.1',
  546. app=self.app, backend=backend),
  547. self.app.GroupResult(uuid(), [
  548. MockAsyncResultSuccess(uuid(), result='3.1',
  549. app=self.app, backend=backend),
  550. MockAsyncResultSuccess(uuid(), result='3.2',
  551. app=self.app, backend=backend),
  552. ]),
  553. ]),
  554. ])
  555. ts.app.backend = backend
  556. vals = ts.get()
  557. assert vals == [
  558. '1.1',
  559. [
  560. '2.1',
  561. [
  562. '3.1',
  563. '3.2',
  564. ]
  565. ],
  566. ]
  567. def test_getitem(self):
  568. subs = [MockAsyncResultSuccess(uuid(), app=self.app),
  569. MockAsyncResultSuccess(uuid(), app=self.app)]
  570. ts = self.app.GroupResult(uuid(), subs)
  571. assert ts[0] is subs[0]
  572. def test_save_restore(self):
  573. subs = [MockAsyncResultSuccess(uuid(), app=self.app),
  574. MockAsyncResultSuccess(uuid(), app=self.app)]
  575. ts = self.app.GroupResult(uuid(), subs)
  576. ts.save()
  577. with pytest.raises(AttributeError):
  578. ts.save(backend=object())
  579. assert self.app.GroupResult.restore(ts.id).results == ts.results
  580. ts.delete()
  581. assert self.app.GroupResult.restore(ts.id) is None
  582. with pytest.raises(AttributeError):
  583. self.app.GroupResult.restore(ts.id, backend=object())
  584. def test_save_restore_empty(self):
  585. subs = []
  586. ts = self.app.GroupResult(uuid(), subs)
  587. ts.save()
  588. assert isinstance(
  589. self.app.GroupResult.restore(ts.id),
  590. self.app.GroupResult,
  591. )
  592. assert self.app.GroupResult.restore(ts.id).results == ts.results == []
  593. def test_restore_app(self):
  594. subs = [MockAsyncResultSuccess(uuid(), app=self.app)]
  595. ts = self.app.GroupResult(uuid(), subs)
  596. ts.save()
  597. restored = GroupResult.restore(ts.id, app=self.app)
  598. assert restored.id == ts.id
  599. def test_restore_current_app_fallback(self):
  600. subs = [MockAsyncResultSuccess(uuid(), app=self.app)]
  601. ts = self.app.GroupResult(uuid(), subs)
  602. ts.save()
  603. with pytest.raises(RuntimeError,
  604. message="Test depends on current_app"):
  605. GroupResult.restore(ts.id)
  606. def test_join_native(self):
  607. backend = SimpleBackend()
  608. results = [self.app.AsyncResult(uuid(), backend=backend)
  609. for i in range(10)]
  610. ts = self.app.GroupResult(uuid(), results)
  611. ts.app.backend = backend
  612. backend.ids = [result.id for result in results]
  613. res = ts.join_native()
  614. assert res == list(range(10))
  615. callback = Mock(name='callback')
  616. assert not ts.join_native(callback=callback)
  617. callback.assert_has_calls([
  618. call(r.id, i) for i, r in enumerate(ts.results)
  619. ])
  620. def test_join_native_raises(self):
  621. ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  622. ts.iter_native = Mock()
  623. ts.iter_native.return_value = iter([
  624. (uuid(), {'status': states.FAILURE, 'result': KeyError()})
  625. ])
  626. with pytest.raises(KeyError):
  627. ts.join_native(propagate=True)
  628. def test_failed_join_report(self):
  629. res = Mock()
  630. ts = self.app.GroupResult(uuid(), [res])
  631. res.state = states.FAILURE
  632. res.backend.is_cached.return_value = True
  633. assert next(ts._failed_join_report()) is res
  634. res.backend.is_cached.return_value = False
  635. with pytest.raises(StopIteration):
  636. next(ts._failed_join_report())
  637. def test_repr(self):
  638. assert repr(
  639. self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())]))
  640. def test_children_is_results(self):
  641. ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  642. assert ts.children is ts.results
  643. def test_iter_native(self):
  644. backend = SimpleBackend()
  645. results = [self.app.AsyncResult(uuid(), backend=backend)
  646. for i in range(10)]
  647. ts = self.app.GroupResult(uuid(), results)
  648. ts.app.backend = backend
  649. backend.ids = [result.id for result in results]
  650. assert len(list(ts.iter_native())) == 10
  651. def test_iterate_yields(self):
  652. ar = MockAsyncResultSuccess(uuid(), app=self.app)
  653. ar2 = MockAsyncResultSuccess(uuid(), app=self.app)
  654. ts = self.app.GroupResult(uuid(), [ar, ar2])
  655. with pytest.warns(CPendingDeprecationWarning):
  656. it = ts.iterate()
  657. assert next(it) == 42
  658. assert next(it) == 42
  659. def test_iterate_eager(self):
  660. ar1 = EagerResult(uuid(), 42, states.SUCCESS)
  661. ar2 = EagerResult(uuid(), 42, states.SUCCESS)
  662. ts = self.app.GroupResult(uuid(), [ar1, ar2])
  663. with pytest.warns(CPendingDeprecationWarning):
  664. it = ts.iterate()
  665. assert next(it) == 42
  666. assert next(it) == 42
  667. def test_join_timeout(self):
  668. ar = MockAsyncResultSuccess(uuid(), app=self.app)
  669. ar2 = MockAsyncResultSuccess(uuid(), app=self.app)
  670. ar3 = self.app.AsyncResult(uuid())
  671. ts = self.app.GroupResult(uuid(), [ar, ar2, ar3])
  672. with pytest.raises(TimeoutError):
  673. ts.join(timeout=0.0000001)
  674. ar4 = self.app.AsyncResult(uuid())
  675. ar4.get = Mock()
  676. ts2 = self.app.GroupResult(uuid(), [ar4])
  677. assert ts2.join(timeout=0.1)
  678. callback = Mock(name='callback')
  679. assert not ts2.join(timeout=0.1, callback=callback)
  680. callback.assert_called_with(ar4.id, ar4.get())
  681. def test_iter_native_when_empty_group(self):
  682. ts = self.app.GroupResult(uuid(), [])
  683. assert list(ts.iter_native()) == []
  684. def test_iterate_simple(self):
  685. with pytest.warns(CPendingDeprecationWarning):
  686. it = self.ts.iterate()
  687. results = sorted(list(it))
  688. assert results == list(range(self.size))
  689. def test___iter__(self):
  690. assert list(iter(self.ts)) == self.ts.results
  691. def test_join(self):
  692. joined = self.ts.join()
  693. assert joined == list(range(self.size))
  694. def test_successful(self):
  695. assert self.ts.successful()
  696. def test_failed(self):
  697. assert not self.ts.failed()
  698. def test_maybe_throw(self):
  699. self.ts.results = [Mock(name='r1')]
  700. self.ts.maybe_throw()
  701. self.ts.results[0].maybe_throw.assert_called_with(
  702. callback=None, propagate=True,
  703. )
  704. def test_join__on_message(self):
  705. with pytest.raises(ImproperlyConfigured):
  706. self.ts.join(on_message=Mock())
  707. def test_waiting(self):
  708. assert not self.ts.waiting()
  709. def test_ready(self):
  710. assert self.ts.ready()
  711. def test_completed_count(self):
  712. assert self.ts.completed_count() == len(self.ts)
  713. class test_pending_AsyncResult:
  714. def test_result(self, app):
  715. res = app.AsyncResult(uuid())
  716. assert res.result is None
  717. class test_failed_AsyncResult:
  718. def setup(self):
  719. self.size = 11
  720. self.app.conf.result_serializer = 'pickle'
  721. results = make_mock_group(self.app, 10)
  722. failed = mock_task('ts11', states.FAILURE, KeyError('Baz'))
  723. save_result(self.app, failed)
  724. failed_res = self.app.AsyncResult(failed['id'])
  725. self.ts = self.app.GroupResult(uuid(), results + [failed_res])
  726. def test_completed_count(self):
  727. assert self.ts.completed_count() == len(self.ts) - 1
  728. def test_iterate_simple(self):
  729. with pytest.warns(CPendingDeprecationWarning):
  730. it = self.ts.iterate()
  731. def consume():
  732. return list(it)
  733. with pytest.raises(KeyError):
  734. consume()
  735. def test_join(self):
  736. with pytest.raises(KeyError):
  737. self.ts.join()
  738. def test_successful(self):
  739. assert not self.ts.successful()
  740. def test_failed(self):
  741. assert self.ts.failed()
  742. class test_pending_Group:
  743. def setup(self):
  744. self.ts = self.app.GroupResult(
  745. uuid(), [self.app.AsyncResult(uuid()),
  746. self.app.AsyncResult(uuid())])
  747. def test_completed_count(self):
  748. assert self.ts.completed_count() == 0
  749. def test_ready(self):
  750. assert not self.ts.ready()
  751. def test_waiting(self):
  752. assert self.ts.waiting()
  753. def test_join(self):
  754. with pytest.raises(TimeoutError):
  755. self.ts.join(timeout=0.001)
  756. def test_join_longer(self):
  757. with pytest.raises(TimeoutError):
  758. self.ts.join(timeout=1)
  759. class test_EagerResult:
  760. def setup(self):
  761. @self.app.task(shared=False)
  762. def raising(x, y):
  763. raise KeyError(x, y)
  764. self.raising = raising
  765. def test_wait_raises(self):
  766. res = self.raising.apply(args=[3, 3])
  767. with pytest.raises(KeyError):
  768. res.wait()
  769. assert res.wait(propagate=False)
  770. def test_wait(self):
  771. res = EagerResult('x', 'x', states.RETRY)
  772. res.wait()
  773. assert res.state == states.RETRY
  774. assert res.status == states.RETRY
  775. def test_forget(self):
  776. res = EagerResult('x', 'x', states.RETRY)
  777. res.forget()
  778. def test_revoke(self):
  779. res = self.raising.apply(args=[3, 3])
  780. assert not res.revoke()
  781. @patch('celery.result.task_join_will_block')
  782. def test_get_sync_subtask_option(self, task_join_will_block):
  783. task_join_will_block.return_value = True
  784. tid = uuid()
  785. res_subtask_async = EagerResult(tid, 'x', 'x', states.SUCCESS)
  786. with pytest.raises(RuntimeError):
  787. res_subtask_async.get()
  788. res_subtask_async.get(disable_sync_subtasks=False)
  789. class test_tuples:
  790. def test_AsyncResult(self):
  791. x = self.app.AsyncResult(uuid())
  792. assert x, result_from_tuple(x.as_tuple() == self.app)
  793. assert x, result_from_tuple(x == self.app)
  794. def test_with_parent(self):
  795. x = self.app.AsyncResult(uuid())
  796. x.parent = self.app.AsyncResult(uuid())
  797. y = result_from_tuple(x.as_tuple(), self.app)
  798. assert y == x
  799. assert y.parent == x.parent
  800. assert isinstance(y.parent, AsyncResult)
  801. def test_compat(self):
  802. uid = uuid()
  803. x = result_from_tuple([uid, []], app=self.app)
  804. assert x.id == uid
  805. def test_GroupResult(self):
  806. x = self.app.GroupResult(
  807. uuid(), [self.app.AsyncResult(uuid()) for _ in range(10)],
  808. )
  809. assert x, result_from_tuple(x.as_tuple() == self.app)
  810. assert x, result_from_tuple(x == self.app)
  811. def test_GroupResult_with_parent(self):
  812. parent = self.app.AsyncResult(uuid())
  813. result = self.app.GroupResult(
  814. uuid(), [self.app.AsyncResult(uuid()) for _ in range(10)],
  815. parent
  816. )
  817. second_result = result_from_tuple(result.as_tuple(), self.app)
  818. assert second_result == result
  819. assert second_result.parent == parent
  820. def test_GroupResult_as_tuple(self):
  821. parent = self.app.AsyncResult(uuid())
  822. result = self.app.GroupResult(
  823. 'group-result-1',
  824. [self.app.AsyncResult('async-result-{}'.format(i))
  825. for i in range(2)],
  826. parent
  827. )
  828. (result_id, parent_tuple), group_results = result.as_tuple()
  829. assert result_id == result.id
  830. assert parent_tuple == parent.as_tuple()
  831. assert parent_tuple[0][0] == parent.id
  832. assert isinstance(group_results, list)
  833. expected_grp_res = [(('async-result-{}'.format(i), None), None)
  834. for i in range(2)]
  835. assert group_results == expected_grp_res