Debian Codegraph @

t/unit/app/test_amqp.py

raw
1 from datetime import datetime, timedelta, timezone
2 from unittest.mock import Mock, patch
3
4 import pytest
5 from kombu import Exchange, Queue
6
7 from celery import uuid
8 from celery.app.amqp import Queues, utf8dict
9 from celery.utils.time import to_utc
10
11
12 class test_TaskConsumer:
13
14 def test_accept_content(self, app):
15 with app.pool.acquire(block=True) as con:
16 app.conf.accept_content = ['application/json']
17 assert app.amqp.TaskConsumer(con).accept == {
18 'application/json',
19 }
20 assert app.amqp.TaskConsumer(con, accept=['json']).accept == {
21 'application/json',
22 }
23
24
25 class test_ProducerPool:
26
27 def test_setup_nolimit(self, app):
28 app.conf.broker_pool_limit = None
29 try:
30 delattr(app, '_pool')
31 except AttributeError:
32 pass
33 app.amqp._producer_pool = None
34 pool = app.amqp.producer_pool
35 assert pool.limit == app.pool.limit
36 assert not pool._resource.queue
37
38 r1 = pool.acquire()
39 r2 = pool.acquire()
40 r1.release()
41 r2.release()
42 r1 = pool.acquire()
43 r2 = pool.acquire()
44
45 def test_setup(self, app):
46 app.conf.broker_pool_limit = 2
47 try:
48 delattr(app, '_pool')
49 except AttributeError:
50 pass
51 app.amqp._producer_pool = None
52 pool = app.amqp.producer_pool
53 assert pool.limit == app.pool.limit
54 assert pool._resource.queue
55
56 p1 = r1 = pool.acquire()
57 p2 = r2 = pool.acquire()
58 r1.release()
59 r2.release()
60 r1 = pool.acquire()
61 r2 = pool.acquire()
62 assert p2 is r1
63 assert p1 is r2
64 r1.release()
65 r2.release()
66
67
68 class test_Queues:
69
70 def test_queues_format(self):
71 self.app.amqp.queues._consume_from = {}
72 assert self.app.amqp.queues.format() == ''
73
74 def test_with_defaults(self):
75 assert Queues(None) == {}
76
77 def test_add(self):
78 q = Queues()
79 q.add('foo', exchange='ex', routing_key='rk')
80 assert 'foo' in q
81 assert isinstance(q['foo'], Queue)
82 assert q['foo'].routing_key == 'rk'
83
84 def test_setitem_adds_default_exchange(self):
85 q = Queues(default_exchange=Exchange('bar'))
86 assert q.default_exchange
87 queue = Queue('foo', exchange=None)
88 queue.exchange = None
89 q['foo'] = queue
90 assert q['foo'].exchange == q.default_exchange
91
92 def test_select_add(self):
93 q = Queues()
94 q.select(['foo', 'bar'])
95 q.select_add('baz')
96 assert sorted(q._consume_from.keys()) == ['bar', 'baz', 'foo']
97
98 def test_deselect(self):
99 q = Queues()
100 q.select(['foo', 'bar'])
101 q.deselect('bar')
102 assert sorted(q._consume_from.keys()) == ['foo']
103
104 def test_add_default_exchange(self):
105 ex = Exchange('fff', 'fanout')
106 q = Queues(default_exchange=ex)
107 q.add(Queue('foo'))
108 assert q['foo'].exchange.name == 'fff'
109
110 def test_alias(self):
111 q = Queues()
112 q.add(Queue('foo', alias='barfoo'))
113 assert q['barfoo'] is q['foo']
114
115 @pytest.mark.parametrize('queues_kwargs,qname,q,expected', [
116 ({'max_priority': 10},
117 'foo', 'foo', {'x-max-priority': 10}),
118 ({'max_priority': 10},
119 'xyz', Queue('xyz', queue_arguments={'x-max-priority': 3}),
120 {'x-max-priority': 3}),
121 ({'max_priority': 10},
122 'moo', Queue('moo', queue_arguments=None),
123 {'x-max-priority': 10}),
124 ({'max_priority': None},
125 'foo2', 'foo2',
126 None),
127 ({'max_priority': None},
128 'xyx3', Queue('xyx3', queue_arguments={'x-max-priority': 7}),
129 {'x-max-priority': 7}),
130
131 ])
132 def test_with_max_priority(self, queues_kwargs, qname, q, expected):
133 queues = Queues(**queues_kwargs)
134 queues.add(q)
135 assert queues[qname].queue_arguments == expected
136
137 def test_missing_queue_quorum(self):
138 queues = Queues(create_missing_queue_type="quorum",
139 create_missing_queue_exchange_type="topic")
140
141 q = queues.new_missing("spontaneous")
142 assert q.name == "spontaneous"
143 assert q.queue_arguments == {"x-queue-type": "quorum"}
144 assert q.exchange.type == "topic"
145
146
147 class test_default_queues:
148
149 @pytest.mark.parametrize('default_queue_type', ['classic', 'quorum'])
150 @pytest.mark.parametrize('name,exchange,rkey', [
151 ('default', None, None),
152 ('default', 'exchange', None),
153 ('default', 'exchange', 'routing_key'),
154 ('default', None, 'routing_key'),
155 ])
156 def test_setting_default_queue(self, name, exchange, rkey, default_queue_type):
157 self.app.conf.task_queues = {}
158 self.app.conf.task_default_exchange = exchange
159 self.app.conf.task_default_routing_key = rkey
160 self.app.conf.task_default_queue = name
161 self.app.conf.task_default_queue_type = default_queue_type
162 assert self.app.amqp.queues.default_exchange.name == exchange or name
163 queues = dict(self.app.amqp.queues)
164 assert len(queues) == 1
165 queue = queues[name]
166 assert queue.exchange.name == exchange or name
167 assert queue.exchange.type == 'direct'
168 assert queue.routing_key == rkey or name
169
170 if default_queue_type == 'quorum':
171 assert queue.queue_arguments == {'x-queue-type': 'quorum'}
172 else:
173 assert queue.queue_arguments is None
174
175
176 class test_default_exchange:
177
178 @pytest.mark.parametrize('name,exchange,rkey', [
179 ('default', 'foo', None),
180 ('default', 'foo', 'routing_key'),
181 ])
182 def test_setting_default_exchange(self, name, exchange, rkey):
183 q = Queue(name, routing_key=rkey)
184 self.app.conf.task_queues = {q}
185 self.app.conf.task_default_exchange = exchange
186 queues = dict(self.app.amqp.queues)
187 queue = queues[name]
188 assert queue.exchange.name == exchange
189
190 @pytest.mark.parametrize('name,extype,rkey', [
191 ('default', 'direct', None),
192 ('default', 'direct', 'routing_key'),
193 ('default', 'topic', None),
194 ('default', 'topic', 'routing_key'),
195 ])
196 def test_setting_default_exchange_type(self, name, extype, rkey):
197 q = Queue(name, routing_key=rkey)
198 self.app.conf.task_queues = {q}
199 self.app.conf.task_default_exchange_type = extype
200 queues = dict(self.app.amqp.queues)
201 queue = queues[name]
202 assert queue.exchange.type == extype
203
204
205 class test_AMQP_proto1:
206
207 def test_kwargs_must_be_mapping(self):
208 with pytest.raises(TypeError):
209 self.app.amqp.as_task_v1(uuid(), 'foo', kwargs=[1, 2])
210
211 def test_args_must_be_list(self):
212 with pytest.raises(TypeError):
213 self.app.amqp.as_task_v1(uuid(), 'foo', args='abc')
214
215 def test_countdown_negative(self):
216 with pytest.raises(ValueError):
217 self.app.amqp.as_task_v1(uuid(), 'foo', countdown=-1232132323123)
218
219 def test_as_task_message_without_utc(self):
220 self.app.amqp.utc = False
221 self.app.amqp.as_task_v1(uuid(), 'foo', countdown=30, expires=40)
222
223
224 class test_AMQP_Base:
225 def setup_method(self):
226 self.simple_message = self.app.amqp.as_task_v2(
227 uuid(), 'foo', create_sent_event=True,
228 )
229 self.simple_message_no_sent_event = self.app.amqp.as_task_v2(
230 uuid(), 'foo', create_sent_event=False,
231 )
232
233
234 class test_AMQP(test_AMQP_Base):
235
236 def test_kwargs_must_be_mapping(self):
237 with pytest.raises(TypeError):
238 self.app.amqp.as_task_v2(uuid(), 'foo', kwargs=[1, 2])
239
240 def test_args_must_be_list(self):
241 with pytest.raises(TypeError):
242 self.app.amqp.as_task_v2(uuid(), 'foo', args='abc')
243
244 def test_countdown_negative(self):
245 with pytest.raises(ValueError):
246 self.app.amqp.as_task_v2(uuid(), 'foo', countdown=-1232132323123)
247
248 def test_Queues__with_max_priority(self):
249 x = self.app.amqp.Queues({}, max_priority=23)
250 assert x.max_priority == 23
251
252 def test_send_task_message__no_kwargs(self):
253 self.app.amqp.send_task_message(Mock(), 'foo', self.simple_message)
254
255 def test_send_task_message__properties(self):
256 prod = Mock(name='producer')
257 self.app.amqp.send_task_message(
258 prod, 'foo', self.simple_message_no_sent_event,
259 foo=1, retry=False,
260 )
261 assert prod.publish.call_args[1]['foo'] == 1
262
263 def test_send_task_message__headers(self):
264 prod = Mock(name='producer')
265 self.app.amqp.send_task_message(
266 prod, 'foo', self.simple_message_no_sent_event,
267 headers={'x1x': 'y2x'},
268 retry=False,
269 )
270 assert prod.publish.call_args[1]['headers']['x1x'] == 'y2x'
271
272 def test_send_task_message__queue_string(self):
273 prod = Mock(name='producer')
274 self.app.amqp.send_task_message(
275 prod, 'foo', self.simple_message_no_sent_event,
276 queue='foo', retry=False,
277 )
278 kwargs = prod.publish.call_args[1]
279 assert kwargs['routing_key'] == 'foo'
280 assert kwargs['exchange'] == ''
281
282 def test_send_task_message__broadcast_without_exchange(self):
283 from kombu.common import Broadcast
284 evd = Mock(name='evd')
285 self.app.amqp.send_task_message(
286 Mock(), 'foo', self.simple_message, retry=False,
287 routing_key='xyz', queue=Broadcast('abc'),
288 event_dispatcher=evd,
289 )
290 evd.publish.assert_called()
291 event = evd.publish.call_args[0][1]
292 assert event['routing_key'] == 'xyz'
293 assert event['exchange'] == 'abc'
294
295 def test_send_event_exchange_direct_with_exchange(self):
296 prod = Mock(name='prod')
297 self.app.amqp.send_task_message(
298 prod, 'foo', self.simple_message_no_sent_event, queue='bar',
299 retry=False, exchange_type='direct', exchange='xyz',
300 )
301 prod.publish.assert_called()
302 pub = prod.publish.call_args[1]
303 assert pub['routing_key'] == 'bar'
304 assert pub['exchange'] == ''
305
306 def test_send_event_exchange_direct_with_routing_key(self):
307 prod = Mock(name='prod')
308 self.app.amqp.send_task_message(
309 prod, 'foo', self.simple_message_no_sent_event, queue='bar',
310 retry=False, exchange_type='direct', routing_key='xyb',
311 )
312 prod.publish.assert_called()
313 pub = prod.publish.call_args[1]
314 assert pub['routing_key'] == 'bar'
315 assert pub['exchange'] == ''
316
317 def test_send_event_exchange_string(self):
318 evd = Mock(name='evd')
319 self.app.amqp.send_task_message(
320 Mock(), 'foo', self.simple_message, retry=False,
321 exchange='xyz', routing_key='xyb',
322 event_dispatcher=evd,
323 )
324 evd.publish.assert_called()
325 event = evd.publish.call_args[0][1]
326 assert event['routing_key'] == 'xyb'
327 assert event['exchange'] == 'xyz'
328
329 def test_send_task_message__with_delivery_mode(self):
330 prod = Mock(name='producer')
331 self.app.amqp.send_task_message(
332 prod, 'foo', self.simple_message_no_sent_event,
333 delivery_mode=33, retry=False,
334 )
335 assert prod.publish.call_args[1]['delivery_mode'] == 33
336
337 def test_send_task_message__with_timeout(self):
338 prod = Mock(name='producer')
339 self.app.amqp.send_task_message(
340 prod, 'foo', self.simple_message_no_sent_event,
341 timeout=1,
342 )
343 assert prod.publish.call_args[1]['timeout'] == 1
344
345 def test_send_task_message__with_confirm_timeout(self):
346 prod = Mock(name='producer')
347 self.app.amqp.send_task_message(
348 prod, 'foo', self.simple_message_no_sent_event,
349 confirm_timeout=1,
350 )
351 assert prod.publish.call_args[1]['confirm_timeout'] == 1
352
353 def test_send_task_message__with_receivers(self):
354 mocked_receiver = ((Mock(), Mock()), Mock())
355 with patch('celery.signals.task_sent.receivers', [mocked_receiver]):
356 self.app.amqp.send_task_message(Mock(), 'foo', self.simple_message)
357
358 def test_routes(self):
359 r1 = self.app.amqp.routes
360 r2 = self.app.amqp.routes
361 assert r1 is r2
362
363 def update_conf_runtime_for_tasks_queues(self):
364 self.app.conf.update(task_routes={'task.create_pr': 'queue.qwerty'})
365 self.app.send_task('task.create_pr')
366 router_was = self.app.amqp.router
367 self.app.conf.update(task_routes={'task.create_pr': 'queue.asdfgh'})
368 self.app.send_task('task.create_pr')
369 router = self.app.amqp.router
370 assert router != router_was
371
372 def test_create_missing_queue_type_from_conf(self):
373 self.app.conf.task_create_missing_queue_type = "quorum"
374 self.app.conf.task_create_missing_queue_exchange_type = "topic"
375 self.app.amqp.__dict__.pop("queues", None)
376 q = self.app.amqp.queues["auto"]
377 assert q.queue_arguments == {"x-queue-type": "quorum"}
378 assert q.exchange.type == "topic"
379
380 def test_create_missing_queue_type_explicit_param(self):
381 qmap = self.app.amqp.Queues({}, create_missing=True,
382 create_missing_queue_type="quorum",
383 create_missing_queue_exchange_type="topic")
384 q = qmap["auto"]
385 assert q.queue_arguments == {"x-queue-type": "quorum"}
386 assert q.exchange.type == "topic"
387
388
389 class test_as_task_v2(test_AMQP_Base):
390
391 def test_raises_if_args_is_not_tuple(self):
392 with pytest.raises(TypeError):
393 self.app.amqp.as_task_v2(uuid(), 'foo', args='123')
394
395 def test_raises_if_kwargs_is_not_mapping(self):
396 with pytest.raises(TypeError):
397 self.app.amqp.as_task_v2(uuid(), 'foo', kwargs=(1, 2, 3))
398
399 def test_countdown_to_eta(self):
400 now = to_utc(datetime.now(timezone.utc)).astimezone(self.app.timezone)
401 m = self.app.amqp.as_task_v2(
402 uuid(), 'foo', countdown=10, now=now,
403 )
404 assert m.headers['eta'] == (now + timedelta(seconds=10)).isoformat()
405
406 def test_expires_to_datetime(self):
407 now = to_utc(datetime.now(timezone.utc)).astimezone(self.app.timezone)
408 m = self.app.amqp.as_task_v2(
409 uuid(), 'foo', expires=30, now=now,
410 )
411 assert m.headers['expires'] == (
412 now + timedelta(seconds=30)).isoformat()
413
414 def test_eta_to_datetime(self):
415 eta = datetime.now(timezone.utc)
416 m = self.app.amqp.as_task_v2(
417 uuid(), 'foo', eta=eta,
418 )
419 assert m.headers['eta'] == eta.isoformat()
420
421 def test_compression(self):
422 self.app.conf.task_compression = 'gzip'
423
424 prod = Mock(name='producer')
425 self.app.amqp.send_task_message(
426 prod, 'foo', self.simple_message_no_sent_event,
427 compression=None
428 )
429 assert prod.publish.call_args[1]['compression'] == 'gzip'
430
431 def test_compression_override(self):
432 self.app.conf.task_compression = 'gzip'
433
434 prod = Mock(name='producer')
435 self.app.amqp.send_task_message(
436 prod, 'foo', self.simple_message_no_sent_event,
437 compression='bz2'
438 )
439 assert prod.publish.call_args[1]['compression'] == 'bz2'
440
441 def test_callbacks_errbacks_chord(self):
442 @self.app.task
443 def t(i):
444 pass
445
446 m = self.app.amqp.as_task_v2(
447 uuid(), 'foo',
448 callbacks=[t.s(1), t.s(2)],
449 errbacks=[t.s(3), t.s(4)],
450 chord=t.s(5),
451 )
452 _, _, embed = m.body
453 assert embed['callbacks'] == [utf8dict(t.s(1)), utf8dict(t.s(2))]
454 assert embed['errbacks'] == [utf8dict(t.s(3)), utf8dict(t.s(4))]
455 assert embed['chord'] == utf8dict(t.s(5))