test_result.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. from __future__ import absolute_import
  2. from contextlib import contextmanager
  3. from celery import states
  4. from celery.exceptions import (
  5. ImproperlyConfigured, IncompleteStream, TimeoutError,
  6. )
  7. from celery.five import range
  8. from celery.result import (
  9. AsyncResult,
  10. EagerResult,
  11. ResultSet,
  12. result_from_tuple,
  13. assert_will_not_block,
  14. )
  15. from celery.utils import uuid
  16. from celery.utils.serialization import pickle
  17. from celery.tests.case import (
  18. AppCase, Mock, call, depends_on_current_app, patch,
  19. )
  20. def mock_task(name, state, result):
  21. return dict(id=uuid(), name=name, state=state, result=result)
  22. def save_result(app, task):
  23. traceback = 'Some traceback'
  24. if task['state'] == states.SUCCESS:
  25. app.backend.mark_as_done(task['id'], task['result'])
  26. elif task['state'] == states.RETRY:
  27. app.backend.mark_as_retry(
  28. task['id'], task['result'], traceback=traceback,
  29. )
  30. else:
  31. app.backend.mark_as_failure(
  32. task['id'], task['result'], traceback=traceback,
  33. )
  34. def make_mock_group(app, size=10):
  35. tasks = [mock_task('ts%d' % i, states.SUCCESS, i) for i in range(size)]
  36. [save_result(app, task) for task in tasks]
  37. return [app.AsyncResult(task['id']) for task in tasks]
  38. class test_AsyncResult(AppCase):
  39. def setup(self):
  40. self.app.conf.result_serializer = 'pickle'
  41. self.task1 = mock_task('task1', states.SUCCESS, 'the')
  42. self.task2 = mock_task('task2', states.SUCCESS, 'quick')
  43. self.task3 = mock_task('task3', states.FAILURE, KeyError('brown'))
  44. self.task4 = mock_task('task3', states.RETRY, KeyError('red'))
  45. for task in (self.task1, self.task2, self.task3, self.task4):
  46. save_result(self.app, task)
  47. @self.app.task(shared=False)
  48. def mytask():
  49. pass
  50. self.mytask = mytask
  51. @patch('celery.result.task_join_will_block')
  52. def test_assert_will_not_block(self, task_join_will_block):
  53. task_join_will_block.return_value = True
  54. with self.assertRaises(RuntimeError):
  55. assert_will_not_block()
  56. task_join_will_block.return_value = False
  57. assert_will_not_block()
  58. def test_without_id(self):
  59. with self.assertRaises(ValueError):
  60. AsyncResult(None, app=self.app)
  61. def test_compat_properties(self):
  62. x = self.app.AsyncResult('1')
  63. self.assertEqual(x.task_id, x.id)
  64. x.task_id = '2'
  65. self.assertEqual(x.id, '2')
  66. @depends_on_current_app
  67. def test_reduce_direct(self):
  68. x = AsyncResult('1', app=self.app)
  69. fun, args = x.__reduce__()
  70. self.assertEqual(fun(*args), x)
  71. def test_children(self):
  72. x = self.app.AsyncResult('1')
  73. children = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
  74. x._cache = {'children': children, 'status': states.SUCCESS}
  75. x.backend = Mock()
  76. self.assertTrue(x.children)
  77. self.assertEqual(len(x.children), 3)
  78. def test_propagates_for_parent(self):
  79. x = self.app.AsyncResult(uuid())
  80. x.backend = Mock(name='backend')
  81. x.backend.get_task_meta.return_value = {}
  82. x.backend.wait_for.return_value = {
  83. 'status': states.SUCCESS, 'result': 84,
  84. }
  85. x.parent = EagerResult(uuid(), KeyError('foo'), states.FAILURE)
  86. with self.assertRaises(KeyError):
  87. x.get(propagate=True)
  88. self.assertFalse(x.backend.wait_for.called)
  89. x.parent = EagerResult(uuid(), 42, states.SUCCESS)
  90. self.assertEqual(x.get(propagate=True), 84)
  91. self.assertTrue(x.backend.wait_for.called)
  92. def test_get_children(self):
  93. tid = uuid()
  94. x = self.app.AsyncResult(tid)
  95. child = [self.app.AsyncResult(uuid()).as_tuple()
  96. for i in range(10)]
  97. x._cache = {'children': child}
  98. self.assertTrue(x.children)
  99. self.assertEqual(len(x.children), 10)
  100. x._cache = {'status': states.SUCCESS}
  101. x.backend._cache[tid] = {'result': None}
  102. self.assertIsNone(x.children)
  103. def test_build_graph_get_leaf_collect(self):
  104. x = self.app.AsyncResult('1')
  105. x.backend._cache['1'] = {'status': states.SUCCESS, 'result': None}
  106. c = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
  107. x.iterdeps = Mock()
  108. x.iterdeps.return_value = (
  109. (None, x),
  110. (x, c[0]),
  111. (c[0], c[1]),
  112. (c[1], c[2])
  113. )
  114. x.backend.READY_STATES = states.READY_STATES
  115. self.assertTrue(x.graph)
  116. self.assertIs(x.get_leaf(), 2)
  117. it = x.collect()
  118. self.assertListEqual(list(it), [
  119. (x, None),
  120. (c[0], 0),
  121. (c[1], 1),
  122. (c[2], 2),
  123. ])
  124. def test_iterdeps(self):
  125. x = self.app.AsyncResult('1')
  126. c = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
  127. x._cache = {'status': states.SUCCESS, 'result': None, 'children': c}
  128. for child in c:
  129. child.backend = Mock()
  130. child.backend.get_children.return_value = []
  131. it = x.iterdeps()
  132. self.assertListEqual(list(it), [
  133. (None, x),
  134. (x, c[0]),
  135. (x, c[1]),
  136. (x, c[2]),
  137. ])
  138. x._cache = None
  139. x.ready = Mock()
  140. x.ready.return_value = False
  141. with self.assertRaises(IncompleteStream):
  142. list(x.iterdeps())
  143. list(x.iterdeps(intermediate=True))
  144. def test_eq_not_implemented(self):
  145. self.assertFalse(self.app.AsyncResult('1') == object())
  146. @depends_on_current_app
  147. def test_reduce(self):
  148. a1 = self.app.AsyncResult('uuid', task_name=self.mytask.name)
  149. restored = pickle.loads(pickle.dumps(a1))
  150. self.assertEqual(restored.id, 'uuid')
  151. self.assertEqual(restored.task_name, self.mytask.name)
  152. a2 = self.app.AsyncResult('uuid')
  153. self.assertEqual(pickle.loads(pickle.dumps(a2)).id, 'uuid')
  154. def test_maybe_set_cache_empty(self):
  155. self.app.AsyncResult('uuid')._maybe_set_cache(None)
  156. def test_set_cache__children(self):
  157. r1 = self.app.AsyncResult('id1')
  158. r2 = self.app.AsyncResult('id2')
  159. r1._set_cache({'children': [r2.as_tuple()]})
  160. self.assertIn(r2, r1.children)
  161. def test_successful(self):
  162. ok_res = self.app.AsyncResult(self.task1['id'])
  163. nok_res = self.app.AsyncResult(self.task3['id'])
  164. nok_res2 = self.app.AsyncResult(self.task4['id'])
  165. self.assertTrue(ok_res.successful())
  166. self.assertFalse(nok_res.successful())
  167. self.assertFalse(nok_res2.successful())
  168. pending_res = self.app.AsyncResult(uuid())
  169. self.assertFalse(pending_res.successful())
  170. def test_str(self):
  171. ok_res = self.app.AsyncResult(self.task1['id'])
  172. ok2_res = self.app.AsyncResult(self.task2['id'])
  173. nok_res = self.app.AsyncResult(self.task3['id'])
  174. self.assertEqual(str(ok_res), self.task1['id'])
  175. self.assertEqual(str(ok2_res), self.task2['id'])
  176. self.assertEqual(str(nok_res), self.task3['id'])
  177. pending_id = uuid()
  178. pending_res = self.app.AsyncResult(pending_id)
  179. self.assertEqual(str(pending_res), pending_id)
  180. def test_repr(self):
  181. ok_res = self.app.AsyncResult(self.task1['id'])
  182. ok2_res = self.app.AsyncResult(self.task2['id'])
  183. nok_res = self.app.AsyncResult(self.task3['id'])
  184. self.assertEqual(repr(ok_res), '<AsyncResult: %s>' % (
  185. self.task1['id']))
  186. self.assertEqual(repr(ok2_res), '<AsyncResult: %s>' % (
  187. self.task2['id']))
  188. self.assertEqual(repr(nok_res), '<AsyncResult: %s>' % (
  189. self.task3['id']))
  190. pending_id = uuid()
  191. pending_res = self.app.AsyncResult(pending_id)
  192. self.assertEqual(repr(pending_res), '<AsyncResult: %s>' % (
  193. pending_id))
  194. def test_hash(self):
  195. self.assertEqual(hash(self.app.AsyncResult('x0w991')),
  196. hash(self.app.AsyncResult('x0w991')))
  197. self.assertNotEqual(hash(self.app.AsyncResult('x0w991')),
  198. hash(self.app.AsyncResult('x1w991')))
  199. def test_get_traceback(self):
  200. ok_res = self.app.AsyncResult(self.task1['id'])
  201. nok_res = self.app.AsyncResult(self.task3['id'])
  202. nok_res2 = self.app.AsyncResult(self.task4['id'])
  203. self.assertFalse(ok_res.traceback)
  204. self.assertTrue(nok_res.traceback)
  205. self.assertTrue(nok_res2.traceback)
  206. pending_res = self.app.AsyncResult(uuid())
  207. self.assertFalse(pending_res.traceback)
  208. def test_get__backend_gives_None(self):
  209. res = self.app.AsyncResult(self.task1['id'])
  210. res.backend.wait_for = Mock(name='wait_for')
  211. res.backend.wait_for.return_value = None
  212. self.assertIsNone(res.get())
  213. def test_get(self):
  214. ok_res = self.app.AsyncResult(self.task1['id'])
  215. ok2_res = self.app.AsyncResult(self.task2['id'])
  216. nok_res = self.app.AsyncResult(self.task3['id'])
  217. nok2_res = self.app.AsyncResult(self.task4['id'])
  218. callback = Mock(name='callback')
  219. self.assertEqual(ok_res.get(callback=callback), 'the')
  220. callback.assert_called_with(ok_res.id, 'the')
  221. self.assertEqual(ok2_res.get(), 'quick')
  222. with self.assertRaises(KeyError):
  223. nok_res.get()
  224. self.assertTrue(nok_res.get(propagate=False))
  225. self.assertIsInstance(nok2_res.result, KeyError)
  226. self.assertEqual(ok_res.info, 'the')
  227. def test_eq_ne(self):
  228. r1 = self.app.AsyncResult(self.task1['id'])
  229. r2 = self.app.AsyncResult(self.task1['id'])
  230. r3 = self.app.AsyncResult(self.task2['id'])
  231. self.assertEqual(r1, r2)
  232. self.assertNotEqual(r1, r3)
  233. self.assertEqual(r1, r2.id)
  234. self.assertNotEqual(r1, r3.id)
  235. @depends_on_current_app
  236. def test_reduce_restore(self):
  237. r1 = self.app.AsyncResult(self.task1['id'])
  238. fun, args = r1.__reduce__()
  239. self.assertEqual(fun(*args), r1)
  240. def test_get_timeout(self):
  241. res = self.app.AsyncResult(self.task4['id']) # has RETRY state
  242. with self.assertRaises(TimeoutError):
  243. res.get(timeout=0.001)
  244. pending_res = self.app.AsyncResult(uuid())
  245. with patch('celery.result.time') as _time:
  246. with self.assertRaises(TimeoutError):
  247. pending_res.get(timeout=0.001, interval=0.001)
  248. _time.sleep.assert_called_with(0.001)
  249. def test_get_timeout_longer(self):
  250. res = self.app.AsyncResult(self.task4['id']) # has RETRY state
  251. with patch('celery.result.time') as _time:
  252. with self.assertRaises(TimeoutError):
  253. res.get(timeout=1, interval=1)
  254. _time.sleep.assert_called_with(1)
  255. def test_ready(self):
  256. oks = (self.app.AsyncResult(self.task1['id']),
  257. self.app.AsyncResult(self.task2['id']),
  258. self.app.AsyncResult(self.task3['id']))
  259. self.assertTrue(all(result.ready() for result in oks))
  260. self.assertFalse(self.app.AsyncResult(self.task4['id']).ready())
  261. self.assertFalse(self.app.AsyncResult(uuid()).ready())
  262. class test_ResultSet(AppCase):
  263. def test_resultset_repr(self):
  264. self.assertTrue(repr(self.app.ResultSet(
  265. [self.app.AsyncResult(t) for t in ['1', '2', '3']])))
  266. def test_eq_other(self):
  267. self.assertFalse(self.app.ResultSet([1, 3, 3]) == 1)
  268. self.assertTrue(self.app.ResultSet([1]) == self.app.ResultSet([1]))
  269. def test_get(self):
  270. x = self.app.ResultSet([self.app.AsyncResult(t) for t in [1, 2, 3]])
  271. b = x.results[0].backend = Mock()
  272. b.supports_native_join = False
  273. x.join_native = Mock()
  274. x.join = Mock()
  275. x.get()
  276. self.assertTrue(x.join.called)
  277. b.supports_native_join = True
  278. x.get()
  279. self.assertTrue(x.join_native.called)
  280. def test_eq_ne(self):
  281. g1 = self.app.ResultSet(
  282. self.app.AsyncResult('id1'),
  283. self.app.AsyncResult('id2'),
  284. )
  285. g2 = self.app.ResultSet(
  286. self.app.AsyncResult('id1'),
  287. self.app.AsyncResult('id2'),
  288. )
  289. g3 = self.app.ResultSet(
  290. self.app.AsyncResult('id3'),
  291. self.app.AsyncResult('id1'),
  292. )
  293. self.assertEqual(g1, g2)
  294. self.assertNotEqual(g1, g3)
  295. self.assertNotEqual(g1, object())
  296. def test_takes_app_from_first_task(self):
  297. x = ResultSet([self.app.AsyncResult('id1')])
  298. self.assertIs(x.app, x.results[0].app)
  299. x.app = self.app
  300. self.assertIs(x.app, self.app)
  301. def test_get_empty(self):
  302. x = self.app.ResultSet([])
  303. self.assertIsNone(x.supports_native_join)
  304. x.join = Mock(name='join')
  305. x.get()
  306. self.assertTrue(x.join.called)
  307. def test_add(self):
  308. x = self.app.ResultSet([1])
  309. x.add(2)
  310. self.assertEqual(len(x), 2)
  311. x.add(2)
  312. self.assertEqual(len(x), 2)
  313. @contextmanager
  314. def dummy_copy(self):
  315. with patch('celery.result.copy') as copy:
  316. def passt(arg):
  317. return arg
  318. copy.side_effect = passt
  319. yield
  320. def test_iterate_respects_subpolling_interval(self):
  321. r1 = self.app.AsyncResult(uuid())
  322. r2 = self.app.AsyncResult(uuid())
  323. backend = r1.backend = r2.backend = Mock()
  324. backend.subpolling_interval = 10
  325. ready = r1.ready = r2.ready = Mock()
  326. def se(*args, **kwargs):
  327. ready.side_effect = KeyError()
  328. return False
  329. ready.return_value = False
  330. ready.side_effect = se
  331. x = self.app.ResultSet([r1, r2])
  332. with self.dummy_copy():
  333. with patch('celery.result.time') as _time:
  334. with self.assertPendingDeprecation():
  335. with self.assertRaises(KeyError):
  336. list(x.iterate())
  337. _time.sleep.assert_called_with(10)
  338. backend.subpolling_interval = 0
  339. with patch('celery.result.time') as _time:
  340. with self.assertPendingDeprecation():
  341. with self.assertRaises(KeyError):
  342. ready.return_value = False
  343. ready.side_effect = se
  344. list(x.iterate())
  345. self.assertFalse(_time.sleep.called)
  346. def test_times_out(self):
  347. r1 = self.app.AsyncResult(uuid)
  348. r1.ready = Mock()
  349. r1.ready.return_value = False
  350. x = self.app.ResultSet([r1])
  351. with self.dummy_copy():
  352. with patch('celery.result.time'):
  353. with self.assertPendingDeprecation():
  354. with self.assertRaises(TimeoutError):
  355. list(x.iterate(timeout=1))
  356. def test_add_discard(self):
  357. x = self.app.ResultSet([])
  358. x.add(self.app.AsyncResult('1'))
  359. self.assertIn(self.app.AsyncResult('1'), x.results)
  360. x.discard(self.app.AsyncResult('1'))
  361. x.discard(self.app.AsyncResult('1'))
  362. x.discard('1')
  363. self.assertNotIn(self.app.AsyncResult('1'), x.results)
  364. x.update([self.app.AsyncResult('2')])
  365. def test_clear(self):
  366. x = self.app.ResultSet([])
  367. r = x.results
  368. x.clear()
  369. self.assertIs(x.results, r)
  370. class MockAsyncResultFailure(AsyncResult):
  371. @property
  372. def result(self):
  373. return KeyError('baz')
  374. @property
  375. def state(self):
  376. return states.FAILURE
  377. def get(self, propagate=True, **kwargs):
  378. if propagate:
  379. raise self.result
  380. return self.result
  381. class MockAsyncResultSuccess(AsyncResult):
  382. forgotten = False
  383. def forget(self):
  384. self.forgotten = True
  385. @property
  386. def result(self):
  387. return 42
  388. @property
  389. def state(self):
  390. return states.SUCCESS
  391. def get(self, **kwargs):
  392. return self.result
  393. class SimpleBackend(object):
  394. ids = []
  395. def __init__(self, ids=[]):
  396. self.ids = ids
  397. def get_many(self, *args, **kwargs):
  398. return ((id, {'result': i, 'status': states.SUCCESS})
  399. for i, id in enumerate(self.ids))
  400. class test_GroupResult(AppCase):
  401. def setup(self):
  402. self.size = 10
  403. self.ts = self.app.GroupResult(
  404. uuid(), make_mock_group(self.app, self.size),
  405. )
  406. @depends_on_current_app
  407. def test_is_pickleable(self):
  408. ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  409. self.assertEqual(pickle.loads(pickle.dumps(ts)), ts)
  410. ts2 = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  411. self.assertEqual(pickle.loads(pickle.dumps(ts2)), ts2)
  412. @depends_on_current_app
  413. def test_reduce(self):
  414. ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  415. fun, args = ts.__reduce__()
  416. ts2 = fun(*args)
  417. self.assertEqual(ts2.id, ts.id)
  418. self.assertEqual(ts, ts2)
  419. def test_eq_ne(self):
  420. ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  421. ts2 = self.app.GroupResult(ts.id, ts.results)
  422. ts3 = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  423. ts4 = self.app.GroupResult(ts.id, [self.app.AsyncResult(uuid())])
  424. self.assertEqual(ts, ts2)
  425. self.assertNotEqual(ts, ts3)
  426. self.assertNotEqual(ts, ts4)
  427. self.assertNotEqual(ts, object())
  428. def test_len(self):
  429. self.assertEqual(len(self.ts), self.size)
  430. def test_eq_other(self):
  431. self.assertFalse(self.ts == 1)
  432. @depends_on_current_app
  433. def test_pickleable(self):
  434. self.assertTrue(pickle.loads(pickle.dumps(self.ts)))
  435. def test_iterate_raises(self):
  436. ar = MockAsyncResultFailure(uuid(), app=self.app)
  437. ts = self.app.GroupResult(uuid(), [ar])
  438. with self.assertPendingDeprecation():
  439. it = ts.iterate()
  440. with self.assertRaises(KeyError):
  441. next(it)
  442. def test_forget(self):
  443. subs = [MockAsyncResultSuccess(uuid(), app=self.app),
  444. MockAsyncResultSuccess(uuid(), app=self.app)]
  445. ts = self.app.GroupResult(uuid(), subs)
  446. ts.forget()
  447. for sub in subs:
  448. self.assertTrue(sub.forgotten)
  449. def test_getitem(self):
  450. subs = [MockAsyncResultSuccess(uuid(), app=self.app),
  451. MockAsyncResultSuccess(uuid(), app=self.app)]
  452. ts = self.app.GroupResult(uuid(), subs)
  453. self.assertIs(ts[0], subs[0])
  454. def test_save_restore(self):
  455. subs = [MockAsyncResultSuccess(uuid(), app=self.app),
  456. MockAsyncResultSuccess(uuid(), app=self.app)]
  457. ts = self.app.GroupResult(uuid(), subs)
  458. ts.save()
  459. with self.assertRaises(AttributeError):
  460. ts.save(backend=object())
  461. self.assertEqual(self.app.GroupResult.restore(ts.id).results,
  462. ts.results)
  463. ts.delete()
  464. self.assertIsNone(self.app.GroupResult.restore(ts.id))
  465. with self.assertRaises(AttributeError):
  466. self.app.GroupResult.restore(ts.id, backend=object())
  467. def test_join_native(self):
  468. backend = SimpleBackend()
  469. results = [self.app.AsyncResult(uuid(), backend=backend)
  470. for i in range(10)]
  471. ts = self.app.GroupResult(uuid(), results)
  472. ts.app.backend = backend
  473. backend.ids = [result.id for result in results]
  474. res = ts.join_native()
  475. self.assertEqual(res, list(range(10)))
  476. callback = Mock(name='callback')
  477. self.assertFalse(ts.join_native(callback=callback))
  478. callback.assert_has_calls([
  479. call(r.id, i) for i, r in enumerate(ts.results)
  480. ])
  481. def test_join_native_raises(self):
  482. ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  483. ts.iter_native = Mock()
  484. ts.iter_native.return_value = iter([
  485. (uuid(), {'status': states.FAILURE, 'result': KeyError()})
  486. ])
  487. with self.assertRaises(KeyError):
  488. ts.join_native(propagate=True)
  489. def test_failed_join_report(self):
  490. res = Mock()
  491. ts = self.app.GroupResult(uuid(), [res])
  492. res.state = states.FAILURE
  493. res.backend.is_cached.return_value = True
  494. self.assertIs(next(ts._failed_join_report()), res)
  495. res.backend.is_cached.return_value = False
  496. with self.assertRaises(StopIteration):
  497. next(ts._failed_join_report())
  498. def test_repr(self):
  499. self.assertTrue(repr(
  500. self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  501. ))
  502. def test_children_is_results(self):
  503. ts = self.app.GroupResult(uuid(), [self.app.AsyncResult(uuid())])
  504. self.assertIs(ts.children, ts.results)
  505. def test_iter_native(self):
  506. backend = SimpleBackend()
  507. results = [self.app.AsyncResult(uuid(), backend=backend)
  508. for i in range(10)]
  509. ts = self.app.GroupResult(uuid(), results)
  510. ts.app.backend = backend
  511. backend.ids = [result.id for result in results]
  512. self.assertEqual(len(list(ts.iter_native())), 10)
  513. def test_iterate_yields(self):
  514. ar = MockAsyncResultSuccess(uuid(), app=self.app)
  515. ar2 = MockAsyncResultSuccess(uuid(), app=self.app)
  516. ts = self.app.GroupResult(uuid(), [ar, ar2])
  517. with self.assertPendingDeprecation():
  518. it = ts.iterate()
  519. self.assertEqual(next(it), 42)
  520. self.assertEqual(next(it), 42)
  521. def test_iterate_eager(self):
  522. ar1 = EagerResult(uuid(), 42, states.SUCCESS)
  523. ar2 = EagerResult(uuid(), 42, states.SUCCESS)
  524. ts = self.app.GroupResult(uuid(), [ar1, ar2])
  525. with self.assertPendingDeprecation():
  526. it = ts.iterate()
  527. self.assertEqual(next(it), 42)
  528. self.assertEqual(next(it), 42)
  529. def test_join_timeout(self):
  530. ar = MockAsyncResultSuccess(uuid(), app=self.app)
  531. ar2 = MockAsyncResultSuccess(uuid(), app=self.app)
  532. ar3 = self.app.AsyncResult(uuid())
  533. ts = self.app.GroupResult(uuid(), [ar, ar2, ar3])
  534. with self.assertRaises(TimeoutError):
  535. ts.join(timeout=0.0000001)
  536. ar4 = self.app.AsyncResult(uuid())
  537. ar4.get = Mock()
  538. ts2 = self.app.GroupResult(uuid(), [ar4])
  539. self.assertTrue(ts2.join(timeout=0.1))
  540. callback = Mock(name='callback')
  541. self.assertFalse(ts2.join(timeout=0.1, callback=callback))
  542. callback.assert_called_with(ar4.id, ar4.get())
  543. def test_iter_native_when_empty_group(self):
  544. ts = self.app.GroupResult(uuid(), [])
  545. self.assertListEqual(list(ts.iter_native()), [])
  546. def test_iterate_simple(self):
  547. with self.assertPendingDeprecation():
  548. it = self.ts.iterate()
  549. results = sorted(list(it))
  550. self.assertListEqual(results, list(range(self.size)))
  551. def test___iter__(self):
  552. self.assertListEqual(list(iter(self.ts)), self.ts.results)
  553. def test_join(self):
  554. joined = self.ts.join()
  555. self.assertListEqual(joined, list(range(self.size)))
  556. def test_successful(self):
  557. self.assertTrue(self.ts.successful())
  558. def test_failed(self):
  559. self.assertFalse(self.ts.failed())
  560. def test_maybe_reraise(self):
  561. self.ts.results = [Mock(name='r1')]
  562. self.ts.maybe_reraise()
  563. self.ts.results[0].maybe_reraise.assert_called_with()
  564. def test_join__on_message(self):
  565. with self.assertRaises(ImproperlyConfigured):
  566. self.ts.join(on_message=Mock())
  567. def test_waiting(self):
  568. self.assertFalse(self.ts.waiting())
  569. def test_ready(self):
  570. self.assertTrue(self.ts.ready())
  571. def test_completed_count(self):
  572. self.assertEqual(self.ts.completed_count(), len(self.ts))
  573. class test_pending_AsyncResult(AppCase):
  574. def setup(self):
  575. self.task = self.app.AsyncResult(uuid())
  576. def test_result(self):
  577. self.assertIsNone(self.task.result)
  578. class test_failed_AsyncResult(test_GroupResult):
  579. def setup(self):
  580. self.app.conf.result_serializer = 'pickle'
  581. self.size = 11
  582. results = make_mock_group(self.app, 10)
  583. failed = mock_task('ts11', states.FAILURE, KeyError('Baz'))
  584. save_result(self.app, failed)
  585. failed_res = self.app.AsyncResult(failed['id'])
  586. self.ts = self.app.GroupResult(uuid(), results + [failed_res])
  587. def test_completed_count(self):
  588. self.assertEqual(self.ts.completed_count(), len(self.ts) - 1)
  589. def test_iterate_simple(self):
  590. with self.assertPendingDeprecation():
  591. it = self.ts.iterate()
  592. def consume():
  593. return list(it)
  594. with self.assertRaises(KeyError):
  595. consume()
  596. def test_join(self):
  597. with self.assertRaises(KeyError):
  598. self.ts.join()
  599. def test_successful(self):
  600. self.assertFalse(self.ts.successful())
  601. def test_failed(self):
  602. self.assertTrue(self.ts.failed())
  603. class test_pending_Group(AppCase):
  604. def setup(self):
  605. self.ts = self.app.GroupResult(
  606. uuid(), [self.app.AsyncResult(uuid()),
  607. self.app.AsyncResult(uuid())])
  608. def test_completed_count(self):
  609. self.assertEqual(self.ts.completed_count(), 0)
  610. def test_ready(self):
  611. self.assertFalse(self.ts.ready())
  612. def test_waiting(self):
  613. self.assertTrue(self.ts.waiting())
  614. def x_join(self):
  615. with self.assertRaises(TimeoutError):
  616. self.ts.join(timeout=0.001)
  617. def x_join_longer(self):
  618. with self.assertRaises(TimeoutError):
  619. self.ts.join(timeout=1)
  620. class test_EagerResult(AppCase):
  621. def setup(self):
  622. @self.app.task(shared=False)
  623. def raising(x, y):
  624. raise KeyError(x, y)
  625. self.raising = raising
  626. def test_wait_raises(self):
  627. res = self.raising.apply(args=[3, 3])
  628. with self.assertRaises(KeyError):
  629. res.wait()
  630. self.assertTrue(res.wait(propagate=False))
  631. def test_wait(self):
  632. res = EagerResult('x', 'x', states.RETRY)
  633. res.wait()
  634. self.assertEqual(res.state, states.RETRY)
  635. self.assertEqual(res.status, states.RETRY)
  636. def test_forget(self):
  637. res = EagerResult('x', 'x', states.RETRY)
  638. res.forget()
  639. def test_revoke(self):
  640. res = self.raising.apply(args=[3, 3])
  641. self.assertFalse(res.revoke())
  642. class test_tuples(AppCase):
  643. def test_AsyncResult(self):
  644. x = self.app.AsyncResult(uuid())
  645. self.assertEqual(x, result_from_tuple(x.as_tuple(), self.app))
  646. self.assertEqual(x, result_from_tuple(x, self.app))
  647. def test_with_parent(self):
  648. x = self.app.AsyncResult(uuid())
  649. x.parent = self.app.AsyncResult(uuid())
  650. y = result_from_tuple(x.as_tuple(), self.app)
  651. self.assertEqual(y, x)
  652. self.assertEqual(y.parent, x.parent)
  653. self.assertIsInstance(y.parent, AsyncResult)
  654. def test_compat(self):
  655. uid = uuid()
  656. x = result_from_tuple([uid, []], app=self.app)
  657. self.assertEqual(x.id, uid)
  658. def test_GroupResult(self):
  659. x = self.app.GroupResult(
  660. uuid(), [self.app.AsyncResult(uuid()) for _ in range(10)],
  661. )
  662. self.assertEqual(x, result_from_tuple(x.as_tuple(), self.app))
  663. self.assertEqual(x, result_from_tuple(x, self.app))