test_request.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import, unicode_literals
  3. import numbers
  4. import os
  5. import signal
  6. import socket
  7. import sys
  8. from datetime import datetime, timedelta
  9. from time import time
  10. import pytest
  11. from billiard.einfo import ExceptionInfo
  12. from case import Mock, patch
  13. from kombu.utils.encoding import (default_encode, from_utf8, safe_repr,
  14. safe_str)
  15. from kombu.utils.uuid import uuid
  16. from celery import states
  17. from celery.app.trace import (TraceInfo, _trace_task_ret, build_tracer,
  18. mro_lookup, reset_worker_optimizations,
  19. setup_worker_optimizations, trace_task)
  20. from celery.exceptions import (Ignore, InvalidTaskError, Reject, Retry,
  21. TaskRevokedError, Terminated, WorkerLostError)
  22. from celery.five import monotonic
  23. from celery.signals import task_revoked
  24. from celery.worker import request as module
  25. from celery.worker import strategy
  26. from celery.worker.request import Request, create_request_cls
  27. from celery.worker.request import logger as req_logger
  28. from celery.worker.state import revoked
  29. class RequestCase:
  30. def setup(self):
  31. self.app.conf.result_serializer = 'pickle'
  32. @self.app.task(shared=False)
  33. def add(x, y, **kw_):
  34. return x + y
  35. self.add = add
  36. @self.app.task(shared=False)
  37. def mytask(i, **kwargs):
  38. return i ** i
  39. self.mytask = mytask
  40. @self.app.task(shared=False)
  41. def mytask_raising(i):
  42. raise KeyError(i)
  43. self.mytask_raising = mytask_raising
  44. def xRequest(self, name=None, id=None, args=None, kwargs=None,
  45. on_ack=None, on_reject=None, Request=Request, **head):
  46. args = [1] if args is None else args
  47. kwargs = {'f': 'x'} if kwargs is None else kwargs
  48. on_ack = on_ack or Mock(name='on_ack')
  49. on_reject = on_reject or Mock(name='on_reject')
  50. message = self.TaskMessage(
  51. name or self.mytask.name, id, args=args, kwargs=kwargs, **head
  52. )
  53. return Request(message, app=self.app,
  54. on_ack=on_ack, on_reject=on_reject)
  55. class test_mro_lookup:
  56. def test_order(self):
  57. class A(object):
  58. pass
  59. class B(A):
  60. pass
  61. class C(B):
  62. pass
  63. class D(C):
  64. @classmethod
  65. def mro(cls):
  66. return ()
  67. A.x = 10
  68. assert mro_lookup(C, 'x') == A
  69. assert mro_lookup(C, 'x', stop={A}) is None
  70. B.x = 10
  71. assert mro_lookup(C, 'x') == B
  72. C.x = 10
  73. assert mro_lookup(C, 'x') == C
  74. assert mro_lookup(D, 'x') is None
  75. def jail(app, task_id, name, args, kwargs):
  76. request = {'id': task_id}
  77. task = app.tasks[name]
  78. task.__trace__ = None # rebuild
  79. return trace_task(
  80. task, task_id, args, kwargs, request=request, eager=False, app=app,
  81. ).retval
  82. @pytest.mark.skipif(sys.version_info[0] > 3, reason='Py2 only')
  83. class test_default_encode:
  84. def test_jython(self):
  85. prev, sys.platform = sys.platform, 'java 1.6.1'
  86. try:
  87. assert default_encode(b'foo') == b'foo'
  88. finally:
  89. sys.platform = prev
  90. def test_cpython(self):
  91. prev, sys.platform = sys.platform, 'darwin'
  92. gfe, sys.getfilesystemencoding = (
  93. sys.getfilesystemencoding,
  94. lambda: 'utf-8',
  95. )
  96. try:
  97. assert default_encode(b'foo') == b'foo'
  98. finally:
  99. sys.platform = prev
  100. sys.getfilesystemencoding = gfe
  101. class test_Retry:
  102. def test_retry_semipredicate(self):
  103. try:
  104. raise Exception('foo')
  105. except Exception as exc:
  106. ret = Retry('Retrying task', exc)
  107. assert ret.exc == exc
  108. class test_trace_task(RequestCase):
  109. def test_process_cleanup_fails(self, patching):
  110. _logger = patching('celery.app.trace.logger')
  111. self.mytask.backend = Mock()
  112. self.mytask.backend.process_cleanup = Mock(side_effect=KeyError())
  113. tid = uuid()
  114. ret = jail(self.app, tid, self.mytask.name, [2], {})
  115. assert ret == 4
  116. self.mytask.backend.mark_as_done.assert_called()
  117. assert 'Process cleanup failed' in _logger.error.call_args[0][0]
  118. def test_process_cleanup_BaseException(self):
  119. self.mytask.backend = Mock()
  120. self.mytask.backend.process_cleanup = Mock(side_effect=SystemExit())
  121. with pytest.raises(SystemExit):
  122. jail(self.app, uuid(), self.mytask.name, [2], {})
  123. def test_execute_jail_success(self):
  124. ret = jail(self.app, uuid(), self.mytask.name, [2], {})
  125. assert ret == 4
  126. def test_marked_as_started(self):
  127. _started = []
  128. def store_result(tid, meta, state, **kwargs):
  129. if state == states.STARTED:
  130. _started.append(tid)
  131. self.mytask.backend.store_result = Mock(name='store_result')
  132. self.mytask.backend.store_result.side_effect = store_result
  133. self.mytask.track_started = True
  134. tid = uuid()
  135. jail(self.app, tid, self.mytask.name, [2], {})
  136. assert tid in _started
  137. self.mytask.ignore_result = True
  138. tid = uuid()
  139. jail(self.app, tid, self.mytask.name, [2], {})
  140. assert tid not in _started
  141. def test_execute_jail_failure(self):
  142. ret = jail(
  143. self.app, uuid(), self.mytask_raising.name, [4], {},
  144. )
  145. assert isinstance(ret, ExceptionInfo)
  146. assert ret.exception.args == (4,)
  147. def test_execute_ignore_result(self):
  148. @self.app.task(shared=False, ignore_result=True)
  149. def ignores_result(i):
  150. return i ** i
  151. task_id = uuid()
  152. ret = jail(self.app, task_id, ignores_result.name, [4], {})
  153. assert ret == 256
  154. assert not self.app.AsyncResult(task_id).ready()
  155. class test_Request(RequestCase):
  156. def get_request(self,
  157. sig,
  158. Request=Request,
  159. exclude_headers=None,
  160. **kwargs):
  161. msg = self.task_message_from_sig(self.app, sig)
  162. headers = None
  163. if exclude_headers:
  164. headers = msg.headers
  165. for header in exclude_headers:
  166. headers.pop(header)
  167. return Request(
  168. msg,
  169. on_ack=Mock(name='on_ack'),
  170. on_reject=Mock(name='on_reject'),
  171. eventer=Mock(name='eventer'),
  172. app=self.app,
  173. connection_errors=(socket.error,),
  174. task=sig.type,
  175. headers=headers,
  176. **kwargs
  177. )
  178. def test_shadow(self):
  179. assert self.get_request(
  180. self.add.s(2, 2).set(shadow='fooxyz')).name == 'fooxyz'
  181. def test_no_shadow_header(self):
  182. request = self.get_request(self.add.s(2, 2),
  183. exclude_headers=['shadow'])
  184. assert request.name == 't.unit.worker.test_request.add'
  185. def test_invalid_eta_raises_InvalidTaskError(self):
  186. with pytest.raises(InvalidTaskError):
  187. self.get_request(self.add.s(2, 2).set(eta='12345'))
  188. def test_invalid_expires_raises_InvalidTaskError(self):
  189. with pytest.raises(InvalidTaskError):
  190. self.get_request(self.add.s(2, 2).set(expires='12345'))
  191. def test_valid_expires_with_utc_makes_aware(self):
  192. with patch('celery.worker.request.maybe_make_aware') as mma:
  193. self.get_request(self.add.s(2, 2).set(expires=10),
  194. maybe_make_aware=mma)
  195. mma.assert_called()
  196. def test_maybe_expire_when_expires_is_None(self):
  197. req = self.get_request(self.add.s(2, 2))
  198. assert not req.maybe_expire()
  199. def test_on_retry_acks_if_late(self):
  200. self.add.acks_late = True
  201. req = self.get_request(self.add.s(2, 2))
  202. req.on_retry(Mock())
  203. req.on_ack.assert_called_with(req_logger, req.connection_errors)
  204. def test_on_failure_Termianted(self):
  205. einfo = None
  206. try:
  207. raise Terminated('9')
  208. except Terminated:
  209. einfo = ExceptionInfo()
  210. assert einfo is not None
  211. req = self.get_request(self.add.s(2, 2))
  212. req.on_failure(einfo)
  213. req.eventer.send.assert_called_with(
  214. 'task-revoked',
  215. uuid=req.id, terminated=True, signum='9', expired=False,
  216. )
  217. def test_on_failure_propagates_MemoryError(self):
  218. einfo = None
  219. try:
  220. raise MemoryError()
  221. except MemoryError:
  222. einfo = ExceptionInfo(internal=True)
  223. assert einfo is not None
  224. req = self.get_request(self.add.s(2, 2))
  225. with pytest.raises(MemoryError):
  226. req.on_failure(einfo)
  227. def test_on_failure_Ignore_acknowledges(self):
  228. einfo = None
  229. try:
  230. raise Ignore()
  231. except Ignore:
  232. einfo = ExceptionInfo(internal=True)
  233. assert einfo is not None
  234. req = self.get_request(self.add.s(2, 2))
  235. req.on_failure(einfo)
  236. req.on_ack.assert_called_with(req_logger, req.connection_errors)
  237. def test_on_failure_Reject_rejects(self):
  238. einfo = None
  239. try:
  240. raise Reject()
  241. except Reject:
  242. einfo = ExceptionInfo(internal=True)
  243. assert einfo is not None
  244. req = self.get_request(self.add.s(2, 2))
  245. req.on_failure(einfo)
  246. req.on_reject.assert_called_with(
  247. req_logger, req.connection_errors, False,
  248. )
  249. def test_on_failure_Reject_rejects_with_requeue(self):
  250. einfo = None
  251. try:
  252. raise Reject(requeue=True)
  253. except Reject:
  254. einfo = ExceptionInfo(internal=True)
  255. assert einfo is not None
  256. req = self.get_request(self.add.s(2, 2))
  257. req.on_failure(einfo)
  258. req.on_reject.assert_called_with(
  259. req_logger, req.connection_errors, True,
  260. )
  261. def test_on_failure_WorkerLostError_rejects_with_requeue(self):
  262. einfo = None
  263. try:
  264. raise WorkerLostError()
  265. except:
  266. einfo = ExceptionInfo(internal=True)
  267. req = self.get_request(self.add.s(2, 2))
  268. req.task.acks_late = True
  269. req.task.reject_on_worker_lost = True
  270. req.delivery_info['redelivered'] = False
  271. req.on_failure(einfo)
  272. req.on_reject.assert_called_with(
  273. req_logger, req.connection_errors, True)
  274. def test_on_failure_WorkerLostError_redelivered_None(self):
  275. einfo = None
  276. try:
  277. raise WorkerLostError()
  278. except:
  279. einfo = ExceptionInfo(internal=True)
  280. req = self.get_request(self.add.s(2, 2))
  281. req.task.acks_late = True
  282. req.task.reject_on_worker_lost = True
  283. req.delivery_info['redelivered'] = None
  284. req.on_failure(einfo)
  285. req.on_reject.assert_called_with(
  286. req_logger, req.connection_errors, True)
  287. def test_tzlocal_is_cached(self):
  288. req = self.get_request(self.add.s(2, 2))
  289. req._tzlocal = 'foo'
  290. assert req.tzlocal == 'foo'
  291. def test_task_wrapper_repr(self):
  292. assert repr(self.xRequest())
  293. def test_sets_store_errors(self):
  294. self.mytask.ignore_result = True
  295. job = self.xRequest()
  296. assert not job.store_errors
  297. self.mytask.store_errors_even_if_ignored = True
  298. job = self.xRequest()
  299. assert job.store_errors
  300. def test_send_event(self):
  301. job = self.xRequest()
  302. job.eventer = Mock(name='.eventer')
  303. job.send_event('task-frobulated')
  304. job.eventer.send.assert_called_with('task-frobulated', uuid=job.id)
  305. def test_send_events__disabled_at_task_level(self):
  306. job = self.xRequest()
  307. job.task.send_events = False
  308. job.eventer = Mock(name='.eventer')
  309. job.send_event('task-frobulated')
  310. job.eventer.send.assert_not_called()
  311. def test_on_retry(self):
  312. job = self.get_request(self.mytask.s(1, f='x'))
  313. job.eventer = Mock(name='.eventer')
  314. try:
  315. raise Retry('foo', KeyError('moofoobar'))
  316. except:
  317. einfo = ExceptionInfo()
  318. job.on_failure(einfo)
  319. job.eventer.send.assert_called_with(
  320. 'task-retried',
  321. uuid=job.id,
  322. exception=safe_repr(einfo.exception.exc),
  323. traceback=safe_str(einfo.traceback),
  324. )
  325. prev, module._does_info = module._does_info, False
  326. try:
  327. job.on_failure(einfo)
  328. finally:
  329. module._does_info = prev
  330. einfo.internal = True
  331. job.on_failure(einfo)
  332. def test_compat_properties(self):
  333. job = self.xRequest()
  334. assert job.task_id == job.id
  335. assert job.task_name == job.name
  336. job.task_id = 'ID'
  337. assert job.id == 'ID'
  338. job.task_name = 'NAME'
  339. assert job.name == 'NAME'
  340. def test_terminate__pool_ref(self):
  341. pool = Mock()
  342. signum = signal.SIGTERM
  343. job = self.get_request(self.mytask.s(1, f='x'))
  344. job._apply_result = Mock(name='_apply_result')
  345. with self.assert_signal_called(
  346. task_revoked, sender=job.task, request=job,
  347. terminated=True, expired=False, signum=signum):
  348. job.time_start = monotonic()
  349. job.worker_pid = 314
  350. job.terminate(pool, signal='TERM')
  351. job._apply_result().terminate.assert_called_with(signum)
  352. job._apply_result = Mock(name='_apply_result2')
  353. job._apply_result.return_value = None
  354. job.terminate(pool, signal='TERM')
  355. def test_terminate__task_started(self):
  356. pool = Mock()
  357. signum = signal.SIGTERM
  358. job = self.get_request(self.mytask.s(1, f='x'))
  359. with self.assert_signal_called(
  360. task_revoked, sender=job.task, request=job,
  361. terminated=True, expired=False, signum=signum):
  362. job.time_start = monotonic()
  363. job.worker_pid = 313
  364. job.terminate(pool, signal='TERM')
  365. pool.terminate_job.assert_called_with(job.worker_pid, signum)
  366. def test_terminate__task_reserved(self):
  367. pool = Mock()
  368. job = self.get_request(self.mytask.s(1, f='x'))
  369. job.time_start = None
  370. job.terminate(pool, signal='TERM')
  371. pool.terminate_job.assert_not_called()
  372. assert job._terminate_on_ack == (pool, 15)
  373. job.terminate(pool, signal='TERM')
  374. def test_revoked_expires_expired(self):
  375. job = self.get_request(self.mytask.s(1, f='x').set(
  376. expires=datetime.utcnow() - timedelta(days=1)
  377. ))
  378. with self.assert_signal_called(
  379. task_revoked, sender=job.task, request=job,
  380. terminated=False, expired=True, signum=None):
  381. job.revoked()
  382. assert job.id in revoked
  383. assert self.mytask.backend.get_status(job.id) == states.REVOKED
  384. def test_revoked_expires_not_expired(self):
  385. job = self.xRequest(
  386. expires=datetime.utcnow() + timedelta(days=1),
  387. )
  388. job.revoked()
  389. assert job.id not in revoked
  390. assert self.mytask.backend.get_status(job.id) != states.REVOKED
  391. def test_revoked_expires_ignore_result(self):
  392. self.mytask.ignore_result = True
  393. job = self.xRequest(
  394. expires=datetime.utcnow() - timedelta(days=1),
  395. )
  396. job.revoked()
  397. assert job.id in revoked
  398. assert self.mytask.backend.get_status(job.id) != states.REVOKED
  399. def test_already_revoked(self):
  400. job = self.xRequest()
  401. job._already_revoked = True
  402. assert job.revoked()
  403. def test_revoked(self):
  404. job = self.xRequest()
  405. with self.assert_signal_called(
  406. task_revoked, sender=job.task, request=job,
  407. terminated=False, expired=False, signum=None):
  408. revoked.add(job.id)
  409. assert job.revoked()
  410. assert job._already_revoked
  411. assert job.acknowledged
  412. def test_execute_does_not_execute_revoked(self):
  413. job = self.xRequest()
  414. revoked.add(job.id)
  415. job.execute()
  416. def test_execute_acks_late(self):
  417. self.mytask_raising.acks_late = True
  418. job = self.xRequest(
  419. name=self.mytask_raising.name,
  420. kwargs={},
  421. )
  422. job.execute()
  423. assert job.acknowledged
  424. job.execute()
  425. def test_execute_using_pool_does_not_execute_revoked(self):
  426. job = self.xRequest()
  427. revoked.add(job.id)
  428. with pytest.raises(TaskRevokedError):
  429. job.execute_using_pool(None)
  430. def test_on_accepted_acks_early(self):
  431. job = self.xRequest()
  432. job.on_accepted(pid=os.getpid(), time_accepted=monotonic())
  433. assert job.acknowledged
  434. prev, module._does_debug = module._does_debug, False
  435. try:
  436. job.on_accepted(pid=os.getpid(), time_accepted=monotonic())
  437. finally:
  438. module._does_debug = prev
  439. def test_on_accepted_acks_late(self):
  440. job = self.xRequest()
  441. self.mytask.acks_late = True
  442. job.on_accepted(pid=os.getpid(), time_accepted=monotonic())
  443. assert not job.acknowledged
  444. def test_on_accepted_terminates(self):
  445. signum = signal.SIGTERM
  446. pool = Mock()
  447. job = self.xRequest()
  448. with self.assert_signal_called(
  449. task_revoked, sender=job.task, request=job,
  450. terminated=True, expired=False, signum=signum):
  451. job.terminate(pool, signal='TERM')
  452. assert not pool.terminate_job.call_count
  453. job.on_accepted(pid=314, time_accepted=monotonic())
  454. pool.terminate_job.assert_called_with(314, signum)
  455. def test_on_accepted_time_start(self):
  456. job = self.xRequest()
  457. job.on_accepted(pid=os.getpid(), time_accepted=monotonic())
  458. assert time() - job.time_start < 1
  459. def test_on_success_acks_early(self):
  460. job = self.xRequest()
  461. job.time_start = 1
  462. job.on_success((0, 42, 0.001))
  463. prev, module._does_info = module._does_info, False
  464. try:
  465. job.on_success((0, 42, 0.001))
  466. assert not job.acknowledged
  467. finally:
  468. module._does_info = prev
  469. def test_on_success_BaseException(self):
  470. job = self.xRequest()
  471. job.time_start = 1
  472. with pytest.raises(SystemExit):
  473. try:
  474. raise SystemExit()
  475. except SystemExit:
  476. job.on_success((1, ExceptionInfo(), 0.01))
  477. else:
  478. assert False
  479. def test_on_success_eventer(self):
  480. job = self.xRequest()
  481. job.time_start = 1
  482. job.eventer = Mock()
  483. job.eventer.send = Mock()
  484. job.on_success((0, 42, 0.001))
  485. job.eventer.send.assert_called()
  486. def test_on_success_when_failure(self):
  487. job = self.xRequest()
  488. job.time_start = 1
  489. job.on_failure = Mock()
  490. try:
  491. raise KeyError('foo')
  492. except Exception:
  493. job.on_success((1, ExceptionInfo(), 0.001))
  494. job.on_failure.assert_called()
  495. def test_on_success_acks_late(self):
  496. job = self.xRequest()
  497. job.time_start = 1
  498. self.mytask.acks_late = True
  499. job.on_success((0, 42, 0.001))
  500. assert job.acknowledged
  501. def test_on_failure_WorkerLostError(self):
  502. def get_ei():
  503. try:
  504. raise WorkerLostError('do re mi')
  505. except WorkerLostError:
  506. return ExceptionInfo()
  507. job = self.xRequest()
  508. exc_info = get_ei()
  509. job.on_failure(exc_info)
  510. assert self.mytask.backend.get_status(job.id) == states.FAILURE
  511. self.mytask.ignore_result = True
  512. exc_info = get_ei()
  513. job = self.xRequest()
  514. job.on_failure(exc_info)
  515. assert self.mytask.backend.get_status(job.id) == states.PENDING
  516. def test_on_failure_acks_late(self):
  517. job = self.xRequest()
  518. job.time_start = 1
  519. self.mytask.acks_late = True
  520. try:
  521. raise KeyError('foo')
  522. except KeyError:
  523. exc_info = ExceptionInfo()
  524. job.on_failure(exc_info)
  525. assert job.acknowledged
  526. def test_from_message_invalid_kwargs(self):
  527. m = self.TaskMessage(self.mytask.name, args=(), kwargs='foo')
  528. req = Request(m, app=self.app)
  529. with pytest.raises(InvalidTaskError):
  530. raise req.execute().exception
  531. def test_on_hard_timeout(self, patching):
  532. error = patching('celery.worker.request.error')
  533. job = self.xRequest()
  534. job.acknowledge = Mock(name='ack')
  535. job.task.acks_late = True
  536. job.on_timeout(soft=False, timeout=1337)
  537. assert 'Hard time limit' in error.call_args[0][0]
  538. assert self.mytask.backend.get_status(job.id) == states.FAILURE
  539. job.acknowledge.assert_called_with()
  540. job = self.xRequest()
  541. job.acknowledge = Mock(name='ack')
  542. job.task.acks_late = False
  543. job.on_timeout(soft=False, timeout=1335)
  544. job.acknowledge.assert_not_called()
  545. def test_on_soft_timeout(self, patching):
  546. warn = patching('celery.worker.request.warn')
  547. job = self.xRequest()
  548. job.acknowledge = Mock(name='ack')
  549. job.task.acks_late = True
  550. job.on_timeout(soft=True, timeout=1337)
  551. assert 'Soft time limit' in warn.call_args[0][0]
  552. assert self.mytask.backend.get_status(job.id) == states.PENDING
  553. job.acknowledge.assert_not_called()
  554. self.mytask.ignore_result = True
  555. job = self.xRequest()
  556. job.on_timeout(soft=True, timeout=1336)
  557. assert self.mytask.backend.get_status(job.id) == states.PENDING
  558. def test_fast_trace_task(self):
  559. from celery.app import trace
  560. setup_worker_optimizations(self.app)
  561. assert trace.trace_task_ret is trace._fast_trace_task
  562. tid = uuid()
  563. message = self.TaskMessage(self.mytask.name, tid, args=[4])
  564. assert len(message.payload) == 3
  565. try:
  566. self.mytask.__trace__ = build_tracer(
  567. self.mytask.name, self.mytask, self.app.loader, 'test',
  568. app=self.app,
  569. )
  570. failed, res, runtime = trace.trace_task_ret(
  571. self.mytask.name, tid, message.headers, message.body,
  572. message.content_type, message.content_encoding)
  573. assert not failed
  574. assert res == repr(4 ** 4)
  575. assert runtime is not None
  576. assert isinstance(runtime, numbers.Real)
  577. finally:
  578. reset_worker_optimizations()
  579. assert trace.trace_task_ret is trace._trace_task_ret
  580. delattr(self.mytask, '__trace__')
  581. failed, res, runtime = trace.trace_task_ret(
  582. self.mytask.name, tid, message.headers, message.body,
  583. message.content_type, message.content_encoding, app=self.app,
  584. )
  585. assert not failed
  586. assert res == repr(4 ** 4)
  587. assert runtime is not None
  588. assert isinstance(runtime, numbers.Real)
  589. def test_trace_task_ret(self):
  590. self.mytask.__trace__ = build_tracer(
  591. self.mytask.name, self.mytask, self.app.loader, 'test',
  592. app=self.app,
  593. )
  594. tid = uuid()
  595. message = self.TaskMessage(self.mytask.name, tid, args=[4])
  596. _, R, _ = _trace_task_ret(
  597. self.mytask.name, tid, message.headers,
  598. message.body, message.content_type,
  599. message.content_encoding, app=self.app,
  600. )
  601. assert R == repr(4 ** 4)
  602. def test_trace_task_ret__no_trace(self):
  603. try:
  604. delattr(self.mytask, '__trace__')
  605. except AttributeError:
  606. pass
  607. tid = uuid()
  608. message = self.TaskMessage(self.mytask.name, tid, args=[4])
  609. _, R, _ = _trace_task_ret(
  610. self.mytask.name, tid, message.headers,
  611. message.body, message.content_type,
  612. message.content_encoding, app=self.app,
  613. )
  614. assert R == repr(4 ** 4)
  615. def test_trace_catches_exception(self):
  616. @self.app.task(request=None, shared=False)
  617. def raising():
  618. raise KeyError('baz')
  619. with pytest.warns(RuntimeWarning):
  620. res = trace_task(raising, uuid(), [], {}, app=self.app)[0]
  621. assert isinstance(res, ExceptionInfo)
  622. def test_worker_task_trace_handle_retry(self):
  623. tid = uuid()
  624. self.mytask.push_request(id=tid)
  625. try:
  626. raise ValueError('foo')
  627. except Exception as exc:
  628. try:
  629. raise Retry(str(exc), exc=exc)
  630. except Retry as exc:
  631. w = TraceInfo(states.RETRY, exc)
  632. w.handle_retry(
  633. self.mytask, self.mytask.request, store_errors=False,
  634. )
  635. assert self.mytask.backend.get_status(tid) == states.PENDING
  636. w.handle_retry(
  637. self.mytask, self.mytask.request, store_errors=True,
  638. )
  639. assert self.mytask.backend.get_status(tid) == states.RETRY
  640. finally:
  641. self.mytask.pop_request()
  642. def test_worker_task_trace_handle_failure(self):
  643. tid = uuid()
  644. self.mytask.push_request()
  645. try:
  646. self.mytask.request.id = tid
  647. try:
  648. raise ValueError('foo')
  649. except Exception as exc:
  650. w = TraceInfo(states.FAILURE, exc)
  651. w.handle_failure(
  652. self.mytask, self.mytask.request, store_errors=False,
  653. )
  654. assert self.mytask.backend.get_status(tid) == states.PENDING
  655. w.handle_failure(
  656. self.mytask, self.mytask.request, store_errors=True,
  657. )
  658. assert self.mytask.backend.get_status(tid) == states.FAILURE
  659. finally:
  660. self.mytask.pop_request()
  661. def test_from_message(self):
  662. us = 'æØåveéðƒeæ'
  663. tid = uuid()
  664. m = self.TaskMessage(
  665. self.mytask.name, tid, args=[2], kwargs={us: 'bar'},
  666. )
  667. job = Request(m, app=self.app)
  668. assert isinstance(job, Request)
  669. assert job.name == self.mytask.name
  670. assert job.id == tid
  671. assert job.message is m
  672. def test_from_message_empty_args(self):
  673. tid = uuid()
  674. m = self.TaskMessage(self.mytask.name, tid, args=[], kwargs={})
  675. job = Request(m, app=self.app)
  676. assert isinstance(job, Request)
  677. def test_from_message_missing_required_fields(self):
  678. m = self.TaskMessage(self.mytask.name)
  679. m.headers.clear()
  680. with pytest.raises(KeyError):
  681. Request(m, app=self.app)
  682. def test_from_message_nonexistant_task(self):
  683. m = self.TaskMessage(
  684. 'cu.mytask.doesnotexist',
  685. args=[2], kwargs={'æØåveéðƒeæ': 'bar'},
  686. )
  687. with pytest.raises(KeyError):
  688. Request(m, app=self.app)
  689. def test_execute(self):
  690. tid = uuid()
  691. job = self.xRequest(id=tid, args=[4], kwargs={})
  692. assert job.execute() == 256
  693. meta = self.mytask.backend.get_task_meta(tid)
  694. assert meta['status'] == states.SUCCESS
  695. assert meta['result'] == 256
  696. def test_execute_success_no_kwargs(self):
  697. @self.app.task # traverses coverage for decorator without parens
  698. def mytask_no_kwargs(i):
  699. return i ** i
  700. tid = uuid()
  701. job = self.xRequest(
  702. name=mytask_no_kwargs.name,
  703. id=tid,
  704. args=[4],
  705. kwargs={},
  706. )
  707. assert job.execute() == 256
  708. meta = mytask_no_kwargs.backend.get_task_meta(tid)
  709. assert meta['result'] == 256
  710. assert meta['status'] == states.SUCCESS
  711. def test_execute_ack(self):
  712. scratch = {'ACK': False}
  713. def on_ack(*args, **kwargs):
  714. scratch['ACK'] = True
  715. tid = uuid()
  716. job = self.xRequest(id=tid, args=[4], on_ack=on_ack)
  717. assert job.execute() == 256
  718. meta = self.mytask.backend.get_task_meta(tid)
  719. assert scratch['ACK']
  720. assert meta['result'] == 256
  721. assert meta['status'] == states.SUCCESS
  722. def test_execute_fail(self):
  723. tid = uuid()
  724. job = self.xRequest(
  725. name=self.mytask_raising.name,
  726. id=tid,
  727. args=[4],
  728. kwargs={},
  729. )
  730. assert isinstance(job.execute(), ExceptionInfo)
  731. assert self.mytask_raising.backend.serializer == 'pickle'
  732. meta = self.mytask_raising.backend.get_task_meta(tid)
  733. assert meta['status'] == states.FAILURE
  734. assert isinstance(meta['result'], KeyError)
  735. def test_execute_using_pool(self):
  736. tid = uuid()
  737. job = self.xRequest(id=tid, args=[4])
  738. p = Mock()
  739. job.execute_using_pool(p)
  740. p.apply_async.assert_called_once()
  741. args = p.apply_async.call_args[1]['args']
  742. assert args[0] == self.mytask.name
  743. assert args[1] == tid
  744. assert args[2] == job.request_dict
  745. assert args[3] == job.message.body
  746. def _test_on_failure(self, exception, **kwargs):
  747. tid = uuid()
  748. job = self.xRequest(id=tid, args=[4])
  749. job.send_event = Mock(name='send_event')
  750. job.task.backend.mark_as_failure = Mock(name='mark_as_failure')
  751. try:
  752. raise exception
  753. except type(exception):
  754. exc_info = ExceptionInfo()
  755. job.on_failure(exc_info, **kwargs)
  756. job.send_event.assert_called()
  757. return job
  758. def test_on_failure(self):
  759. self._test_on_failure(Exception('Inside unit tests'))
  760. def test_on_failure__unicode_exception(self):
  761. self._test_on_failure(Exception('Бобры атакуют'))
  762. def test_on_failure__utf8_exception(self):
  763. self._test_on_failure(Exception(
  764. from_utf8('Бобры атакуют')))
  765. def test_on_failure__WorkerLostError(self):
  766. exc = WorkerLostError()
  767. job = self._test_on_failure(exc)
  768. job.task.backend.mark_as_failure.assert_called_with(
  769. job.id, exc, request=job, store_result=True,
  770. )
  771. def test_on_failure__return_ok(self):
  772. self._test_on_failure(KeyError(), return_ok=True)
  773. def test_reject(self):
  774. job = self.xRequest(id=uuid())
  775. job.on_reject = Mock(name='on_reject')
  776. job.reject(requeue=True)
  777. job.on_reject.assert_called_with(
  778. req_logger, job.connection_errors, True,
  779. )
  780. assert job.acknowledged
  781. job.on_reject.reset_mock()
  782. job.reject(requeue=True)
  783. job.on_reject.assert_not_called()
  784. def test_group(self):
  785. gid = uuid()
  786. job = self.xRequest(id=uuid(), group=gid)
  787. assert job.group == gid
  788. class test_create_request_class(RequestCase):
  789. def setup(self):
  790. self.task = Mock(name='task')
  791. self.pool = Mock(name='pool')
  792. self.eventer = Mock(name='eventer')
  793. RequestCase.setup(self)
  794. def create_request_cls(self, **kwargs):
  795. return create_request_cls(
  796. Request, self.task, self.pool, 'foo', self.eventer, **kwargs
  797. )
  798. def zRequest(self, Request=None, revoked_tasks=None, ref=None, **kwargs):
  799. return self.xRequest(
  800. Request=Request or self.create_request_cls(
  801. ref=ref,
  802. revoked_tasks=revoked_tasks,
  803. ),
  804. **kwargs)
  805. def test_on_success(self):
  806. self.zRequest(id=uuid()).on_success((False, 'hey', 3.1222))
  807. def test_on_success__SystemExit(self,
  808. errors=(SystemExit, KeyboardInterrupt)):
  809. for exc in errors:
  810. einfo = None
  811. try:
  812. raise exc()
  813. except exc:
  814. einfo = ExceptionInfo()
  815. with pytest.raises(exc):
  816. self.zRequest(id=uuid()).on_success((True, einfo, 1.0))
  817. def test_on_success__calls_failure(self):
  818. job = self.zRequest(id=uuid())
  819. einfo = Mock(name='einfo')
  820. job.on_failure = Mock(name='on_failure')
  821. job.on_success((True, einfo, 1.0))
  822. job.on_failure.assert_called_with(einfo, return_ok=True)
  823. def test_on_success__acks_late_enabled(self):
  824. self.task.acks_late = True
  825. job = self.zRequest(id=uuid())
  826. job.acknowledge = Mock(name='ack')
  827. job.on_success((False, 'foo', 1.0))
  828. job.acknowledge.assert_called_with()
  829. def test_on_success__acks_late_disabled(self):
  830. self.task.acks_late = False
  831. job = self.zRequest(id=uuid())
  832. job.acknowledge = Mock(name='ack')
  833. job.on_success((False, 'foo', 1.0))
  834. job.acknowledge.assert_not_called()
  835. def test_on_success__no_events(self):
  836. self.eventer = None
  837. job = self.zRequest(id=uuid())
  838. job.send_event = Mock(name='send_event')
  839. job.on_success((False, 'foo', 1.0))
  840. job.send_event.assert_not_called()
  841. def test_on_success__with_events(self):
  842. job = self.zRequest(id=uuid())
  843. job.send_event = Mock(name='send_event')
  844. job.on_success((False, 'foo', 1.0))
  845. job.send_event.assert_called_with(
  846. 'task-succeeded', result='foo', runtime=1.0,
  847. )
  848. def test_execute_using_pool__revoked(self):
  849. tid = uuid()
  850. job = self.zRequest(id=tid, revoked_tasks={tid})
  851. job.revoked = Mock()
  852. job.revoked.return_value = True
  853. with pytest.raises(TaskRevokedError):
  854. job.execute_using_pool(self.pool)
  855. def test_execute_using_pool__expired(self):
  856. tid = uuid()
  857. job = self.zRequest(id=tid, revoked_tasks=set())
  858. job.expires = 1232133
  859. job.revoked = Mock()
  860. job.revoked.return_value = True
  861. with pytest.raises(TaskRevokedError):
  862. job.execute_using_pool(self.pool)
  863. def test_execute_using_pool(self):
  864. from celery.app.trace import trace_task_ret as trace
  865. weakref_ref = Mock(name='weakref.ref')
  866. job = self.zRequest(id=uuid(), revoked_tasks=set(), ref=weakref_ref)
  867. job.execute_using_pool(self.pool)
  868. self.pool.apply_async.assert_called_with(
  869. trace,
  870. args=(job.type, job.id, job.request_dict, job.body,
  871. job.content_type, job.content_encoding),
  872. accept_callback=job.on_accepted,
  873. timeout_callback=job.on_timeout,
  874. callback=job.on_success,
  875. error_callback=job.on_failure,
  876. soft_timeout=self.task.soft_time_limit,
  877. timeout=self.task.time_limit,
  878. correlation_id=job.id,
  879. )
  880. assert job._apply_result
  881. weakref_ref.assert_called_with(self.pool.apply_async())
  882. assert job._apply_result is weakref_ref()
  883. def test_execute_using_pool_with_none_timelimit_header(self):
  884. from celery.app.trace import trace_task_ret as trace
  885. weakref_ref = Mock(name='weakref.ref')
  886. job = self.zRequest(id=uuid(),
  887. revoked_tasks=set(),
  888. ref=weakref_ref,
  889. headers={'timelimit': None})
  890. job.execute_using_pool(self.pool)
  891. self.pool.apply_async.assert_called_with(
  892. trace,
  893. args=(job.type, job.id, job.request_dict, job.body,
  894. job.content_type, job.content_encoding),
  895. accept_callback=job.on_accepted,
  896. timeout_callback=job.on_timeout,
  897. callback=job.on_success,
  898. error_callback=job.on_failure,
  899. soft_timeout=self.task.soft_time_limit,
  900. timeout=self.task.time_limit,
  901. correlation_id=job.id,
  902. )
  903. assert job._apply_result
  904. weakref_ref.assert_called_with(self.pool.apply_async())
  905. assert job._apply_result is weakref_ref()
  906. def test_execute_using_pool__defaults_of_hybrid_to_proto2(self):
  907. weakref_ref = Mock(name='weakref.ref')
  908. headers = strategy.hybrid_to_proto2('', {'id': uuid(),
  909. 'task': self.mytask.name})[1]
  910. job = self.zRequest(revoked_tasks=set(), ref=weakref_ref, **headers)
  911. job.execute_using_pool(self.pool)
  912. assert job._apply_result
  913. weakref_ref.assert_called_with(self.pool.apply_async())
  914. assert job._apply_result is weakref_ref()