test_result.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. from __future__ import absolute_import
  2. from __future__ import with_statement
  3. from pickle import loads, dumps
  4. from mock import Mock
  5. from celery import states
  6. from celery.app import app_or_default
  7. from celery.exceptions import IncompleteStream
  8. from celery.utils import uuid
  9. from celery.utils.serialization import pickle
  10. from celery.result import (
  11. AsyncResult,
  12. EagerResult,
  13. GroupResult,
  14. TaskSetResult,
  15. ResultSet,
  16. from_serializable,
  17. )
  18. from celery.exceptions import TimeoutError
  19. from celery.task import task
  20. from celery.task.base import Task
  21. from celery.tests.utils import AppCase
  22. from celery.tests.utils import skip_if_quick
  23. @task()
  24. def mytask():
  25. pass
  26. def mock_task(name, state, result):
  27. return dict(id=uuid(), name=name, state=state, result=result)
  28. def save_result(task):
  29. app = app_or_default()
  30. traceback = '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(task['id'], task['result'],
  35. traceback=traceback)
  36. else:
  37. app.backend.mark_as_failure(task['id'], task['result'],
  38. traceback=traceback)
  39. def make_mock_group(size=10):
  40. tasks = [mock_task('ts%d' % i, states.SUCCESS, i) for i in xrange(size)]
  41. [save_result(task) for task in tasks]
  42. return [AsyncResult(task['id']) for task in tasks]
  43. class test_AsyncResult(AppCase):
  44. def setup(self):
  45. self.task1 = mock_task('task1', states.SUCCESS, 'the')
  46. self.task2 = mock_task('task2', states.SUCCESS, 'quick')
  47. self.task3 = mock_task('task3', states.FAILURE, KeyError('brown'))
  48. self.task4 = mock_task('task3', states.RETRY, KeyError('red'))
  49. for task in (self.task1, self.task2, self.task3, self.task4):
  50. save_result(task)
  51. def test_compat_properties(self):
  52. x = AsyncResult('1')
  53. self.assertEqual(x.task_id, x.id)
  54. x.task_id = '2'
  55. self.assertEqual(x.id, '2')
  56. def test_children(self):
  57. x = AsyncResult('1')
  58. children = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
  59. x.backend = Mock()
  60. x.backend.get_children.return_value = children
  61. x.backend.READY_STATES = states.READY_STATES
  62. self.assertTrue(x.children)
  63. self.assertEqual(len(x.children), 3)
  64. def test_get_children(self):
  65. tid = uuid()
  66. x = AsyncResult(tid)
  67. child = [AsyncResult(uuid()).serializable() for i in xrange(10)]
  68. x.backend._cache[tid] = {'children': child}
  69. self.assertTrue(x.children)
  70. self.assertEqual(len(x.children), 10)
  71. x.backend._cache[tid] = {'result': None}
  72. self.assertIsNone(x.children)
  73. def test_build_graph_get_leaf_collect(self):
  74. x = AsyncResult('1')
  75. x.backend._cache['1'] = {'status': states.SUCCESS, 'result': None}
  76. c = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
  77. x.iterdeps = Mock()
  78. x.iterdeps.return_value = (
  79. (None, x),
  80. (x, c[0]),
  81. (c[0], c[1]),
  82. (c[1], c[2])
  83. )
  84. x.backend.READY_STATES = states.READY_STATES
  85. self.assertTrue(x.graph)
  86. self.assertIs(x.get_leaf(), 2)
  87. it = x.collect()
  88. self.assertListEqual(list(it), [
  89. (x, None),
  90. (c[0], 0),
  91. (c[1], 1),
  92. (c[2], 2),
  93. ])
  94. def test_iterdeps(self):
  95. x = AsyncResult('1')
  96. x.backend._cache['1'] = {'status': states.SUCCESS, 'result': None}
  97. c = [EagerResult(str(i), i, states.SUCCESS) for i in range(3)]
  98. for child in c:
  99. child.backend = Mock()
  100. child.backend.get_children.return_value = []
  101. x.backend.get_children = Mock()
  102. x.backend.get_children.return_value = c
  103. it = x.iterdeps()
  104. self.assertListEqual(list(it), [
  105. (None, x),
  106. (x, c[0]),
  107. (x, c[1]),
  108. (x, c[2]),
  109. ])
  110. x.backend._cache.pop('1')
  111. x.ready = Mock()
  112. x.ready.return_value = False
  113. with self.assertRaises(IncompleteStream):
  114. list(x.iterdeps())
  115. list(x.iterdeps(intermediate=True))
  116. def test_eq_not_implemented(self):
  117. self.assertFalse(AsyncResult('1') == object())
  118. def test_reduce(self):
  119. a1 = AsyncResult('uuid', task_name=mytask.name)
  120. restored = pickle.loads(pickle.dumps(a1))
  121. self.assertEqual(restored.id, 'uuid')
  122. self.assertEqual(restored.task_name, mytask.name)
  123. a2 = AsyncResult('uuid')
  124. self.assertEqual(pickle.loads(pickle.dumps(a2)).id, 'uuid')
  125. def test_successful(self):
  126. ok_res = AsyncResult(self.task1['id'])
  127. nok_res = AsyncResult(self.task3['id'])
  128. nok_res2 = AsyncResult(self.task4['id'])
  129. self.assertTrue(ok_res.successful())
  130. self.assertFalse(nok_res.successful())
  131. self.assertFalse(nok_res2.successful())
  132. pending_res = AsyncResult(uuid())
  133. self.assertFalse(pending_res.successful())
  134. def test_str(self):
  135. ok_res = AsyncResult(self.task1['id'])
  136. ok2_res = AsyncResult(self.task2['id'])
  137. nok_res = AsyncResult(self.task3['id'])
  138. self.assertEqual(str(ok_res), self.task1['id'])
  139. self.assertEqual(str(ok2_res), self.task2['id'])
  140. self.assertEqual(str(nok_res), self.task3['id'])
  141. pending_id = uuid()
  142. pending_res = AsyncResult(pending_id)
  143. self.assertEqual(str(pending_res), pending_id)
  144. def test_repr(self):
  145. ok_res = AsyncResult(self.task1['id'])
  146. ok2_res = AsyncResult(self.task2['id'])
  147. nok_res = AsyncResult(self.task3['id'])
  148. self.assertEqual(repr(ok_res), '<AsyncResult: %s>' % (
  149. self.task1['id']))
  150. self.assertEqual(repr(ok2_res), '<AsyncResult: %s>' % (
  151. self.task2['id']))
  152. self.assertEqual(repr(nok_res), '<AsyncResult: %s>' % (
  153. self.task3['id']))
  154. pending_id = uuid()
  155. pending_res = AsyncResult(pending_id)
  156. self.assertEqual(repr(pending_res), '<AsyncResult: %s>' % (
  157. pending_id))
  158. def test_hash(self):
  159. self.assertEqual(hash(AsyncResult('x0w991')),
  160. hash(AsyncResult('x0w991')))
  161. self.assertNotEqual(hash(AsyncResult('x0w991')),
  162. hash(AsyncResult('x1w991')))
  163. def test_get_traceback(self):
  164. ok_res = AsyncResult(self.task1['id'])
  165. nok_res = AsyncResult(self.task3['id'])
  166. nok_res2 = AsyncResult(self.task4['id'])
  167. self.assertFalse(ok_res.traceback)
  168. self.assertTrue(nok_res.traceback)
  169. self.assertTrue(nok_res2.traceback)
  170. pending_res = AsyncResult(uuid())
  171. self.assertFalse(pending_res.traceback)
  172. def test_get(self):
  173. ok_res = AsyncResult(self.task1['id'])
  174. ok2_res = AsyncResult(self.task2['id'])
  175. nok_res = AsyncResult(self.task3['id'])
  176. nok2_res = AsyncResult(self.task4['id'])
  177. self.assertEqual(ok_res.get(), 'the')
  178. self.assertEqual(ok2_res.get(), 'quick')
  179. with self.assertRaises(KeyError):
  180. nok_res.get()
  181. self.assertTrue(nok_res.get(propagate=False))
  182. self.assertIsInstance(nok2_res.result, KeyError)
  183. self.assertEqual(ok_res.info, 'the')
  184. def test_get_timeout(self):
  185. res = AsyncResult(self.task4['id']) # has RETRY state
  186. with self.assertRaises(TimeoutError):
  187. res.get(timeout=0.1)
  188. pending_res = AsyncResult(uuid())
  189. with self.assertRaises(TimeoutError):
  190. pending_res.get(timeout=0.1)
  191. @skip_if_quick
  192. def test_get_timeout_longer(self):
  193. res = AsyncResult(self.task4['id']) # has RETRY state
  194. with self.assertRaises(TimeoutError):
  195. res.get(timeout=1)
  196. def test_ready(self):
  197. oks = (AsyncResult(self.task1['id']),
  198. AsyncResult(self.task2['id']),
  199. AsyncResult(self.task3['id']))
  200. self.assertTrue(all(result.ready() for result in oks))
  201. self.assertFalse(AsyncResult(self.task4['id']).ready())
  202. self.assertFalse(AsyncResult(uuid()).ready())
  203. class test_ResultSet(AppCase):
  204. def test_resultset_repr(self):
  205. self.assertTrue(repr(ResultSet(map(AsyncResult, [1, 2, 3]))))
  206. def test_eq_other(self):
  207. self.assertFalse(ResultSet([1, 3, 3]) == 1)
  208. self.assertTrue(ResultSet([1]) == ResultSet([1]))
  209. def test_get(self):
  210. x = ResultSet(map(AsyncResult, [1, 2, 3]))
  211. b = x.results[0].backend = Mock()
  212. b.supports_native_join = False
  213. x.join_native = Mock()
  214. x.join = Mock()
  215. x.get()
  216. self.assertTrue(x.join.called)
  217. b.supports_native_join = True
  218. x.get()
  219. self.assertTrue(x.join_native.called)
  220. def test_add(self):
  221. x = ResultSet([1])
  222. x.add(2)
  223. self.assertEqual(len(x), 2)
  224. x.add(2)
  225. self.assertEqual(len(x), 2)
  226. def test_add_discard(self):
  227. x = ResultSet([])
  228. x.add(AsyncResult('1'))
  229. self.assertIn(AsyncResult('1'), x.results)
  230. x.discard(AsyncResult('1'))
  231. x.discard(AsyncResult('1'))
  232. x.discard('1')
  233. self.assertNotIn(AsyncResult('1'), x.results)
  234. x.update([AsyncResult('2')])
  235. def test_clear(self):
  236. x = ResultSet([])
  237. r = x.results
  238. x.clear()
  239. self.assertIs(x.results, r)
  240. class MockAsyncResultFailure(AsyncResult):
  241. @property
  242. def result(self):
  243. return KeyError('baz')
  244. @property
  245. def state(self):
  246. return states.FAILURE
  247. def get(self, propagate=True, **kwargs):
  248. if propagate:
  249. raise self.result
  250. return self.result
  251. class MockAsyncResultSuccess(AsyncResult):
  252. forgotten = False
  253. def forget(self):
  254. self.forgotten = True
  255. @property
  256. def result(self):
  257. return 42
  258. @property
  259. def state(self):
  260. return states.SUCCESS
  261. def get(self, **kwargs):
  262. return self.result
  263. class SimpleBackend(object):
  264. ids = []
  265. def __init__(self, ids=[]):
  266. self.ids = ids
  267. def get_many(self, *args, **kwargs):
  268. return ((id, {'result': i}) for i, id in enumerate(self.ids))
  269. class test_TaskSetResult(AppCase):
  270. def setup(self):
  271. self.size = 10
  272. self.ts = TaskSetResult(uuid(), make_mock_group(self.size))
  273. def test_total(self):
  274. self.assertEqual(self.ts.total, self.size)
  275. def test_compat_properties(self):
  276. self.assertEqual(self.ts.taskset_id, self.ts.id)
  277. self.ts.taskset_id = 'foo'
  278. self.assertEqual(self.ts.taskset_id, 'foo')
  279. def test_compat_subtasks_kwarg(self):
  280. x = TaskSetResult(uuid(), subtasks=[1, 2, 3])
  281. self.assertEqual(x.results, [1, 2, 3])
  282. def test_itersubtasks(self):
  283. it = self.ts.itersubtasks()
  284. for i, t in enumerate(it):
  285. self.assertEqual(t.get(), i)
  286. class test_GroupResult(AppCase):
  287. def setup(self):
  288. self.size = 10
  289. self.ts = GroupResult(uuid(), make_mock_group(self.size))
  290. def test_len(self):
  291. self.assertEqual(len(self.ts), self.size)
  292. def test_eq_other(self):
  293. self.assertFalse(self.ts == 1)
  294. def test_reduce(self):
  295. self.assertTrue(loads(dumps(self.ts)))
  296. def test_iterate_raises(self):
  297. ar = MockAsyncResultFailure(uuid())
  298. ts = GroupResult(uuid(), [ar])
  299. it = iter(ts)
  300. with self.assertRaises(KeyError):
  301. it.next()
  302. def test_forget(self):
  303. subs = [MockAsyncResultSuccess(uuid()),
  304. MockAsyncResultSuccess(uuid())]
  305. ts = GroupResult(uuid(), subs)
  306. ts.forget()
  307. for sub in subs:
  308. self.assertTrue(sub.forgotten)
  309. def test_getitem(self):
  310. subs = [MockAsyncResultSuccess(uuid()),
  311. MockAsyncResultSuccess(uuid())]
  312. ts = GroupResult(uuid(), subs)
  313. self.assertIs(ts[0], subs[0])
  314. def test_save_restore(self):
  315. subs = [MockAsyncResultSuccess(uuid()),
  316. MockAsyncResultSuccess(uuid())]
  317. ts = GroupResult(uuid(), subs)
  318. ts.save()
  319. with self.assertRaises(AttributeError):
  320. ts.save(backend=object())
  321. self.assertEqual(GroupResult.restore(ts.id).subtasks,
  322. ts.subtasks)
  323. ts.delete()
  324. self.assertIsNone(GroupResult.restore(ts.id))
  325. with self.assertRaises(AttributeError):
  326. GroupResult.restore(ts.id, backend=object())
  327. def test_join_native(self):
  328. backend = SimpleBackend()
  329. subtasks = [AsyncResult(uuid(), backend=backend)
  330. for i in range(10)]
  331. ts = GroupResult(uuid(), subtasks)
  332. backend.ids = [subtask.id for subtask in subtasks]
  333. res = ts.join_native()
  334. self.assertEqual(res, range(10))
  335. def test_iter_native(self):
  336. backend = SimpleBackend()
  337. subtasks = [AsyncResult(uuid(), backend=backend)
  338. for i in range(10)]
  339. ts = GroupResult(uuid(), subtasks)
  340. backend.ids = [subtask.id for subtask in subtasks]
  341. self.assertEqual(len(list(ts.iter_native())), 10)
  342. def test_iterate_yields(self):
  343. ar = MockAsyncResultSuccess(uuid())
  344. ar2 = MockAsyncResultSuccess(uuid())
  345. ts = GroupResult(uuid(), [ar, ar2])
  346. it = iter(ts)
  347. self.assertEqual(it.next(), 42)
  348. self.assertEqual(it.next(), 42)
  349. def test_iterate_eager(self):
  350. ar1 = EagerResult(uuid(), 42, states.SUCCESS)
  351. ar2 = EagerResult(uuid(), 42, states.SUCCESS)
  352. ts = GroupResult(uuid(), [ar1, ar2])
  353. it = iter(ts)
  354. self.assertEqual(it.next(), 42)
  355. self.assertEqual(it.next(), 42)
  356. def test_join_timeout(self):
  357. ar = MockAsyncResultSuccess(uuid())
  358. ar2 = MockAsyncResultSuccess(uuid())
  359. ar3 = AsyncResult(uuid())
  360. ts = GroupResult(uuid(), [ar, ar2, ar3])
  361. with self.assertRaises(TimeoutError):
  362. ts.join(timeout=0.0000001)
  363. def test___iter__(self):
  364. it = iter(self.ts)
  365. results = sorted(list(it))
  366. self.assertListEqual(results, list(xrange(self.size)))
  367. def test_join(self):
  368. joined = self.ts.join()
  369. self.assertListEqual(joined, list(xrange(self.size)))
  370. def test_successful(self):
  371. self.assertTrue(self.ts.successful())
  372. def test_failed(self):
  373. self.assertFalse(self.ts.failed())
  374. def test_waiting(self):
  375. self.assertFalse(self.ts.waiting())
  376. def test_ready(self):
  377. self.assertTrue(self.ts.ready())
  378. def test_completed_count(self):
  379. self.assertEqual(self.ts.completed_count(), len(self.ts))
  380. class test_pending_AsyncResult(AppCase):
  381. def setup(self):
  382. self.task = AsyncResult(uuid())
  383. def test_result(self):
  384. self.assertIsNone(self.task.result)
  385. class test_failed_AsyncResult(test_GroupResult):
  386. def setup(self):
  387. self.size = 11
  388. subtasks = make_mock_group(10)
  389. failed = mock_task('ts11', states.FAILURE, KeyError('Baz'))
  390. save_result(failed)
  391. failed_res = AsyncResult(failed['id'])
  392. self.ts = GroupResult(uuid(), subtasks + [failed_res])
  393. def test_completed_count(self):
  394. self.assertEqual(self.ts.completed_count(), len(self.ts) - 1)
  395. def test___iter__(self):
  396. it = iter(self.ts)
  397. def consume():
  398. return list(it)
  399. with self.assertRaises(KeyError):
  400. consume()
  401. def test_join(self):
  402. with self.assertRaises(KeyError):
  403. self.ts.join()
  404. def test_successful(self):
  405. self.assertFalse(self.ts.successful())
  406. def test_failed(self):
  407. self.assertTrue(self.ts.failed())
  408. class test_pending_Group(AppCase):
  409. def setup(self):
  410. self.ts = GroupResult(uuid(), [AsyncResult(uuid()),
  411. AsyncResult(uuid())])
  412. def test_completed_count(self):
  413. self.assertEqual(self.ts.completed_count(), 0)
  414. def test_ready(self):
  415. self.assertFalse(self.ts.ready())
  416. def test_waiting(self):
  417. self.assertTrue(self.ts.waiting())
  418. def x_join(self):
  419. with self.assertRaises(TimeoutError):
  420. self.ts.join(timeout=0.001)
  421. @skip_if_quick
  422. def x_join_longer(self):
  423. with self.assertRaises(TimeoutError):
  424. self.ts.join(timeout=1)
  425. class RaisingTask(Task):
  426. def run(self, x, y):
  427. raise KeyError('xy')
  428. class test_EagerResult(AppCase):
  429. def test_wait_raises(self):
  430. res = RaisingTask.apply(args=[3, 3])
  431. with self.assertRaises(KeyError):
  432. res.wait()
  433. self.assertTrue(res.wait(propagate=False))
  434. def test_wait(self):
  435. res = EagerResult('x', 'x', states.RETRY)
  436. res.wait()
  437. self.assertEqual(res.state, states.RETRY)
  438. self.assertEqual(res.status, states.RETRY)
  439. def test_forget(self):
  440. res = EagerResult('x', 'x', states.RETRY)
  441. res.forget()
  442. def test_revoke(self):
  443. res = RaisingTask.apply(args=[3, 3])
  444. self.assertFalse(res.revoke())
  445. class test_serializable(AppCase):
  446. def test_AsyncResult(self):
  447. x = AsyncResult(uuid())
  448. self.assertEqual(x, from_serializable(x.serializable()))
  449. self.assertEqual(x, from_serializable(x))
  450. def test_GroupResult(self):
  451. x = GroupResult(uuid(), [AsyncResult(uuid()) for _ in range(10)])
  452. self.assertEqual(x, from_serializable(x.serializable()))
  453. self.assertEqual(x, from_serializable(x))