test_trace.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. from __future__ import absolute_import, unicode_literals
  2. import pytest
  3. from case import Mock, patch
  4. from kombu.exceptions import EncodeError
  5. from celery import group, signals, states, uuid
  6. from celery.app.trace import (TraceInfo, _fast_trace_task, _trace_task_ret,
  7. build_tracer, get_log_policy,
  8. log_policy_expected, log_policy_ignore,
  9. log_policy_internal, log_policy_reject,
  10. log_policy_unexpected,
  11. reset_worker_optimizations,
  12. setup_worker_optimizations, trace_task)
  13. from celery.exceptions import Ignore, Reject, Retry
  14. def trace(app, task, args=(), kwargs={},
  15. propagate=False, eager=True, request=None, **opts):
  16. t = build_tracer(task.name, task,
  17. eager=eager, propagate=propagate, app=app, **opts)
  18. ret = t('id-1', args, kwargs, request)
  19. return ret.retval, ret.info
  20. class TraceCase:
  21. def setup(self):
  22. @self.app.task(shared=False)
  23. def add(x, y):
  24. return x + y
  25. self.add = add
  26. @self.app.task(shared=False, ignore_result=True)
  27. def add_cast(x, y):
  28. return x + y
  29. self.add_cast = add_cast
  30. @self.app.task(shared=False)
  31. def raises(exc):
  32. raise exc
  33. self.raises = raises
  34. def trace(self, *args, **kwargs):
  35. return trace(self.app, *args, **kwargs)
  36. class test_trace(TraceCase):
  37. def test_trace_successful(self):
  38. retval, info = self.trace(self.add, (2, 2), {})
  39. assert info is None
  40. assert retval == 4
  41. def test_trace_on_success(self):
  42. @self.app.task(shared=False, on_success=Mock())
  43. def add_with_success(x, y):
  44. return x + y
  45. self.trace(add_with_success, (2, 2), {})
  46. add_with_success.on_success.assert_called()
  47. def test_get_log_policy(self):
  48. einfo = Mock(name='einfo')
  49. einfo.internal = False
  50. assert get_log_policy(self.add, einfo, Reject()) is log_policy_reject
  51. assert get_log_policy(self.add, einfo, Ignore()) is log_policy_ignore
  52. self.add.throws = (TypeError,)
  53. assert (get_log_policy(self.add, einfo, KeyError()) is
  54. log_policy_unexpected)
  55. assert (get_log_policy(self.add, einfo, TypeError()) is
  56. log_policy_expected)
  57. einfo2 = Mock(name='einfo2')
  58. einfo2.internal = True
  59. assert (get_log_policy(self.add, einfo2, KeyError()) is
  60. log_policy_internal)
  61. def test_trace_after_return(self):
  62. @self.app.task(shared=False, after_return=Mock())
  63. def add_with_after_return(x, y):
  64. return x + y
  65. self.trace(add_with_after_return, (2, 2), {})
  66. add_with_after_return.after_return.assert_called()
  67. def test_with_prerun_receivers(self):
  68. on_prerun = Mock()
  69. signals.task_prerun.connect(on_prerun)
  70. try:
  71. self.trace(self.add, (2, 2), {})
  72. on_prerun.assert_called()
  73. finally:
  74. signals.task_prerun.receivers[:] = []
  75. def test_with_postrun_receivers(self):
  76. on_postrun = Mock()
  77. signals.task_postrun.connect(on_postrun)
  78. try:
  79. self.trace(self.add, (2, 2), {})
  80. on_postrun.assert_called()
  81. finally:
  82. signals.task_postrun.receivers[:] = []
  83. def test_with_success_receivers(self):
  84. on_success = Mock()
  85. signals.task_success.connect(on_success)
  86. try:
  87. self.trace(self.add, (2, 2), {})
  88. on_success.assert_called()
  89. finally:
  90. signals.task_success.receivers[:] = []
  91. def test_when_chord_part(self):
  92. @self.app.task(shared=False)
  93. def add(x, y):
  94. return x + y
  95. add.backend = Mock()
  96. request = {'chord': uuid()}
  97. self.trace(add, (2, 2), {}, request=request)
  98. add.backend.mark_as_done.assert_called()
  99. args, kwargs = add.backend.mark_as_done.call_args
  100. assert args[0] == 'id-1'
  101. assert args[1] == 4
  102. assert args[2].chord == request['chord']
  103. assert not args[3]
  104. def test_when_backend_cleanup_raises(self):
  105. @self.app.task(shared=False)
  106. def add(x, y):
  107. return x + y
  108. add.backend = Mock(name='backend')
  109. add.backend.process_cleanup.side_effect = KeyError()
  110. self.trace(add, (2, 2), {}, eager=False)
  111. add.backend.process_cleanup.assert_called_with()
  112. add.backend.process_cleanup.side_effect = MemoryError()
  113. with pytest.raises(MemoryError):
  114. self.trace(add, (2, 2), {}, eager=False)
  115. def test_when_Ignore(self):
  116. @self.app.task(shared=False)
  117. def ignored():
  118. raise Ignore()
  119. retval, info = self.trace(ignored, (), {})
  120. assert info.state == states.IGNORED
  121. def test_when_Reject(self):
  122. @self.app.task(shared=False)
  123. def rejecting():
  124. raise Reject()
  125. retval, info = self.trace(rejecting, (), {})
  126. assert info.state == states.REJECTED
  127. def test_backend_cleanup_raises(self):
  128. self.add.backend.process_cleanup = Mock()
  129. self.add.backend.process_cleanup.side_effect = RuntimeError()
  130. self.trace(self.add, (2, 2), {})
  131. @patch('celery.canvas.maybe_signature')
  132. def test_callbacks__scalar(self, maybe_signature):
  133. sig = Mock(name='sig')
  134. request = {'callbacks': [sig], 'root_id': 'root'}
  135. maybe_signature.return_value = sig
  136. retval, _ = self.trace(self.add, (2, 2), {}, request=request)
  137. sig.apply_async.assert_called_with(
  138. (4,), parent_id='id-1', root_id='root',
  139. )
  140. @patch('celery.canvas.maybe_signature')
  141. def test_chain_proto2(self, maybe_signature):
  142. sig = Mock(name='sig')
  143. sig2 = Mock(name='sig2')
  144. request = {'chain': [sig2, sig], 'root_id': 'root'}
  145. maybe_signature.return_value = sig
  146. retval, _ = self.trace(self.add, (2, 2), {}, request=request)
  147. sig.apply_async.assert_called_with(
  148. (4, ), parent_id='id-1', root_id='root',
  149. chain=[sig2],
  150. )
  151. @patch('celery.canvas.maybe_signature')
  152. def test_callbacks__EncodeError(self, maybe_signature):
  153. sig = Mock(name='sig')
  154. request = {'callbacks': [sig], 'root_id': 'root'}
  155. maybe_signature.return_value = sig
  156. sig.apply_async.side_effect = EncodeError()
  157. retval, einfo = self.trace(self.add, (2, 2), {}, request=request)
  158. assert einfo.state == states.FAILURE
  159. @patch('celery.canvas.maybe_signature')
  160. @patch('celery.app.trace.group.apply_async')
  161. def test_callbacks__sigs(self, group_, maybe_signature):
  162. sig1 = Mock(name='sig')
  163. sig2 = Mock(name='sig2')
  164. sig3 = group([Mock(name='g1'), Mock(name='g2')], app=self.app)
  165. sig3.apply_async = Mock(name='gapply')
  166. request = {'callbacks': [sig1, sig3, sig2], 'root_id': 'root'}
  167. def passt(s, *args, **kwargs):
  168. return s
  169. maybe_signature.side_effect = passt
  170. retval, _ = self.trace(self.add, (2, 2), {}, request=request)
  171. group_.assert_called_with(
  172. (4,), parent_id='id-1', root_id='root',
  173. )
  174. sig3.apply_async.assert_called_with(
  175. (4,), parent_id='id-1', root_id='root',
  176. )
  177. @patch('celery.canvas.maybe_signature')
  178. @patch('celery.app.trace.group.apply_async')
  179. def test_callbacks__only_groups(self, group_, maybe_signature):
  180. sig1 = group([Mock(name='g1'), Mock(name='g2')], app=self.app)
  181. sig2 = group([Mock(name='g3'), Mock(name='g4')], app=self.app)
  182. sig1.apply_async = Mock(name='gapply')
  183. sig2.apply_async = Mock(name='gapply')
  184. request = {'callbacks': [sig1, sig2], 'root_id': 'root'}
  185. def passt(s, *args, **kwargs):
  186. return s
  187. maybe_signature.side_effect = passt
  188. retval, _ = self.trace(self.add, (2, 2), {}, request=request)
  189. sig1.apply_async.assert_called_with(
  190. (4,), parent_id='id-1', root_id='root',
  191. )
  192. sig2.apply_async.assert_called_with(
  193. (4,), parent_id='id-1', root_id='root',
  194. )
  195. def test_trace_SystemExit(self):
  196. with pytest.raises(SystemExit):
  197. self.trace(self.raises, (SystemExit(),), {})
  198. def test_trace_Retry(self):
  199. exc = Retry('foo', 'bar')
  200. _, info = self.trace(self.raises, (exc,), {})
  201. assert info.state == states.RETRY
  202. assert info.retval is exc
  203. def test_trace_exception(self):
  204. exc = KeyError('foo')
  205. _, info = self.trace(self.raises, (exc,), {})
  206. assert info.state == states.FAILURE
  207. assert info.retval is exc
  208. def test_trace_task_ret__no_content_type(self):
  209. _trace_task_ret(
  210. self.add.name, 'id1', {}, ((2, 2), {}, {}), None, None,
  211. app=self.app,
  212. )
  213. def test_fast_trace_task__no_content_type(self):
  214. self.app.tasks[self.add.name].__trace__ = build_tracer(
  215. self.add.name, self.add, app=self.app,
  216. )
  217. _fast_trace_task(
  218. self.add.name, 'id1', {}, ((2, 2), {}, {}), None, None,
  219. app=self.app, _loc=[self.app.tasks, {}, 'hostname']
  220. )
  221. def test_trace_exception_propagate(self):
  222. with pytest.raises(KeyError):
  223. self.trace(self.raises, (KeyError('foo'),), {}, propagate=True)
  224. @patch('celery.app.trace.build_tracer')
  225. @patch('celery.app.trace.report_internal_error')
  226. def test_outside_body_error(self, report_internal_error, build_tracer):
  227. tracer = Mock()
  228. tracer.side_effect = KeyError('foo')
  229. build_tracer.return_value = tracer
  230. @self.app.task(shared=False)
  231. def xtask():
  232. pass
  233. trace_task(xtask, 'uuid', (), {})
  234. assert report_internal_error.call_count
  235. assert xtask.__trace__ is tracer
  236. class test_TraceInfo(TraceCase):
  237. class TI(TraceInfo):
  238. __slots__ = TraceInfo.__slots__ + ('__dict__',)
  239. def test_handle_error_state(self):
  240. x = self.TI(states.FAILURE)
  241. x.handle_failure = Mock()
  242. x.handle_error_state(self.add_cast, self.add_cast.request)
  243. x.handle_failure.assert_called_with(
  244. self.add_cast, self.add_cast.request,
  245. store_errors=self.add_cast.store_errors_even_if_ignored,
  246. call_errbacks=True,
  247. )
  248. @patch('celery.app.trace.ExceptionInfo')
  249. def test_handle_reject(self, ExceptionInfo):
  250. x = self.TI(states.FAILURE)
  251. x._log_error = Mock(name='log_error')
  252. req = Mock(name='req')
  253. x.handle_reject(self.add, req)
  254. x._log_error.assert_called_with(self.add, req, ExceptionInfo())
  255. class test_stackprotection:
  256. def test_stackprotection(self):
  257. setup_worker_optimizations(self.app)
  258. try:
  259. @self.app.task(shared=False, bind=True)
  260. def foo(self, i):
  261. if i:
  262. return foo(0)
  263. return self.request
  264. assert foo(1).called_directly
  265. finally:
  266. reset_worker_optimizations()