test_base.py 21 KB

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