test_strategy.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. from __future__ import absolute_import, unicode_literals
  2. import pytest
  3. from collections import defaultdict
  4. from contextlib import contextmanager
  5. from case import Mock, patch
  6. from kombu.utils.limits import TokenBucket
  7. from celery.exceptions import InvalidTaskError
  8. from celery.worker import state
  9. from celery.worker.strategy import proto1_to_proto2
  10. from celery.utils.time import rate
  11. class test_proto1_to_proto2:
  12. def setup(self):
  13. self.message = Mock(name='message')
  14. self.body = {
  15. 'args': (1,),
  16. 'kwargs': {'foo': 'baz'},
  17. 'utc': False,
  18. 'taskset': '123',
  19. }
  20. def test_message_without_args(self):
  21. self.body.pop('args')
  22. body, _, _, _ = proto1_to_proto2(self.message, self.body)
  23. assert body[:2] == ((), {'foo': 'baz'})
  24. def test_message_without_kwargs(self):
  25. self.body.pop('kwargs')
  26. body, _, _, _ = proto1_to_proto2(self.message, self.body)
  27. assert body[:2] == ((1,), {})
  28. def test_message_kwargs_not_mapping(self):
  29. self.body['kwargs'] = (2,)
  30. with pytest.raises(InvalidTaskError):
  31. proto1_to_proto2(self.message, self.body)
  32. def test_message_no_taskset_id(self):
  33. self.body.pop('taskset')
  34. assert proto1_to_proto2(self.message, self.body)
  35. def test_message(self):
  36. body, headers, decoded, utc = proto1_to_proto2(self.message, self.body)
  37. assert body == ((1,), {'foo': 'baz'}, {
  38. 'callbacks': None, 'errbacks': None, 'chord': None, 'chain': None,
  39. })
  40. assert headers == dict(self.body, group='123')
  41. assert decoded
  42. assert not utc
  43. class test_default_strategy_proto2:
  44. def setup(self):
  45. @self.app.task(shared=False)
  46. def add(x, y):
  47. return x + y
  48. self.add = add
  49. def get_message_class(self):
  50. return self.TaskMessage
  51. def prepare_message(self, message):
  52. return message
  53. class Context(object):
  54. def __init__(self, sig, s, reserved, consumer, message):
  55. self.sig = sig
  56. self.s = s
  57. self.reserved = reserved
  58. self.consumer = consumer
  59. self.message = message
  60. def __call__(self, callbacks=[], **kwargs):
  61. return self.s(
  62. self.message,
  63. (self.message.payload
  64. if not self.message.headers.get('id') else None),
  65. self.message.ack, self.message.reject, callbacks, **kwargs
  66. )
  67. def was_reserved(self):
  68. return self.reserved.called
  69. def was_rate_limited(self):
  70. assert not self.was_reserved()
  71. return self.consumer._limit_task.called
  72. def was_scheduled(self):
  73. assert not self.was_reserved()
  74. assert not self.was_rate_limited()
  75. return self.consumer.timer.call_at.called
  76. def event_sent(self):
  77. return self.consumer.event_dispatcher.send.call_args
  78. def get_request(self):
  79. if self.was_reserved():
  80. return self.reserved.call_args[0][0]
  81. if self.was_rate_limited():
  82. return self.consumer._limit_task.call_args[0][0]
  83. if self.was_scheduled():
  84. return self.consumer.timer.call_at.call_args[0][0]
  85. raise ValueError('request not handled')
  86. @contextmanager
  87. def _context(self, sig,
  88. rate_limits=True, events=True, utc=True, limit=None):
  89. assert sig.type.Strategy
  90. reserved = Mock()
  91. consumer = Mock()
  92. consumer.task_buckets = defaultdict(lambda: None)
  93. if limit:
  94. bucket = TokenBucket(rate(limit), capacity=1)
  95. consumer.task_buckets[sig.task] = bucket
  96. consumer.controller.state.revoked = set()
  97. consumer.disable_rate_limits = not rate_limits
  98. consumer.event_dispatcher.enabled = events
  99. s = sig.type.start_strategy(self.app, consumer, task_reserved=reserved)
  100. assert s
  101. message = self.task_message_from_sig(
  102. self.app, sig, utc=utc, TaskMessage=self.get_message_class(),
  103. )
  104. message = self.prepare_message(message)
  105. yield self.Context(sig, s, reserved, consumer, message)
  106. def test_when_logging_disabled(self):
  107. with patch('celery.worker.strategy.logger') as logger:
  108. logger.isEnabledFor.return_value = False
  109. with self._context(self.add.s(2, 2)) as C:
  110. C()
  111. logger.info.assert_not_called()
  112. def test_task_strategy(self):
  113. with self._context(self.add.s(2, 2)) as C:
  114. C()
  115. assert C.was_reserved()
  116. req = C.get_request()
  117. C.consumer.on_task_request.assert_called_with(req)
  118. assert C.event_sent()
  119. def test_callbacks(self):
  120. with self._context(self.add.s(2, 2)) as C:
  121. callbacks = [Mock(name='cb1'), Mock(name='cb2')]
  122. C(callbacks=callbacks)
  123. req = C.get_request()
  124. for callback in callbacks:
  125. callback.assert_called_with(req)
  126. def test_when_events_disabled(self):
  127. with self._context(self.add.s(2, 2), events=False) as C:
  128. C()
  129. assert C.was_reserved()
  130. assert not C.event_sent()
  131. def test_eta_task(self):
  132. with self._context(self.add.s(2, 2).set(countdown=10)) as C:
  133. C()
  134. assert C.was_scheduled()
  135. C.consumer.qos.increment_eventually.assert_called_with()
  136. def test_eta_task_utc_disabled(self):
  137. with self._context(self.add.s(2, 2).set(countdown=10), utc=False) as C:
  138. C()
  139. assert C.was_scheduled()
  140. C.consumer.qos.increment_eventually.assert_called_with()
  141. def test_when_rate_limited(self):
  142. task = self.add.s(2, 2)
  143. with self._context(task, rate_limits=True, limit='1/m') as C:
  144. C()
  145. assert C.was_rate_limited()
  146. def test_when_rate_limited__limits_disabled(self):
  147. task = self.add.s(2, 2)
  148. with self._context(task, rate_limits=False, limit='1/m') as C:
  149. C()
  150. assert C.was_reserved()
  151. def test_when_revoked(self):
  152. task = self.add.s(2, 2)
  153. task.freeze()
  154. try:
  155. with self._context(task) as C:
  156. C.consumer.controller.state.revoked.add(task.id)
  157. state.revoked.add(task.id)
  158. C()
  159. with pytest.raises(ValueError):
  160. C.get_request()
  161. finally:
  162. state.revoked.discard(task.id)
  163. class test_default_strategy_proto1(test_default_strategy_proto2):
  164. def get_message_class(self):
  165. return self.TaskMessage1
  166. class test_default_strategy_proto1__no_utc(test_default_strategy_proto2):
  167. def get_message_class(self):
  168. return self.TaskMessage1
  169. def prepare_message(self, message):
  170. message.payload['utc'] = False
  171. return message