test_base.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. import pytest
  2. from contextlib import contextmanager
  3. from case import ANY, Mock, call, patch
  4. from celery import states
  5. from celery import chord, group, uuid
  6. from celery.backends.base import (
  7. BaseBackend,
  8. KeyValueStoreBackend,
  9. DisabledBackend,
  10. _nulldict,
  11. )
  12. from celery.exceptions import ChordError, TimeoutError
  13. from celery.result import result_from_tuple
  14. from celery.utils import serialization
  15. from celery.utils.functional import pass1
  16. from celery.utils.serialization import subclass_exception
  17. from celery.utils.serialization import find_pickleable_exception as fnpe
  18. from celery.utils.serialization import UnpickleableExceptionWrapper
  19. from celery.utils.serialization import get_pickleable_exception as gpe
  20. class wrapobject:
  21. def __init__(self, *args, **kwargs):
  22. self.args = args
  23. Unpickleable = subclass_exception('Unpickleable', KeyError, 'foo.module')
  24. Impossible = subclass_exception('Impossible', object, 'foo.module')
  25. Lookalike = subclass_exception('Lookalike', wrapobject, 'foo.module')
  26. class test_nulldict:
  27. def test_nulldict(self):
  28. x = _nulldict()
  29. x['foo'] = 1
  30. x.update(foo=1, bar=2)
  31. x.setdefault('foo', 3)
  32. class test_serialization:
  33. def test_create_exception_cls(self):
  34. assert serialization.create_exception_cls('FooError', 'm')
  35. assert serialization.create_exception_cls('FooError', 'm', KeyError)
  36. class test_BaseBackend_interface:
  37. def setup(self):
  38. self.b = BaseBackend(self.app)
  39. def test__forget(self):
  40. with pytest.raises(NotImplementedError):
  41. self.b._forget('SOMExx-N0Nex1stant-IDxx-')
  42. def test_forget(self):
  43. with pytest.raises(NotImplementedError):
  44. self.b.forget('SOMExx-N0nex1stant-IDxx-')
  45. def test_on_chord_part_return(self):
  46. self.b.on_chord_part_return(None, None, None)
  47. def test_apply_chord(self, unlock='celery.chord_unlock'):
  48. self.app.tasks[unlock] = Mock()
  49. self.b.apply_chord(
  50. group(app=self.app), (), 'dakj221', None,
  51. result=[self.app.AsyncResult(x) for x in [1, 2, 3]],
  52. )
  53. assert self.app.tasks[unlock].apply_async.call_count
  54. class test_exception_pickle:
  55. def test_BaseException(self):
  56. assert fnpe(Exception()) is None
  57. def test_get_pickleable_exception(self):
  58. exc = Exception('foo')
  59. assert gpe(exc) == exc
  60. def test_unpickleable(self):
  61. assert isinstance(fnpe(Unpickleable()), KeyError)
  62. assert fnpe(Impossible()) is None
  63. class test_prepare_exception:
  64. def setup(self):
  65. self.b = BaseBackend(self.app)
  66. def test_unpickleable(self):
  67. self.b.serializer = 'pickle'
  68. x = self.b.prepare_exception(Unpickleable(1, 2, 'foo'))
  69. assert isinstance(x, KeyError)
  70. y = self.b.exception_to_python(x)
  71. assert isinstance(y, KeyError)
  72. def test_impossible(self):
  73. self.b.serializer = 'pickle'
  74. x = self.b.prepare_exception(Impossible())
  75. assert isinstance(x, UnpickleableExceptionWrapper)
  76. assert str(x)
  77. y = self.b.exception_to_python(x)
  78. assert y.__class__.__name__ == 'Impossible'
  79. assert y.__class__.__module__ == 'foo.module'
  80. def test_regular(self):
  81. self.b.serializer = 'pickle'
  82. x = self.b.prepare_exception(KeyError('baz'))
  83. assert isinstance(x, KeyError)
  84. y = self.b.exception_to_python(x)
  85. assert isinstance(y, KeyError)
  86. class KVBackend(KeyValueStoreBackend):
  87. mget_returns_dict = False
  88. def __init__(self, app, *args, **kwargs):
  89. self.db = {}
  90. super().__init__(app)
  91. def get(self, key):
  92. return self.db.get(key)
  93. def set(self, key, value):
  94. self.db[key] = value
  95. def mget(self, keys):
  96. if self.mget_returns_dict:
  97. return {key: self.get(key) for key in keys}
  98. else:
  99. return [self.get(k) for k in keys]
  100. def delete(self, key):
  101. self.db.pop(key, None)
  102. class DictBackend(BaseBackend):
  103. def __init__(self, *args, **kwargs):
  104. BaseBackend.__init__(self, *args, **kwargs)
  105. self._data = {'can-delete': {'result': 'foo'}}
  106. def _restore_group(self, group_id):
  107. if group_id == 'exists':
  108. return {'result': 'group'}
  109. def _get_task_meta_for(self, task_id):
  110. if task_id == 'task-exists':
  111. return {'result': 'task'}
  112. def _delete_group(self, group_id):
  113. self._data.pop(group_id, None)
  114. class test_BaseBackend_dict:
  115. def setup(self):
  116. self.b = DictBackend(app=self.app)
  117. def test_delete_group(self):
  118. self.b.delete_group('can-delete')
  119. assert 'can-delete' not in self.b._data
  120. def test_prepare_exception_json(self):
  121. x = DictBackend(self.app, serializer='json')
  122. e = x.prepare_exception(KeyError('foo'))
  123. assert 'exc_type' in e
  124. e = x.exception_to_python(e)
  125. assert e.__class__.__name__ == 'KeyError'
  126. assert str(e).strip('u') == "'foo'"
  127. def test_save_group(self):
  128. b = BaseBackend(self.app)
  129. b._save_group = Mock()
  130. b.save_group('foofoo', 'xxx')
  131. b._save_group.assert_called_with('foofoo', 'xxx')
  132. def test_add_to_chord_interface(self):
  133. b = BaseBackend(self.app)
  134. with pytest.raises(NotImplementedError):
  135. b.add_to_chord('group_id', 'sig')
  136. def test_forget_interface(self):
  137. b = BaseBackend(self.app)
  138. with pytest.raises(NotImplementedError):
  139. b.forget('foo')
  140. def test_restore_group(self):
  141. assert self.b.restore_group('missing') is None
  142. assert self.b.restore_group('missing') is None
  143. assert self.b.restore_group('exists') == 'group'
  144. assert self.b.restore_group('exists') == 'group'
  145. assert self.b.restore_group('exists', cache=False) == 'group'
  146. def test_reload_group_result(self):
  147. self.b._cache = {}
  148. self.b.reload_group_result('exists')
  149. self.b._cache['exists'] = {'result': 'group'}
  150. def test_reload_task_result(self):
  151. self.b._cache = {}
  152. self.b.reload_task_result('task-exists')
  153. self.b._cache['task-exists'] = {'result': 'task'}
  154. def test_fail_from_current_stack(self):
  155. self.b.mark_as_failure = Mock()
  156. try:
  157. raise KeyError('foo')
  158. except KeyError as exc:
  159. self.b.fail_from_current_stack('task_id')
  160. self.b.mark_as_failure.assert_called()
  161. args = self.b.mark_as_failure.call_args[0]
  162. assert args[0] == 'task_id'
  163. assert args[1] is exc
  164. assert args[2]
  165. def test_prepare_value_serializes_group_result(self):
  166. self.b.serializer = 'json'
  167. g = self.app.GroupResult('group_id', [self.app.AsyncResult('foo')])
  168. v = self.b.prepare_value(g)
  169. assert isinstance(v, (list, tuple))
  170. assert result_from_tuple(v, app=self.app) == g
  171. v2 = self.b.prepare_value(g[0])
  172. assert isinstance(v2, (list, tuple))
  173. assert result_from_tuple(v2, app=self.app) == g[0]
  174. self.b.serializer = 'pickle'
  175. assert isinstance(self.b.prepare_value(g), self.app.GroupResult)
  176. def test_is_cached(self):
  177. b = BaseBackend(app=self.app, max_cached_results=1)
  178. b._cache['foo'] = 1
  179. assert b.is_cached('foo')
  180. assert not b.is_cached('false')
  181. def test_mark_as_done__chord(self):
  182. b = BaseBackend(app=self.app)
  183. b._store_result = Mock()
  184. request = Mock(name='request')
  185. b.on_chord_part_return = Mock()
  186. b.mark_as_done('id', 10, request=request)
  187. b.on_chord_part_return.assert_called_with(request, states.SUCCESS, 10)
  188. def test_mark_as_failure__chord(self):
  189. b = BaseBackend(app=self.app)
  190. b._store_result = Mock()
  191. request = Mock(name='request')
  192. request.errbacks = []
  193. b.on_chord_part_return = Mock()
  194. exc = KeyError()
  195. b.mark_as_failure('id', exc, request=request)
  196. b.on_chord_part_return.assert_called_with(request, states.FAILURE, exc)
  197. def test_mark_as_revoked__chord(self):
  198. b = BaseBackend(app=self.app)
  199. b._store_result = Mock()
  200. request = Mock(name='request')
  201. request.errbacks = []
  202. b.on_chord_part_return = Mock()
  203. b.mark_as_revoked('id', 'revoked', request=request)
  204. b.on_chord_part_return.assert_called_with(request, states.REVOKED, ANY)
  205. def test_chord_error_from_stack_raises(self):
  206. b = BaseBackend(app=self.app)
  207. exc = KeyError()
  208. callback = Mock(name='callback')
  209. callback.options = {'link_error': []}
  210. task = self.app.tasks[callback.task] = Mock()
  211. b.fail_from_current_stack = Mock()
  212. group = self.patching('celery.group')
  213. group.side_effect = exc
  214. b.chord_error_from_stack(callback, exc=ValueError())
  215. task.backend.fail_from_current_stack.assert_called_with(
  216. callback.id, exc=exc)
  217. def test_exception_to_python_when_None(self):
  218. b = BaseBackend(app=self.app)
  219. assert b.exception_to_python(None) is None
  220. def test_wait_for__on_interval(self):
  221. self.patching('time.sleep')
  222. b = BaseBackend(app=self.app)
  223. b._get_task_meta_for = Mock()
  224. b._get_task_meta_for.return_value = {'status': states.PENDING}
  225. callback = Mock(name='callback')
  226. with pytest.raises(TimeoutError):
  227. b.wait_for(task_id='1', on_interval=callback, timeout=1)
  228. callback.assert_called_with()
  229. b._get_task_meta_for.return_value = {'status': states.SUCCESS}
  230. b.wait_for(task_id='1', timeout=None)
  231. def test_get_children(self):
  232. b = BaseBackend(app=self.app)
  233. b._get_task_meta_for = Mock()
  234. b._get_task_meta_for.return_value = {}
  235. assert b.get_children('id') is None
  236. b._get_task_meta_for.return_value = {'children': 3}
  237. assert b.get_children('id') == 3
  238. class test_KeyValueStoreBackend:
  239. def setup(self):
  240. self.b = KVBackend(app=self.app)
  241. def test_on_chord_part_return(self):
  242. assert not self.b.implements_incr
  243. self.b.on_chord_part_return(None, None, None)
  244. def test_get_store_delete_result(self):
  245. tid = uuid()
  246. self.b.mark_as_done(tid, 'Hello world')
  247. assert self.b.get_result(tid) == 'Hello world'
  248. assert self.b.get_state(tid) == states.SUCCESS
  249. self.b.forget(tid)
  250. assert self.b.get_state(tid) == states.PENDING
  251. def test_strip_prefix(self):
  252. x = self.b.get_key_for_task('x1b34')
  253. assert self.b._strip_prefix(x) == 'x1b34'
  254. assert self.b._strip_prefix('x1b34') == 'x1b34'
  255. def test_get_many(self):
  256. for is_dict in True, False:
  257. self.b.mget_returns_dict = is_dict
  258. ids = {uuid(): i for i in range(10)}
  259. for id, i in ids.items():
  260. self.b.mark_as_done(id, i)
  261. it = self.b.get_many(list(ids))
  262. for i, (got_id, got_state) in enumerate(it):
  263. assert got_state['result'] == ids[got_id]
  264. assert i == 9
  265. assert list(self.b.get_many(list(ids)))
  266. self.b._cache.clear()
  267. callback = Mock(name='callback')
  268. it = self.b.get_many(list(ids), on_message=callback)
  269. for i, (got_id, got_state) in enumerate(it):
  270. assert got_state['result'] == ids[got_id]
  271. assert i == 9
  272. assert list(self.b.get_many(list(ids)))
  273. callback.assert_has_calls([
  274. call(ANY) for id in ids
  275. ])
  276. def test_get_many_times_out(self):
  277. tasks = [uuid() for _ in range(4)]
  278. self.b._cache[tasks[1]] = {'status': 'PENDING'}
  279. with pytest.raises(self.b.TimeoutError):
  280. list(self.b.get_many(tasks, timeout=0.01, interval=0.01))
  281. def test_chord_part_return_no_gid(self):
  282. self.b.implements_incr = True
  283. task = Mock()
  284. state = 'SUCCESS'
  285. result = 10
  286. task.request.group = None
  287. self.b.get_key_for_chord = Mock()
  288. self.b.get_key_for_chord.side_effect = AssertionError(
  289. 'should not get here',
  290. )
  291. assert self.b.on_chord_part_return(
  292. task.request, state, result) is None
  293. @patch('celery.backends.base.GroupResult')
  294. @patch('celery.backends.base.maybe_signature')
  295. def test_chord_part_return_restore_raises(self, maybe_signature,
  296. GroupResult):
  297. self.b.implements_incr = True
  298. GroupResult.restore.side_effect = KeyError()
  299. self.b.chord_error_from_stack = Mock()
  300. callback = Mock(name='callback')
  301. request = Mock(name='request')
  302. request.group = 'gid'
  303. maybe_signature.return_value = callback
  304. self.b.on_chord_part_return(request, states.SUCCESS, 10)
  305. self.b.chord_error_from_stack.assert_called_with(
  306. callback, ANY,
  307. )
  308. @patch('celery.backends.base.GroupResult')
  309. @patch('celery.backends.base.maybe_signature')
  310. def test_chord_part_return_restore_empty(self, maybe_signature,
  311. GroupResult):
  312. self.b.implements_incr = True
  313. GroupResult.restore.return_value = None
  314. self.b.chord_error_from_stack = Mock()
  315. callback = Mock(name='callback')
  316. request = Mock(name='request')
  317. request.group = 'gid'
  318. maybe_signature.return_value = callback
  319. self.b.on_chord_part_return(request, states.SUCCESS, 10)
  320. self.b.chord_error_from_stack.assert_called_with(
  321. callback, ANY,
  322. )
  323. def test_filter_ready(self):
  324. self.b.decode_result = Mock()
  325. self.b.decode_result.side_effect = pass1
  326. assert len(list(self.b._filter_ready([
  327. (1, {'status': states.RETRY}),
  328. (2, {'status': states.FAILURE}),
  329. (3, {'status': states.SUCCESS}),
  330. ]))) == 2
  331. @contextmanager
  332. def _chord_part_context(self, b):
  333. @self.app.task(shared=False)
  334. def callback(result):
  335. pass
  336. b.implements_incr = True
  337. b.client = Mock()
  338. with patch('celery.backends.base.GroupResult') as GR:
  339. deps = GR.restore.return_value = Mock(name='DEPS')
  340. deps.__len__ = Mock()
  341. deps.__len__.return_value = 10
  342. b.incr = Mock()
  343. b.incr.return_value = 10
  344. b.expire = Mock()
  345. task = Mock()
  346. task.request.group = 'grid'
  347. cb = task.request.chord = callback.s()
  348. task.request.chord.freeze()
  349. callback.backend = b
  350. callback.backend.fail_from_current_stack = Mock()
  351. yield task, deps, cb
  352. def test_chord_part_return_propagate_set(self):
  353. with self._chord_part_context(self.b) as (task, deps, _):
  354. self.b.on_chord_part_return(task.request, 'SUCCESS', 10)
  355. self.b.expire.assert_not_called()
  356. deps.delete.assert_called_with()
  357. deps.join_native.assert_called_with(propagate=True, timeout=3.0)
  358. def test_chord_part_return_propagate_default(self):
  359. with self._chord_part_context(self.b) as (task, deps, _):
  360. self.b.on_chord_part_return(task.request, 'SUCCESS', 10)
  361. self.b.expire.assert_not_called()
  362. deps.delete.assert_called_with()
  363. deps.join_native.assert_called_with(propagate=True, timeout=3.0)
  364. def test_chord_part_return_join_raises_internal(self):
  365. with self._chord_part_context(self.b) as (task, deps, callback):
  366. deps._failed_join_report = lambda: iter([])
  367. deps.join_native.side_effect = KeyError('foo')
  368. self.b.on_chord_part_return(task.request, 'SUCCESS', 10)
  369. self.b.fail_from_current_stack.assert_called()
  370. args = self.b.fail_from_current_stack.call_args
  371. exc = args[1]['exc']
  372. assert isinstance(exc, ChordError)
  373. assert 'foo' in str(exc)
  374. def test_chord_part_return_join_raises_task(self):
  375. b = KVBackend(serializer='pickle', app=self.app)
  376. with self._chord_part_context(b) as (task, deps, callback):
  377. deps._failed_join_report = lambda: iter([
  378. self.app.AsyncResult('culprit'),
  379. ])
  380. deps.join_native.side_effect = KeyError('foo')
  381. b.on_chord_part_return(task.request, 'SUCCESS', 10)
  382. b.fail_from_current_stack.assert_called()
  383. args = b.fail_from_current_stack.call_args
  384. exc = args[1]['exc']
  385. assert isinstance(exc, ChordError)
  386. assert 'Dependency culprit raised' in str(exc)
  387. def test_restore_group_from_json(self):
  388. b = KVBackend(serializer='json', app=self.app)
  389. g = self.app.GroupResult(
  390. 'group_id',
  391. [self.app.AsyncResult('a'), self.app.AsyncResult('b')],
  392. )
  393. b._save_group(g.id, g)
  394. g2 = b._restore_group(g.id)['result']
  395. assert g2 == g
  396. def test_restore_group_from_pickle(self):
  397. b = KVBackend(serializer='pickle', app=self.app)
  398. g = self.app.GroupResult(
  399. 'group_id',
  400. [self.app.AsyncResult('a'), self.app.AsyncResult('b')],
  401. )
  402. b._save_group(g.id, g)
  403. g2 = b._restore_group(g.id)['result']
  404. assert g2 == g
  405. def test_chord_apply_fallback(self):
  406. self.b.implements_incr = False
  407. self.b.fallback_chord_unlock = Mock()
  408. self.b.apply_chord(
  409. group(app=self.app), (), 'group_id', 'body',
  410. result='result', foo=1,
  411. )
  412. self.b.fallback_chord_unlock.assert_called_with(
  413. 'group_id', 'body', result='result', foo=1,
  414. )
  415. def test_get_missing_meta(self):
  416. assert self.b.get_result('xxx-missing') is None
  417. assert self.b.get_state('xxx-missing') == states.PENDING
  418. def test_save_restore_delete_group(self):
  419. tid = uuid()
  420. tsr = self.app.GroupResult(
  421. tid, [self.app.AsyncResult(uuid()) for _ in range(10)],
  422. )
  423. self.b.save_group(tid, tsr)
  424. self.b.restore_group(tid)
  425. assert self.b.restore_group(tid) == tsr
  426. self.b.delete_group(tid)
  427. assert self.b.restore_group(tid) is None
  428. def test_restore_missing_group(self):
  429. assert self.b.restore_group('xxx-nonexistant') is None
  430. class test_KeyValueStoreBackend_interface:
  431. def test_get(self):
  432. with pytest.raises(NotImplementedError):
  433. KeyValueStoreBackend(self.app).get('a')
  434. def test_set(self):
  435. with pytest.raises(NotImplementedError):
  436. KeyValueStoreBackend(self.app).set('a', 1)
  437. def test_incr(self):
  438. with pytest.raises(NotImplementedError):
  439. KeyValueStoreBackend(self.app).incr('a')
  440. def test_cleanup(self):
  441. assert not KeyValueStoreBackend(self.app).cleanup()
  442. def test_delete(self):
  443. with pytest.raises(NotImplementedError):
  444. KeyValueStoreBackend(self.app).delete('a')
  445. def test_mget(self):
  446. with pytest.raises(NotImplementedError):
  447. KeyValueStoreBackend(self.app).mget(['a'])
  448. def test_forget(self):
  449. with pytest.raises(NotImplementedError):
  450. KeyValueStoreBackend(self.app).forget('a')
  451. class test_DisabledBackend:
  452. def test_store_result(self):
  453. DisabledBackend(self.app).store_result()
  454. def test_is_disabled(self):
  455. with pytest.raises(NotImplementedError):
  456. DisabledBackend(self.app).get_state('foo')
  457. def test_as_uri(self):
  458. assert DisabledBackend(self.app).as_uri() == 'disabled://'
  459. @pytest.mark.celery(result_backend='disabled')
  460. def test_chord_raises_error(self):
  461. with pytest.raises(NotImplementedError):
  462. chord(self.add.s(i, i) for i in range(10))(self.add.s([2]))
  463. @pytest.mark.celery(result_backend='disabled')
  464. def test_chain_with_chord_raises_error(self):
  465. with pytest.raises(NotImplementedError):
  466. (self.add.s(2, 2) |
  467. group(self.add.s(2, 2),
  468. self.add.s(5, 6)) | self.add.s()).delay()
  469. class test_as_uri:
  470. def setup(self):
  471. self.b = BaseBackend(
  472. app=self.app,
  473. url='sch://uuuu:pwpw@hostname.dom'
  474. )
  475. def test_as_uri_include_password(self):
  476. assert self.b.as_uri(True) == self.b.url
  477. def test_as_uri_exclude_password(self):
  478. assert self.b.as_uri() == 'sch://uuuu:**@hostname.dom/'