test_result.py 32 KB

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