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