Debian Codegraph @

t/unit/contrib/test_migrate.py

raw
1 from contextlib import contextmanager
2 from unittest.mock import Mock, patch
3
4 import pytest
5 from amqp import ChannelError
6 from kombu import Connection, Exchange, Producer, Queue
7 from kombu.transport.virtual import QoS
8 from kombu.utils.encoding import ensure_bytes
9
10 from celery.contrib.migrate import (State, StopFiltering, _maybe_queue, expand_dest, filter_callback, filter_status,
11 migrate_task, migrate_tasks, move, move_by_idmap, move_by_taskmap,
12 move_task_by_id, start_filter, task_id_eq, task_id_in)
13 from t.unit import conftest
14
15 # hack to ignore error at shutdown
16 QoS.restore_at_shutdown = False
17
18
19 def Message(body, exchange='exchange', routing_key='rkey',
20 compression=None, content_type='application/json',
21 content_encoding='utf-8'):
22 return Mock(
23 body=body,
24 delivery_info={
25 'exchange': exchange,
26 'routing_key': routing_key,
27 },
28 headers={
29 'compression': compression,
30 },
31 content_type=content_type,
32 content_encoding=content_encoding,
33 properties={
34 'correlation_id': isinstance(body, dict) and body['id'] or None
35 }
36 )
37
38
39 class test_State:
40
41 def test_strtotal(self):
42 x = State()
43 assert x.strtotal == '?'
44 x.total_apx = 100
45 assert x.strtotal == '100'
46
47 def test_repr(self):
48 x = State()
49 assert repr(x)
50 x.filtered = 'foo'
51 assert repr(x)
52
53
54 class test_move:
55
56 @contextmanager
57 def move_context(self, **kwargs):
58 with patch('celery.contrib.migrate.start_filter') as start:
59 with patch('celery.contrib.migrate.republish') as republish:
60 pred = Mock(name='predicate')
61 move(pred, app=self.app,
62 connection=self.app.connection(), **kwargs)
63 start.assert_called()
64 callback = start.call_args[0][2]
65 yield callback, pred, republish
66
67 def msgpair(self, **kwargs):
68 body = dict({'task': 'add', 'id': 'id'}, **kwargs)
69 return body, Message(body)
70
71 def test_move(self):
72 with self.move_context() as (callback, pred, republish):
73 pred.return_value = None
74 body, message = self.msgpair()
75 callback(body, message)
76 message.ack.assert_not_called()
77 republish.assert_not_called()
78
79 pred.return_value = 'foo'
80 callback(body, message)
81 message.ack.assert_called_with()
82 republish.assert_called()
83
84 def test_move_transform(self):
85 trans = Mock(name='transform')
86 trans.return_value = Queue('bar')
87 with self.move_context(transform=trans) as (callback, pred, republish):
88 pred.return_value = 'foo'
89 body, message = self.msgpair()
90 with patch('celery.contrib.migrate.maybe_declare') as maybed:
91 callback(body, message)
92 trans.assert_called_with('foo')
93 maybed.assert_called()
94 republish.assert_called()
95
96 def test_limit(self):
97 with self.move_context(limit=1) as (callback, pred, republish):
98 pred.return_value = 'foo'
99 body, message = self.msgpair()
100 with pytest.raises(StopFiltering):
101 callback(body, message)
102 republish.assert_called()
103
104 def test_callback(self):
105 cb = Mock()
106 with self.move_context(callback=cb) as (callback, pred, republish):
107 pred.return_value = 'foo'
108 body, message = self.msgpair()
109 callback(body, message)
110 republish.assert_called()
111 cb.assert_called()
112
113
114 class test_start_filter:
115
116 def test_start(self):
117 with patch('celery.contrib.migrate.eventloop') as evloop:
118 app = Mock()
119 filt = Mock(name='filter')
120 conn = Connection('memory://')
121 evloop.side_effect = StopFiltering()
122 app.amqp.queues = {'foo': Queue('foo'), 'bar': Queue('bar')}
123 consumer = app.amqp.TaskConsumer.return_value = Mock(name='consum')
124 consumer.queues = list(app.amqp.queues.values())
125 consumer.channel = conn.default_channel
126 consumer.__enter__ = Mock(name='consumer.__enter__')
127 consumer.__exit__ = Mock(name='consumer.__exit__')
128 consumer.callbacks = []
129
130 def register_callback(x):
131 consumer.callbacks.append(x)
132 consumer.register_callback = register_callback
133
134 start_filter(app, conn, filt,
135 queues='foo,bar', ack_messages=True)
136 body = {'task': 'add', 'id': 'id'}
137 for callback in consumer.callbacks:
138 callback(body, Message(body))
139 consumer.callbacks[:] = []
140 cb = Mock(name='callback=')
141 start_filter(app, conn, filt, tasks='add,mul', callback=cb)
142 for callback in consumer.callbacks:
143 callback(body, Message(body))
144 cb.assert_called()
145
146 on_declare_queue = Mock()
147 start_filter(app, conn, filt, tasks='add,mul', queues='foo',
148 on_declare_queue=on_declare_queue)
149 on_declare_queue.assert_called()
150 start_filter(app, conn, filt, queues=['foo', 'bar'])
151 consumer.callbacks[:] = []
152 state = State()
153 start_filter(app, conn, filt,
154 tasks='add,mul', callback=cb, state=state, limit=1)
155 stop_filtering_raised = False
156 for callback in consumer.callbacks:
157 try:
158 callback(body, Message(body))
159 except StopFiltering:
160 stop_filtering_raised = True
161 assert state.count
162 assert stop_filtering_raised
163
164
165 class test_filter_callback:
166
167 def test_filter(self):
168 callback = Mock()
169 filt = filter_callback(callback, ['add', 'mul'])
170 t1 = {'task': 'add'}
171 t2 = {'task': 'div'}
172
173 message = Mock()
174 filt(t2, message)
175 callback.assert_not_called()
176 filt(t1, message)
177 callback.assert_called_with(t1, message)
178
179
180 def test_task_id_in():
181 assert task_id_in(['A'], {'id': 'A'}, Mock())
182 assert not task_id_in(['A'], {'id': 'B'}, Mock())
183
184
185 def test_task_id_eq():
186 assert task_id_eq('A', {'id': 'A'}, Mock())
187 assert not task_id_eq('A', {'id': 'B'}, Mock())
188
189
190 def test_expand_dest():
191 assert expand_dest(None, 'foo', 'bar') == ('foo', 'bar')
192 assert expand_dest(('b', 'x'), 'foo', 'bar') == ('b', 'x')
193
194
195 def test_maybe_queue():
196 app = Mock()
197 app.amqp.queues = {'foo': 313}
198 assert _maybe_queue(app, 'foo') == 313
199 assert _maybe_queue(app, Queue('foo')) == Queue('foo')
200
201
202 def test_filter_status():
203 with conftest.stdouts() as (stdout, stderr):
204 filter_status(State(), {'id': '1', 'task': 'add'}, Mock())
205 assert stdout.getvalue()
206
207
208 def test_move_by_taskmap():
209 with patch('celery.contrib.migrate.move') as move:
210 move_by_taskmap({'add': Queue('foo')})
211 move.assert_called()
212 cb = move.call_args[0][0]
213 assert cb({'task': 'add'}, Mock())
214
215
216 def test_move_by_idmap():
217 with patch('celery.contrib.migrate.move') as move:
218 move_by_idmap({'123f': Queue('foo')})
219 move.assert_called()
220 cb = move.call_args[0][0]
221 body = {'id': '123f'}
222 assert cb(body, Message(body))
223
224
225 def test_move_task_by_id():
226 with patch('celery.contrib.migrate.move') as move:
227 move_task_by_id('123f', Queue('foo'))
228 move.assert_called()
229 cb = move.call_args[0][0]
230 body = {'id': '123f'}
231 assert cb(body, Message(body)) == Queue('foo')
232
233
234 class test_migrate_task:
235
236 def test_removes_compression_header(self):
237 x = Message('foo', compression='zlib')
238 producer = Mock()
239 migrate_task(producer, x.body, x)
240 producer.publish.assert_called()
241 args, kwargs = producer.publish.call_args
242 assert isinstance(args[0], bytes)
243 assert 'compression' not in kwargs['headers']
244 assert kwargs['compression'] == 'zlib'
245 assert kwargs['content_type'] == 'application/json'
246 assert kwargs['content_encoding'] == 'utf-8'
247 assert kwargs['exchange'] == 'exchange'
248 assert kwargs['routing_key'] == 'rkey'
249
250
251 class test_migrate_tasks:
252
253 def test_migrate(self, app, name='testcelery'):
254 connection_kwargs = {
255 'transport_options': {'polling_interval': 0.01}
256 }
257 x = Connection('memory://foo', **connection_kwargs)
258 y = Connection('memory://foo', **connection_kwargs)
259 # use separate state
260 x.default_channel.queues = {}
261 y.default_channel.queues = {}
262
263 ex = Exchange(name, 'direct')
264 q = Queue(name, exchange=ex, routing_key=name)
265 q(x.default_channel).declare()
266 Producer(x).publish('foo', exchange=name, routing_key=name)
267 Producer(x).publish('bar', exchange=name, routing_key=name)
268 Producer(x).publish('baz', exchange=name, routing_key=name)
269 assert x.default_channel.queues
270 assert not y.default_channel.queues
271 migrate_tasks(x, y, accept=['text/plain'], app=app)
272
273 yq = q(y.default_channel)
274 assert yq.get().body == ensure_bytes('foo')
275 assert yq.get().body == ensure_bytes('bar')
276 assert yq.get().body == ensure_bytes('baz')
277
278 Producer(x).publish('foo', exchange=name, routing_key=name)
279 callback = Mock()
280 migrate_tasks(x, y,
281 callback=callback, accept=['text/plain'], app=app)
282 callback.assert_called()
283 migrate = Mock()
284 Producer(x).publish('baz', exchange=name, routing_key=name)
285 migrate_tasks(x, y, callback=callback,
286 migrate=migrate, accept=['text/plain'], app=app)
287 migrate.assert_called()
288
289 with patch('kombu.transport.virtual.Channel.queue_declare') as qd:
290
291 def effect(*args, **kwargs):
292 if kwargs.get('passive'):
293 raise ChannelError('some channel error')
294 return 0, 3, 0
295 qd.side_effect = effect
296 migrate_tasks(x, y, app=app)
297
298 x = Connection('memory://', **connection_kwargs)
299 x.default_channel.queues = {}
300 y.default_channel.queues = {}
301 callback = Mock()
302 migrate_tasks(x, y,
303 callback=callback, accept=['text/plain'], app=app)
304 callback.assert_not_called()