test_tasks.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. from __future__ import absolute_import, unicode_literals
  2. import pytest
  3. import socket
  4. from datetime import datetime, timedelta
  5. from case import ContextMock, MagicMock, Mock, patch
  6. from kombu import Queue
  7. from celery import Task, group, uuid
  8. from celery.app.task import _reprtask
  9. from celery.exceptions import Ignore, Retry
  10. from celery.five import items, range, string_t
  11. from celery.result import EagerResult
  12. from celery.utils.time import parse_iso8601
  13. def return_True(*args, **kwargs):
  14. # Task run functions can't be closures/lambdas, as they're pickled.
  15. return True
  16. class MockApplyTask(Task):
  17. abstract = True
  18. applied = 0
  19. def run(self, x, y):
  20. return x * y
  21. def apply_async(self, *args, **kwargs):
  22. self.applied += 1
  23. class TasksCase:
  24. def setup(self):
  25. self.app.conf.task_protocol = 1 # XXX Still using proto1
  26. self.mytask = self.app.task(shared=False)(return_True)
  27. @self.app.task(bind=True, count=0, shared=False)
  28. def increment_counter(self, increment_by=1):
  29. self.count += increment_by or 1
  30. return self.count
  31. self.increment_counter = increment_counter
  32. @self.app.task(shared=False)
  33. def raising():
  34. raise KeyError('foo')
  35. self.raising = raising
  36. @self.app.task(bind=True, max_retries=3, iterations=0, shared=False)
  37. def retry_task(self, arg1, arg2, kwarg=1, max_retries=None, care=True):
  38. self.iterations += 1
  39. rmax = self.max_retries if max_retries is None else max_retries
  40. assert repr(self.request)
  41. retries = self.request.retries
  42. if care and retries >= rmax:
  43. return arg1
  44. else:
  45. raise self.retry(countdown=0, max_retries=rmax)
  46. self.retry_task = retry_task
  47. @self.app.task(bind=True, max_retries=3, iterations=0, shared=False)
  48. def retry_task_noargs(self, **kwargs):
  49. self.iterations += 1
  50. if self.request.retries >= 3:
  51. return 42
  52. else:
  53. raise self.retry(countdown=0)
  54. self.retry_task_noargs = retry_task_noargs
  55. @self.app.task(bind=True, max_retries=3, iterations=0,
  56. base=MockApplyTask, shared=False)
  57. def retry_task_mockapply(self, arg1, arg2, kwarg=1):
  58. self.iterations += 1
  59. retries = self.request.retries
  60. if retries >= 3:
  61. return arg1
  62. raise self.retry(countdown=0)
  63. self.retry_task_mockapply = retry_task_mockapply
  64. @self.app.task(bind=True, max_retries=3, iterations=0, shared=False)
  65. def retry_task_customexc(self, arg1, arg2, kwarg=1, **kwargs):
  66. self.iterations += 1
  67. retries = self.request.retries
  68. if retries >= 3:
  69. return arg1 + kwarg
  70. else:
  71. try:
  72. raise MyCustomException('Elaine Marie Benes')
  73. except MyCustomException as exc:
  74. kwargs.update(kwarg=kwarg)
  75. raise self.retry(countdown=0, exc=exc)
  76. self.retry_task_customexc = retry_task_customexc
  77. @self.app.task(bind=True, autoretry_for=(ZeroDivisionError,),
  78. shared=False)
  79. def autoretry_task_no_kwargs(self, a, b):
  80. self.iterations += 1
  81. return a / b
  82. self.autoretry_task_no_kwargs = autoretry_task_no_kwargs
  83. @self.app.task(bind=True, autoretry_for=(ZeroDivisionError,),
  84. retry_kwargs={'max_retries': 5}, shared=False)
  85. def autoretry_task(self, a, b):
  86. self.iterations += 1
  87. return a / b
  88. self.autoretry_task = autoretry_task
  89. @self.app.task(bind=True)
  90. def task_check_request_context(self):
  91. assert self.request.hostname == socket.gethostname()
  92. self.task_check_request_context = task_check_request_context
  93. # memove all messages from memory-transport
  94. from kombu.transport.memory import Channel
  95. Channel.queues.clear()
  96. class MyCustomException(Exception):
  97. """Random custom exception."""
  98. class test_task_retries(TasksCase):
  99. def test_retry(self):
  100. self.retry_task.max_retries = 3
  101. self.retry_task.iterations = 0
  102. self.retry_task.apply([0xFF, 0xFFFF])
  103. assert self.retry_task.iterations == 4
  104. self.retry_task.max_retries = 3
  105. self.retry_task.iterations = 0
  106. self.retry_task.apply([0xFF, 0xFFFF], {'max_retries': 10})
  107. assert self.retry_task.iterations == 11
  108. def test_retry_no_args(self):
  109. self.retry_task_noargs.max_retries = 3
  110. self.retry_task_noargs.iterations = 0
  111. self.retry_task_noargs.apply(propagate=True).get()
  112. assert self.retry_task_noargs.iterations == 4
  113. def test_signature_from_request__passes_headers(self):
  114. self.retry_task.push_request()
  115. self.retry_task.request.headers = {'custom': 10.1}
  116. sig = self.retry_task.signature_from_request()
  117. assert sig.options['headers']['custom'] == 10.1
  118. def test_signature_from_request__delivery_info(self):
  119. self.retry_task.push_request()
  120. self.retry_task.request.delivery_info = {
  121. 'exchange': 'testex',
  122. 'routing_key': 'testrk',
  123. }
  124. sig = self.retry_task.signature_from_request()
  125. assert sig.options['exchange'] == 'testex'
  126. assert sig.options['routing_key'] == 'testrk'
  127. def test_retry_kwargs_can_be_empty(self):
  128. self.retry_task_mockapply.push_request()
  129. try:
  130. with pytest.raises(Retry):
  131. import sys
  132. try:
  133. sys.exc_clear()
  134. except AttributeError:
  135. pass
  136. self.retry_task_mockapply.retry(args=[4, 4], kwargs=None)
  137. finally:
  138. self.retry_task_mockapply.pop_request()
  139. def test_retry_not_eager(self):
  140. self.retry_task_mockapply.push_request()
  141. try:
  142. self.retry_task_mockapply.request.called_directly = False
  143. exc = Exception('baz')
  144. try:
  145. self.retry_task_mockapply.retry(
  146. args=[4, 4], kwargs={'task_retries': 0},
  147. exc=exc, throw=False,
  148. )
  149. assert self.retry_task_mockapply.applied
  150. finally:
  151. self.retry_task_mockapply.applied = 0
  152. try:
  153. with pytest.raises(Retry):
  154. self.retry_task_mockapply.retry(
  155. args=[4, 4], kwargs={'task_retries': 0},
  156. exc=exc, throw=True)
  157. assert self.retry_task_mockapply.applied
  158. finally:
  159. self.retry_task_mockapply.applied = 0
  160. finally:
  161. self.retry_task_mockapply.pop_request()
  162. def test_retry_with_kwargs(self):
  163. self.retry_task_customexc.max_retries = 3
  164. self.retry_task_customexc.iterations = 0
  165. self.retry_task_customexc.apply([0xFF, 0xFFFF], {'kwarg': 0xF})
  166. assert self.retry_task_customexc.iterations == 4
  167. def test_retry_with_custom_exception(self):
  168. self.retry_task_customexc.max_retries = 2
  169. self.retry_task_customexc.iterations = 0
  170. result = self.retry_task_customexc.apply(
  171. [0xFF, 0xFFFF], {'kwarg': 0xF},
  172. )
  173. with pytest.raises(MyCustomException):
  174. result.get()
  175. assert self.retry_task_customexc.iterations == 3
  176. def test_max_retries_exceeded(self):
  177. self.retry_task.max_retries = 2
  178. self.retry_task.iterations = 0
  179. result = self.retry_task.apply([0xFF, 0xFFFF], {'care': False})
  180. with pytest.raises(self.retry_task.MaxRetriesExceededError):
  181. result.get()
  182. assert self.retry_task.iterations == 3
  183. self.retry_task.max_retries = 1
  184. self.retry_task.iterations = 0
  185. result = self.retry_task.apply([0xFF, 0xFFFF], {'care': False})
  186. with pytest.raises(self.retry_task.MaxRetriesExceededError):
  187. result.get()
  188. assert self.retry_task.iterations == 2
  189. def test_autoretry_no_kwargs(self):
  190. self.autoretry_task_no_kwargs.max_retries = 3
  191. self.autoretry_task_no_kwargs.iterations = 0
  192. self.autoretry_task_no_kwargs.apply((1, 0))
  193. assert self.autoretry_task_no_kwargs.iterations == 4
  194. def test_autoretry(self):
  195. self.autoretry_task.max_retries = 3
  196. self.autoretry_task.iterations = 0
  197. self.autoretry_task.apply((1, 0))
  198. assert self.autoretry_task.iterations == 6
  199. def test_retry_wrong_eta_when_not_enable_utc(self):
  200. """Issue #3753"""
  201. self.app.conf.enable_utc = False
  202. self.app.conf.timezone = 'US/Eastern'
  203. self.autoretry_task.iterations = 0
  204. self.autoretry_task.default_retry_delay = 2
  205. self.autoretry_task.apply((1, 0))
  206. assert self.autoretry_task.iterations == 6
  207. class test_canvas_utils(TasksCase):
  208. def test_si(self):
  209. assert self.retry_task.si()
  210. assert self.retry_task.si().immutable
  211. def test_chunks(self):
  212. assert self.retry_task.chunks(range(100), 10)
  213. def test_map(self):
  214. assert self.retry_task.map(range(100))
  215. def test_starmap(self):
  216. assert self.retry_task.starmap(range(100))
  217. def test_on_success(self):
  218. self.retry_task.on_success(1, 1, (), {})
  219. class test_tasks(TasksCase):
  220. def now(self):
  221. return self.app.now()
  222. def test_typing(self):
  223. @self.app.task()
  224. def add(x, y, kw=1):
  225. pass
  226. with pytest.raises(TypeError):
  227. add.delay(1)
  228. with pytest.raises(TypeError):
  229. add.delay(1, kw=2)
  230. with pytest.raises(TypeError):
  231. add.delay(1, 2, foobar=3)
  232. add.delay(2, 2)
  233. def test_typing__disabled(self):
  234. @self.app.task(typing=False)
  235. def add(x, y, kw=1):
  236. pass
  237. add.delay(1)
  238. add.delay(1, kw=2)
  239. add.delay(1, 2, foobar=3)
  240. def test_typing__disabled_by_app(self):
  241. with self.Celery(set_as_current=False, strict_typing=False) as app:
  242. @app.task()
  243. def add(x, y, kw=1):
  244. pass
  245. assert not add.typing
  246. add.delay(1)
  247. add.delay(1, kw=2)
  248. add.delay(1, 2, foobar=3)
  249. @pytest.mark.usefixtures('depends_on_current_app')
  250. def test_unpickle_task(self):
  251. import pickle
  252. @self.app.task(shared=True)
  253. def xxx():
  254. pass
  255. assert pickle.loads(pickle.dumps(xxx)) is xxx.app.tasks[xxx.name]
  256. @patch('celery.app.task.current_app')
  257. @pytest.mark.usefixtures('depends_on_current_app')
  258. def test_bind__no_app(self, current_app):
  259. class XTask(Task):
  260. _app = None
  261. XTask._app = None
  262. XTask.__bound__ = False
  263. XTask.bind = Mock(name='bind')
  264. assert XTask.app is current_app
  265. XTask.bind.assert_called_with(current_app)
  266. def test_reprtask__no_fmt(self):
  267. assert _reprtask(self.mytask)
  268. def test_AsyncResult(self):
  269. task_id = uuid()
  270. result = self.retry_task.AsyncResult(task_id)
  271. assert result.backend == self.retry_task.backend
  272. assert result.id == task_id
  273. def assert_next_task_data_equal(self, consumer, presult, task_name,
  274. test_eta=False, test_expires=False,
  275. **kwargs):
  276. next_task = consumer.queues[0].get(accept=['pickle', 'json'])
  277. task_data = next_task.decode()
  278. assert task_data['id'] == presult.id
  279. assert task_data['task'] == task_name
  280. task_kwargs = task_data.get('kwargs', {})
  281. if test_eta:
  282. assert isinstance(task_data.get('eta'), string_t)
  283. to_datetime = parse_iso8601(task_data.get('eta'))
  284. assert isinstance(to_datetime, datetime)
  285. if test_expires:
  286. assert isinstance(task_data.get('expires'), string_t)
  287. to_datetime = parse_iso8601(task_data.get('expires'))
  288. assert isinstance(to_datetime, datetime)
  289. for arg_name, arg_value in items(kwargs):
  290. assert task_kwargs.get(arg_name) == arg_value
  291. def test_incomplete_task_cls(self):
  292. class IncompleteTask(Task):
  293. app = self.app
  294. name = 'c.unittest.t.itask'
  295. with pytest.raises(NotImplementedError):
  296. IncompleteTask().run()
  297. def test_task_kwargs_must_be_dictionary(self):
  298. with pytest.raises(TypeError):
  299. self.increment_counter.apply_async([], 'str')
  300. def test_task_args_must_be_list(self):
  301. with pytest.raises(TypeError):
  302. self.increment_counter.apply_async('s', {})
  303. def test_regular_task(self):
  304. assert isinstance(self.mytask, Task)
  305. assert self.mytask.run()
  306. assert callable(self.mytask)
  307. assert self.mytask(), 'Task class runs run() when called'
  308. with self.app.connection_or_acquire() as conn:
  309. consumer = self.app.amqp.TaskConsumer(conn)
  310. with pytest.raises(NotImplementedError):
  311. consumer.receive('foo', 'foo')
  312. consumer.purge()
  313. assert consumer.queues[0].get() is None
  314. self.app.amqp.TaskConsumer(conn, queues=[Queue('foo')])
  315. # Without arguments.
  316. presult = self.mytask.delay()
  317. self.assert_next_task_data_equal(
  318. consumer, presult, self.mytask.name)
  319. # With arguments.
  320. presult2 = self.mytask.apply_async(
  321. kwargs=dict(name='George Costanza'),
  322. )
  323. self.assert_next_task_data_equal(
  324. consumer, presult2, self.mytask.name, name='George Costanza',
  325. )
  326. # send_task
  327. sresult = self.app.send_task(self.mytask.name,
  328. kwargs=dict(name='Elaine M. Benes'))
  329. self.assert_next_task_data_equal(
  330. consumer, sresult, self.mytask.name, name='Elaine M. Benes',
  331. )
  332. # With ETA.
  333. presult2 = self.mytask.apply_async(
  334. kwargs=dict(name='George Costanza'),
  335. eta=self.now() + timedelta(days=1),
  336. expires=self.now() + timedelta(days=2),
  337. )
  338. self.assert_next_task_data_equal(
  339. consumer, presult2, self.mytask.name,
  340. name='George Costanza', test_eta=True, test_expires=True,
  341. )
  342. # With countdown.
  343. presult2 = self.mytask.apply_async(
  344. kwargs=dict(name='George Costanza'), countdown=10, expires=12,
  345. )
  346. self.assert_next_task_data_equal(
  347. consumer, presult2, self.mytask.name,
  348. name='George Costanza', test_eta=True, test_expires=True,
  349. )
  350. # Discarding all tasks.
  351. consumer.purge()
  352. self.mytask.apply_async()
  353. assert consumer.purge() == 1
  354. assert consumer.queues[0].get() is None
  355. assert not presult.successful()
  356. self.mytask.backend.mark_as_done(presult.id, result=None)
  357. assert presult.successful()
  358. def test_send_event(self):
  359. mytask = self.mytask._get_current_object()
  360. mytask.app.events = Mock(name='events')
  361. mytask.app.events.attach_mock(ContextMock(), 'default_dispatcher')
  362. mytask.request.id = 'fb'
  363. mytask.send_event('task-foo', id=3122)
  364. mytask.app.events.default_dispatcher().send.assert_called_with(
  365. 'task-foo', uuid='fb', id=3122,
  366. retry=True, retry_policy=self.app.conf.task_publish_retry_policy)
  367. def test_replace(self):
  368. sig1 = Mock(name='sig1')
  369. sig1.options = {}
  370. with pytest.raises(Ignore):
  371. self.mytask.replace(sig1)
  372. @pytest.mark.usefixtures('depends_on_current_app')
  373. def test_replace_callback(self):
  374. c = group([self.mytask.s()], app=self.app)
  375. c.freeze = Mock(name='freeze')
  376. c.delay = Mock(name='delay')
  377. self.mytask.request.id = 'id'
  378. self.mytask.request.group = 'group'
  379. self.mytask.request.root_id = 'root_id'
  380. self.mytask.request.callbacks = 'callbacks'
  381. self.mytask.request.errbacks = 'errbacks'
  382. class JsonMagicMock(MagicMock):
  383. parent = None
  384. def __json__(self):
  385. return 'whatever'
  386. def reprcall(self, *args, **kwargs):
  387. return 'whatever2'
  388. mocked_signature = JsonMagicMock(name='s')
  389. accumulate_mock = JsonMagicMock(name='accumulate', s=mocked_signature)
  390. self.mytask.app.tasks['celery.accumulate'] = accumulate_mock
  391. try:
  392. self.mytask.replace(c)
  393. except Ignore:
  394. mocked_signature.return_value.set.assert_called_with(
  395. chord=None,
  396. link='callbacks',
  397. link_error='errbacks',
  398. )
  399. def test_replace_group(self):
  400. c = group([self.mytask.s()], app=self.app)
  401. c.freeze = Mock(name='freeze')
  402. c.delay = Mock(name='delay')
  403. self.mytask.request.id = 'id'
  404. self.mytask.request.group = 'group'
  405. self.mytask.request.root_id = 'root_id',
  406. with pytest.raises(Ignore):
  407. self.mytask.replace(c)
  408. def test_add_trail__no_trail(self):
  409. mytask = self.increment_counter._get_current_object()
  410. mytask.trail = False
  411. mytask.add_trail('foo')
  412. def test_repr_v2_compat(self):
  413. self.mytask.__v2_compat__ = True
  414. assert 'v2 compatible' in repr(self.mytask)
  415. def test_apply_with_self(self):
  416. @self.app.task(__self__=42, shared=False)
  417. def tawself(self):
  418. return self
  419. assert tawself.apply().get() == 42
  420. assert tawself() == 42
  421. def test_context_get(self):
  422. self.mytask.push_request()
  423. try:
  424. request = self.mytask.request
  425. request.foo = 32
  426. assert request.get('foo') == 32
  427. assert request.get('bar', 36) == 36
  428. request.clear()
  429. finally:
  430. self.mytask.pop_request()
  431. def test_annotate(self):
  432. with patch('celery.app.task.resolve_all_annotations') as anno:
  433. anno.return_value = [{'FOO': 'BAR'}]
  434. @self.app.task(shared=False)
  435. def task():
  436. pass
  437. task.annotate()
  438. assert task.FOO == 'BAR'
  439. def test_after_return(self):
  440. self.mytask.push_request()
  441. try:
  442. self.mytask.request.chord = self.mytask.s()
  443. self.mytask.after_return('SUCCESS', 1.0, 'foobar', (), {}, None)
  444. self.mytask.request.clear()
  445. finally:
  446. self.mytask.pop_request()
  447. def test_update_state(self):
  448. @self.app.task(shared=False)
  449. def yyy():
  450. pass
  451. yyy.push_request()
  452. try:
  453. tid = uuid()
  454. yyy.update_state(tid, 'FROBULATING', {'fooz': 'baaz'})
  455. assert yyy.AsyncResult(tid).status == 'FROBULATING'
  456. assert yyy.AsyncResult(tid).result == {'fooz': 'baaz'}
  457. yyy.request.id = tid
  458. yyy.update_state(state='FROBUZATING', meta={'fooz': 'baaz'})
  459. assert yyy.AsyncResult(tid).status == 'FROBUZATING'
  460. assert yyy.AsyncResult(tid).result == {'fooz': 'baaz'}
  461. finally:
  462. yyy.pop_request()
  463. def test_repr(self):
  464. @self.app.task(shared=False)
  465. def task_test_repr():
  466. pass
  467. assert 'task_test_repr' in repr(task_test_repr)
  468. def test_has___name__(self):
  469. @self.app.task(shared=False)
  470. def yyy2():
  471. pass
  472. assert yyy2.__name__
  473. class test_apply_task(TasksCase):
  474. def test_apply_throw(self):
  475. with pytest.raises(KeyError):
  476. self.raising.apply(throw=True)
  477. def test_apply_with_task_eager_propagates(self):
  478. self.app.conf.task_eager_propagates = True
  479. with pytest.raises(KeyError):
  480. self.raising.apply()
  481. def test_apply_request_context_is_ok(self):
  482. self.app.conf.task_eager_propagates = True
  483. self.task_check_request_context.apply()
  484. def test_apply(self):
  485. self.increment_counter.count = 0
  486. e = self.increment_counter.apply()
  487. assert isinstance(e, EagerResult)
  488. assert e.get() == 1
  489. e = self.increment_counter.apply(args=[1])
  490. assert e.get() == 2
  491. e = self.increment_counter.apply(kwargs={'increment_by': 4})
  492. assert e.get() == 6
  493. assert e.successful()
  494. assert e.ready()
  495. assert repr(e).startswith('<EagerResult:')
  496. f = self.raising.apply()
  497. assert f.ready()
  498. assert not f.successful()
  499. assert f.traceback
  500. with pytest.raises(KeyError):
  501. f.get()