test_amqp.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. from __future__ import absolute_import, unicode_literals
  2. import pytest
  3. from datetime import datetime, timedelta
  4. from case import Mock
  5. from kombu import Exchange, Queue
  6. from celery import uuid
  7. from celery.app.amqp import Queues, utf8dict
  8. from celery.five import keys
  9. from celery.utils.time import to_utc
  10. class test_TaskConsumer:
  11. def test_accept_content(self, app):
  12. with app.pool.acquire(block=True) as con:
  13. app.conf.accept_content = ['application/json']
  14. assert app.amqp.TaskConsumer(con).accept == {
  15. 'application/json',
  16. }
  17. assert app.amqp.TaskConsumer(con, accept=['json']).accept == {
  18. 'application/json',
  19. }
  20. class test_ProducerPool:
  21. def test_setup_nolimit(self, app):
  22. app.conf.broker_pool_limit = None
  23. try:
  24. delattr(app, '_pool')
  25. except AttributeError:
  26. pass
  27. app.amqp._producer_pool = None
  28. pool = app.amqp.producer_pool
  29. assert pool.limit == app.pool.limit
  30. assert not pool._resource.queue
  31. r1 = pool.acquire()
  32. r2 = pool.acquire()
  33. r1.release()
  34. r2.release()
  35. r1 = pool.acquire()
  36. r2 = pool.acquire()
  37. def test_setup(self, app):
  38. app.conf.broker_pool_limit = 2
  39. try:
  40. delattr(app, '_pool')
  41. except AttributeError:
  42. pass
  43. app.amqp._producer_pool = None
  44. pool = app.amqp.producer_pool
  45. assert pool.limit == app.pool.limit
  46. assert pool._resource.queue
  47. p1 = r1 = pool.acquire()
  48. p2 = r2 = pool.acquire()
  49. r1.release()
  50. r2.release()
  51. r1 = pool.acquire()
  52. r2 = pool.acquire()
  53. assert p2 is r1
  54. assert p1 is r2
  55. r1.release()
  56. r2.release()
  57. class test_Queues:
  58. def test_queues_format(self):
  59. self.app.amqp.queues._consume_from = {}
  60. assert self.app.amqp.queues.format() == ''
  61. def test_with_defaults(self):
  62. assert Queues(None) == {}
  63. def test_add(self):
  64. q = Queues()
  65. q.add('foo', exchange='ex', routing_key='rk')
  66. assert 'foo' in q
  67. assert isinstance(q['foo'], Queue)
  68. assert q['foo'].routing_key == 'rk'
  69. def test_setitem_adds_default_exchange(self):
  70. q = Queues(default_exchange=Exchange('bar'))
  71. assert q.default_exchange
  72. queue = Queue('foo', exchange=None)
  73. queue.exchange = None
  74. q['foo'] = queue
  75. assert q['foo'].exchange == q.default_exchange
  76. @pytest.mark.parametrize('ha_policy,qname,q,qargs,expected', [
  77. (None, 'xyz', 'xyz', None, None),
  78. (None, 'xyz', 'xyz', {'x-foo': 'bar'}, {'x-foo': 'bar'}),
  79. ('all', 'foo', Queue('foo'), None, {'x-ha-policy': 'all'}),
  80. ('all', 'xyx2',
  81. Queue('xyx2', queue_arguments={'x-foo': 'bari'}),
  82. None,
  83. {'x-ha-policy': 'all', 'x-foo': 'bari'}),
  84. (['A', 'B', 'C'], 'foo', Queue('foo'), None, {
  85. 'x-ha-policy': 'nodes',
  86. 'x-ha-policy-params': ['A', 'B', 'C']}),
  87. ])
  88. def test_with_ha_policy(self, ha_policy, qname, q, qargs, expected):
  89. queues = Queues(ha_policy=ha_policy, create_missing=False)
  90. queues.add(q, queue_arguments=qargs)
  91. assert queues[qname].queue_arguments == expected
  92. def test_select_add(self):
  93. q = Queues()
  94. q.select(['foo', 'bar'])
  95. q.select_add('baz')
  96. assert sorted(keys(q._consume_from)) == ['bar', 'baz', 'foo']
  97. def test_deselect(self):
  98. q = Queues()
  99. q.select(['foo', 'bar'])
  100. q.deselect('bar')
  101. assert sorted(keys(q._consume_from)) == ['foo']
  102. def test_with_ha_policy_compat(self):
  103. q = Queues(ha_policy='all')
  104. q.add('bar')
  105. assert q['bar'].queue_arguments == {'x-ha-policy': 'all'}
  106. def test_add_default_exchange(self):
  107. ex = Exchange('fff', 'fanout')
  108. q = Queues(default_exchange=ex)
  109. q.add(Queue('foo'))
  110. assert q['foo'].exchange.name == 'fff'
  111. def test_alias(self):
  112. q = Queues()
  113. q.add(Queue('foo', alias='barfoo'))
  114. assert q['barfoo'] is q['foo']
  115. @pytest.mark.parametrize('queues_kwargs,qname,q,expected', [
  116. (dict(max_priority=10),
  117. 'foo', 'foo', {'x-max-priority': 10}),
  118. (dict(max_priority=10),
  119. 'xyz', Queue('xyz', queue_arguments={'x-max-priority': 3}),
  120. {'x-max-priority': 3}),
  121. (dict(max_priority=10),
  122. 'moo', Queue('moo', queue_arguments=None),
  123. {'x-max-priority': 10}),
  124. (dict(ha_policy='all', max_priority=5),
  125. 'bar', 'bar',
  126. {'x-ha-policy': 'all', 'x-max-priority': 5}),
  127. (dict(ha_policy='all', max_priority=5),
  128. 'xyx2', Queue('xyx2', queue_arguments={'x-max-priority': 2}),
  129. {'x-ha-policy': 'all', 'x-max-priority': 2}),
  130. (dict(max_priority=None),
  131. 'foo2', 'foo2',
  132. None),
  133. (dict(max_priority=None),
  134. 'xyx3', Queue('xyx3', queue_arguments={'x-max-priority': 7}),
  135. {'x-max-priority': 7}),
  136. ])
  137. def test_with_max_priority(self, queues_kwargs, qname, q, expected):
  138. queues = Queues(**queues_kwargs)
  139. queues.add(q)
  140. assert queues[qname].queue_arguments == expected
  141. class test_default_queues:
  142. @pytest.mark.parametrize('name,exchange,rkey', [
  143. ('default', None, None),
  144. ('default', 'exchange', None),
  145. ('default', 'exchange', 'routing_key'),
  146. ('default', None, 'routing_key'),
  147. ])
  148. def test_setting_default_queue(self, name, exchange, rkey):
  149. self.app.conf.task_queues = {}
  150. self.app.conf.task_default_exchange = exchange
  151. self.app.conf.task_default_routing_key = rkey
  152. self.app.conf.task_default_queue = name
  153. assert self.app.amqp.queues.default_exchange.name == exchange or name
  154. queues = dict(self.app.amqp.queues)
  155. assert len(queues) == 1
  156. queue = queues[name]
  157. assert queue.exchange.name == exchange or name
  158. assert queue.exchange.type == 'direct'
  159. assert queue.routing_key == rkey or name
  160. class test_AMQP_proto1:
  161. def test_kwargs_must_be_mapping(self):
  162. with pytest.raises(TypeError):
  163. self.app.amqp.as_task_v1(uuid(), 'foo', kwargs=[1, 2])
  164. def test_args_must_be_list(self):
  165. with pytest.raises(TypeError):
  166. self.app.amqp.as_task_v1(uuid(), 'foo', args='abc')
  167. def test_countdown_negative(self):
  168. with pytest.raises(ValueError):
  169. self.app.amqp.as_task_v1(uuid(), 'foo', countdown=-1232132323123)
  170. def test_as_task_message_without_utc(self):
  171. self.app.amqp.utc = False
  172. self.app.amqp.as_task_v1(uuid(), 'foo', countdown=30, expires=40)
  173. class test_AMQP:
  174. def setup(self):
  175. self.simple_message = self.app.amqp.as_task_v2(
  176. uuid(), 'foo', create_sent_event=True,
  177. )
  178. self.simple_message_no_sent_event = self.app.amqp.as_task_v2(
  179. uuid(), 'foo', create_sent_event=False,
  180. )
  181. def test_kwargs_must_be_mapping(self):
  182. with pytest.raises(TypeError):
  183. self.app.amqp.as_task_v2(uuid(), 'foo', kwargs=[1, 2])
  184. def test_args_must_be_list(self):
  185. with pytest.raises(TypeError):
  186. self.app.amqp.as_task_v2(uuid(), 'foo', args='abc')
  187. def test_countdown_negative(self):
  188. with pytest.raises(ValueError):
  189. self.app.amqp.as_task_v2(uuid(), 'foo', countdown=-1232132323123)
  190. def test_Queues__with_ha_policy(self):
  191. x = self.app.amqp.Queues({}, ha_policy='all')
  192. assert x.ha_policy == 'all'
  193. def test_Queues__with_max_priority(self):
  194. x = self.app.amqp.Queues({}, max_priority=23)
  195. assert x.max_priority == 23
  196. def test_send_task_message__no_kwargs(self):
  197. self.app.amqp.send_task_message(Mock(), 'foo', self.simple_message)
  198. def test_send_task_message__properties(self):
  199. prod = Mock(name='producer')
  200. self.app.amqp.send_task_message(
  201. prod, 'foo', self.simple_message_no_sent_event,
  202. foo=1, retry=False,
  203. )
  204. assert prod.publish.call_args[1]['foo'] == 1
  205. def test_send_task_message__headers(self):
  206. prod = Mock(name='producer')
  207. self.app.amqp.send_task_message(
  208. prod, 'foo', self.simple_message_no_sent_event,
  209. headers={'x1x': 'y2x'},
  210. retry=False,
  211. )
  212. assert prod.publish.call_args[1]['headers']['x1x'] == 'y2x'
  213. def test_send_task_message__queue_string(self):
  214. prod = Mock(name='producer')
  215. self.app.amqp.send_task_message(
  216. prod, 'foo', self.simple_message_no_sent_event,
  217. queue='foo', retry=False,
  218. )
  219. kwargs = prod.publish.call_args[1]
  220. assert kwargs['routing_key'] == 'foo'
  221. assert kwargs['exchange'] == ''
  222. def test_send_event_exchange_string(self):
  223. evd = Mock(name='evd')
  224. self.app.amqp.send_task_message(
  225. Mock(), 'foo', self.simple_message, retry=False,
  226. exchange='xyz', routing_key='xyb',
  227. event_dispatcher=evd,
  228. )
  229. evd.publish.assert_called()
  230. event = evd.publish.call_args[0][1]
  231. assert event['routing_key'] == 'xyb'
  232. assert event['exchange'] == 'xyz'
  233. def test_send_task_message__with_delivery_mode(self):
  234. prod = Mock(name='producer')
  235. self.app.amqp.send_task_message(
  236. prod, 'foo', self.simple_message_no_sent_event,
  237. delivery_mode=33, retry=False,
  238. )
  239. assert prod.publish.call_args[1]['delivery_mode'] == 33
  240. def test_send_task_message__with_receivers(self):
  241. from case import patch
  242. mocked_receiver = ((Mock(), Mock()), Mock())
  243. with patch('celery.signals.task_sent.receivers', [mocked_receiver]):
  244. self.app.amqp.send_task_message(Mock(), 'foo', self.simple_message)
  245. def test_routes(self):
  246. r1 = self.app.amqp.routes
  247. r2 = self.app.amqp.routes
  248. assert r1 is r2
  249. class test_as_task_v2:
  250. def test_raises_if_args_is_not_tuple(self):
  251. with pytest.raises(TypeError):
  252. self.app.amqp.as_task_v2(uuid(), 'foo', args='123')
  253. def test_raises_if_kwargs_is_not_mapping(self):
  254. with pytest.raises(TypeError):
  255. self.app.amqp.as_task_v2(uuid(), 'foo', kwargs=(1, 2, 3))
  256. def test_countdown_to_eta(self):
  257. now = to_utc(datetime.utcnow()).astimezone(self.app.timezone)
  258. m = self.app.amqp.as_task_v2(
  259. uuid(), 'foo', countdown=10, now=now,
  260. )
  261. assert m.headers['eta'] == (now + timedelta(seconds=10)).isoformat()
  262. def test_expires_to_datetime(self):
  263. now = to_utc(datetime.utcnow()).astimezone(self.app.timezone)
  264. m = self.app.amqp.as_task_v2(
  265. uuid(), 'foo', expires=30, now=now,
  266. )
  267. assert m.headers['expires'] == (
  268. now + timedelta(seconds=30)).isoformat()
  269. def test_callbacks_errbacks_chord(self):
  270. @self.app.task
  271. def t(i):
  272. pass
  273. m = self.app.amqp.as_task_v2(
  274. uuid(), 'foo',
  275. callbacks=[t.s(1), t.s(2)],
  276. errbacks=[t.s(3), t.s(4)],
  277. chord=t.s(5),
  278. )
  279. _, _, embed = m.body
  280. assert embed['callbacks'] == [utf8dict(t.s(1)), utf8dict(t.s(2))]
  281. assert embed['errbacks'] == [utf8dict(t.s(3)), utf8dict(t.s(4))]
  282. assert embed['chord'] == utf8dict(t.s(5))