test_request.py 33 KB

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