test_loops.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. from __future__ import absolute_import
  2. import socket
  3. from mock import Mock
  4. from celery.exceptions import InvalidTaskError, SystemTerminate
  5. from celery.five import Empty
  6. from celery.worker import state
  7. from celery.worker.loops import asynloop, synloop, CLOSE, READ, WRITE, ERR
  8. from celery.tests.utils import AppCase, body_from_sig
  9. class X(object):
  10. def __init__(self, heartbeat=None, on_task=None):
  11. (
  12. self.obj,
  13. self.connection,
  14. self.consumer,
  15. self.strategies,
  16. self.blueprint,
  17. self.hub,
  18. self.qos,
  19. self.heartbeat,
  20. self.handle_unknown_message,
  21. self.handle_unknown_task,
  22. self.handle_invalid_task,
  23. self.clock,
  24. ) = self.args = [Mock(name='obj'),
  25. Mock(name='connection'),
  26. Mock(name='consumer'),
  27. {},
  28. Mock(name='blueprint'),
  29. Mock(name='Hub'),
  30. Mock(name='qos'),
  31. heartbeat,
  32. Mock(name='handle_unknown_message'),
  33. Mock(name='handle_unknown_task'),
  34. Mock(name='handle_invalid_task'),
  35. Mock(name='clock')]
  36. self.connection.supports_heartbeats = True
  37. self.consumer.callbacks = []
  38. self.connection.connection_errors = (socket.error, )
  39. #hent = self.Hub.__enter__ = Mock(name='Hub.__enter__')
  40. #self.Hub.__exit__ = Mock(name='Hub.__exit__')
  41. #self.hub = hent.return_value = Mock(name='hub_context')
  42. self.hub.on_task = on_task or []
  43. self.hub.readers = {}
  44. self.hub.writers = {}
  45. self.hub.fire_timers.return_value = 1.7
  46. self.Hub = self.hub
  47. def timeout_then_error(self, mock):
  48. def first(*args, **kwargs):
  49. mock.side_effect = socket.error()
  50. self.connection.more_to_read = False
  51. raise socket.timeout()
  52. mock.side_effect = first
  53. def close_then_error(self, mock):
  54. def first(*args, **kwargs):
  55. self.close()
  56. self.connection.more_to_read = False
  57. raise socket.error()
  58. mock.side_effect = first
  59. def close(self, *args, **kwargs):
  60. self.blueprint.state = CLOSE
  61. def closer(self, mock=None):
  62. mock = Mock() if mock is None else mock
  63. mock.side_effect = self.close
  64. return mock
  65. def get_task_callback(*args, **kwargs):
  66. x = X(*args, **kwargs)
  67. x.blueprint.state = CLOSE
  68. asynloop(*x.args)
  69. return x, x.consumer.callbacks[0]
  70. class test_asynloop(AppCase):
  71. def setup(self):
  72. @self.app.task()
  73. def add(x, y):
  74. return x + y
  75. self.add = add
  76. def test_setup_heartbeat(self):
  77. x = X(heartbeat=10)
  78. x.blueprint.state = CLOSE
  79. asynloop(*x.args)
  80. x.consumer.consume.assert_called_with()
  81. x.obj.on_ready.assert_called_with()
  82. x.hub.timer.apply_interval.assert_called_with(
  83. 10 * 1000.0 / 2.0, x.connection.heartbeat_check, (2.0, ),
  84. )
  85. def task_context(self, sig, **kwargs):
  86. x, on_task = get_task_callback(**kwargs)
  87. body = body_from_sig(self.app, sig)
  88. message = Mock()
  89. strategy = x.strategies[sig.task] = Mock()
  90. return x, on_task, body, message, strategy
  91. def test_on_task_received(self):
  92. _, on_task, body, msg, strategy = self.task_context(self.add.s(2, 2))
  93. on_task(body, msg)
  94. strategy.assert_called_with(msg, body, msg.ack_log_error)
  95. def test_on_task_received_executes_hub_on_task(self):
  96. cbs = [Mock(), Mock(), Mock()]
  97. _, on_task, body, msg, _ = self.task_context(
  98. self.add.s(2, 2), on_task=cbs,
  99. )
  100. on_task(body, msg)
  101. [cb.assert_called_with() for cb in cbs]
  102. def test_on_task_message_missing_name(self):
  103. x, on_task, body, msg, strategy = self.task_context(self.add.s(2, 2))
  104. body.pop('task')
  105. on_task(body, msg)
  106. x.handle_unknown_message.assert_called_with(body, msg)
  107. def test_on_task_not_registered(self):
  108. x, on_task, body, msg, strategy = self.task_context(self.add.s(2, 2))
  109. exc = strategy.side_effect = KeyError(self.add.name)
  110. on_task(body, msg)
  111. x.handle_unknown_task.assert_called_with(body, msg, exc)
  112. def test_on_task_InvalidTaskError(self):
  113. x, on_task, body, msg, strategy = self.task_context(self.add.s(2, 2))
  114. exc = strategy.side_effect = InvalidTaskError()
  115. on_task(body, msg)
  116. x.handle_invalid_task.assert_called_with(body, msg, exc)
  117. def test_should_terminate(self):
  118. x = X()
  119. # XXX why aren't the errors propagated?!?
  120. state.should_terminate = True
  121. try:
  122. with self.assertRaises(SystemTerminate):
  123. asynloop(*x.args)
  124. finally:
  125. state.should_terminate = False
  126. def test_should_terminate_hub_close_raises(self):
  127. x = X()
  128. # XXX why aren't the errors propagated?!?
  129. state.should_terminate = True
  130. x.hub.close.side_effect = MemoryError()
  131. try:
  132. with self.assertRaises(SystemTerminate):
  133. asynloop(*x.args)
  134. finally:
  135. state.should_terminate = False
  136. def test_should_stop(self):
  137. x = X()
  138. state.should_stop = True
  139. try:
  140. with self.assertRaises(SystemExit):
  141. asynloop(*x.args)
  142. finally:
  143. state.should_stop = False
  144. def test_updates_qos(self):
  145. x = X()
  146. x.qos.prev = 3
  147. x.qos.value = 3
  148. asynloop(*x.args, sleep=x.closer())
  149. self.assertFalse(x.qos.update.called)
  150. x = X()
  151. x.qos.prev = 1
  152. x.qos.value = 6
  153. asynloop(*x.args, sleep=x.closer())
  154. x.qos.update.assert_called_with()
  155. x.hub.fire_timers.assert_called_with(propagate=(socket.error, ))
  156. x.connection.transport.on_poll_start.assert_called_with()
  157. def test_poll_empty(self):
  158. x = X()
  159. x.hub.readers = {6: Mock()}
  160. x.close_then_error(x.connection.drain_nowait)
  161. x.hub.fire_timers.return_value = 33.37
  162. x.hub.poller.poll.return_value = []
  163. with self.assertRaises(socket.error):
  164. asynloop(*x.args)
  165. x.hub.poller.poll.assert_called_with(33.37)
  166. x.connection.transport.on_poll_empty.assert_called_with()
  167. def test_poll_readable(self):
  168. x = X()
  169. x.hub.readers = {6: Mock()}
  170. x.close_then_error(x.connection.drain_nowait)
  171. x.hub.poller.poll.return_value = [(6, READ)]
  172. with self.assertRaises(socket.error):
  173. asynloop(*x.args)
  174. x.hub.readers[6].assert_called_with(6, READ)
  175. self.assertTrue(x.hub.poller.poll.called)
  176. def test_poll_readable_raises_Empty(self):
  177. x = X()
  178. x.hub.readers = {6: Mock()}
  179. x.close_then_error(x.connection.drain_nowait)
  180. x.hub.poller.poll.return_value = [(6, READ)]
  181. x.hub.readers[6].side_effect = Empty()
  182. with self.assertRaises(socket.error):
  183. asynloop(*x.args)
  184. x.hub.readers[6].assert_called_with(6, READ)
  185. self.assertTrue(x.hub.poller.poll.called)
  186. def test_poll_writable(self):
  187. x = X()
  188. x.hub.writers = {6: Mock()}
  189. x.close_then_error(x.connection.drain_nowait)
  190. x.hub.poller.poll.return_value = [(6, WRITE)]
  191. with self.assertRaises(socket.error):
  192. asynloop(*x.args)
  193. x.hub.writers[6].assert_called_with(6, WRITE)
  194. self.assertTrue(x.hub.poller.poll.called)
  195. def test_poll_writable_none_registered(self):
  196. x = X()
  197. x.hub.writers = {6: Mock()}
  198. x.close_then_error(x.connection.drain_nowait)
  199. x.hub.poller.poll.return_value = [(7, WRITE)]
  200. with self.assertRaises(socket.error):
  201. asynloop(*x.args)
  202. self.assertTrue(x.hub.poller.poll.called)
  203. def test_poll_unknown_event(self):
  204. x = X()
  205. x.hub.writers = {6: Mock()}
  206. x.close_then_error(x.connection.drain_nowait)
  207. x.hub.poller.poll.return_value = [(6, 0)]
  208. with self.assertRaises(socket.error):
  209. asynloop(*x.args)
  210. self.assertTrue(x.hub.poller.poll.called)
  211. def test_poll_keep_draining_disabled(self):
  212. x = X()
  213. x.hub.writers = {6: Mock()}
  214. poll = x.hub.poller.poll
  215. def se(*args, **kwargs):
  216. poll.side_effect = socket.error()
  217. poll.side_effect = se
  218. x.connection.transport.nb_keep_draining = False
  219. x.close_then_error(x.connection.drain_nowait)
  220. x.hub.poller.poll.return_value = [(6, 0)]
  221. with self.assertRaises(socket.error):
  222. asynloop(*x.args)
  223. self.assertTrue(x.hub.poller.poll.called)
  224. self.assertFalse(x.connection.drain_nowait.called)
  225. def test_poll_err_writable(self):
  226. x = X()
  227. x.hub.writers = {6: Mock()}
  228. x.close_then_error(x.connection.drain_nowait)
  229. x.hub.poller.poll.return_value = [(6, ERR)]
  230. with self.assertRaises(socket.error):
  231. asynloop(*x.args)
  232. x.hub.writers[6].assert_called_with(6, ERR)
  233. self.assertTrue(x.hub.poller.poll.called)
  234. def test_poll_write_generator(self):
  235. x = X()
  236. def Gen():
  237. yield 1
  238. yield 2
  239. gen = Gen()
  240. x.hub.writers = {6: gen}
  241. x.close_then_error(x.connection.drain_nowait)
  242. x.hub.poller.poll.return_value = [(6, WRITE)]
  243. with self.assertRaises(socket.error):
  244. asynloop(*x.args)
  245. self.assertTrue(gen.gi_frame.f_lasti != -1)
  246. self.assertFalse(x.hub.remove.called)
  247. def test_poll_write_generator_stopped(self):
  248. x = X()
  249. def Gen():
  250. raise StopIteration()
  251. yield
  252. gen = Gen()
  253. x.hub.writers = {6: gen}
  254. x.close_then_error(x.connection.drain_nowait)
  255. x.hub.poller.poll.return_value = [(6, WRITE)]
  256. with self.assertRaises(socket.error):
  257. asynloop(*x.args)
  258. self.assertIsNone(gen.gi_frame)
  259. x.hub.remove.assert_called_with(6)
  260. def test_poll_write_generator_raises(self):
  261. x = X()
  262. def Gen():
  263. raise ValueError('foo')
  264. yield
  265. gen = Gen()
  266. x.hub.writers = {6: gen}
  267. x.close_then_error(x.connection.drain_nowait)
  268. x.hub.poller.poll.return_value = [(6, WRITE)]
  269. with self.assertRaises(ValueError):
  270. asynloop(*x.args)
  271. self.assertIsNone(gen.gi_frame)
  272. x.hub.remove.assert_called_with(6)
  273. def test_poll_err_readable(self):
  274. x = X()
  275. x.hub.readers = {6: Mock()}
  276. x.close_then_error(x.connection.drain_nowait)
  277. x.hub.poller.poll.return_value = [(6, ERR)]
  278. with self.assertRaises(socket.error):
  279. asynloop(*x.args)
  280. x.hub.readers[6].assert_called_with(6, ERR)
  281. self.assertTrue(x.hub.poller.poll.called)
  282. def test_poll_raises_ValueError(self):
  283. x = X()
  284. x.hub.readers = {6: Mock()}
  285. x.close_then_error(x.connection.drain_nowait)
  286. x.hub.poller.poll.side_effect = ValueError()
  287. asynloop(*x.args)
  288. self.assertTrue(x.hub.poller.poll.called)
  289. class test_synloop(AppCase):
  290. def test_timeout_ignored(self):
  291. x = X()
  292. x.timeout_then_error(x.connection.drain_events)
  293. with self.assertRaises(socket.error):
  294. synloop(*x.args)
  295. self.assertEqual(x.connection.drain_events.call_count, 2)
  296. def test_updates_qos_when_changed(self):
  297. x = X()
  298. x.qos.prev = 2
  299. x.qos.value = 2
  300. x.timeout_then_error(x.connection.drain_events)
  301. with self.assertRaises(socket.error):
  302. synloop(*x.args)
  303. self.assertFalse(x.qos.update.called)
  304. x.qos.value = 4
  305. x.timeout_then_error(x.connection.drain_events)
  306. with self.assertRaises(socket.error):
  307. synloop(*x.args)
  308. x.qos.update.assert_called_with()
  309. def test_ignores_socket_errors_when_closed(self):
  310. x = X()
  311. x.close_then_error(x.connection.drain_events)
  312. self.assertIsNone(synloop(*x.args))