Debian Codegraph @

t/unit/backends/test_rpc.py

raw
1 import uuid
2 from unittest.mock import Mock, patch
3
4 import pytest
5
6 from celery import chord, group
7 from celery._state import _task_stack
8 from celery.backends.rpc import RPCBackend
9
10
11 class test_RPCResultConsumer:
12 def get_backend(self):
13 return RPCBackend(app=self.app)
14
15 def get_consumer(self):
16 return self.get_backend().result_consumer
17
18 def test_drain_events_before_start(self):
19 consumer = self.get_consumer()
20 # drain_events shouldn't crash when called before start
21 consumer.drain_events(0.001)
22
23 def test_drain_events_reconnects_on_connection_error(self):
24 consumer = self.get_consumer()
25 # Simulate a started consumer with a live connection.
26 mock_conn = Mock(name='connection')
27 mock_conn.connection_errors = (OSError,)
28 mock_conn.channel_errors = ()
29 mock_conn.drain_events.side_effect = OSError(
30 'Server unexpectedly closed connection'
31 )
32 consumer._connection = mock_conn
33 consumer._connection_errors = mock_conn.connection_errors + mock_conn.channel_errors
34
35 mock_consumer = Mock(name='consumer')
36 mock_consumer.queues = [Mock(name='queue1')]
37 consumer._consumer = mock_consumer
38
39 # Patch app.connection() to return a fresh mock connection
40 # and Consumer to return a mock consumer.
41 new_conn = Mock(name='new_connection')
42 new_conn.connection_errors = (OSError,)
43 new_conn.channel_errors = ()
44 new_kombu_consumer = Mock(name='new_kombu_consumer')
45 consumer.app = Mock()
46 consumer.app.connection.return_value = new_conn
47 consumer.Consumer = Mock(return_value=new_kombu_consumer)
48
49 # drain_events should NOT raise; it should reconnect instead.
50 consumer.drain_events(timeout=1)
51
52 # Old connection should be closed.
53 mock_conn.close.assert_called_once()
54 # New connection should be established.
55 consumer.app.connection.assert_called_once()
56 assert consumer._connection is new_conn
57 # New consumer should be consuming.
58 assert consumer._consumer is new_kombu_consumer
59 new_kombu_consumer.consume.assert_called_once()
60
61 def test_drain_events_reconnect_preserves_queues(self):
62 consumer = self.get_consumer()
63 mock_conn = Mock(name='connection')
64 mock_conn.connection_errors = (ConnectionError,)
65 mock_conn.channel_errors = ()
66 mock_conn.drain_events.side_effect = ConnectionError('reset')
67 consumer._connection = mock_conn
68 consumer._connection_errors = mock_conn.connection_errors + mock_conn.channel_errors
69
70 queue1, queue2 = Mock(name='q1'), Mock(name='q2')
71 mock_consumer = Mock(name='consumer')
72 mock_consumer.queues = [queue1, queue2]
73 consumer._consumer = mock_consumer
74
75 new_conn = Mock(name='new_connection')
76 new_conn.connection_errors = (ConnectionError,)
77 new_conn.channel_errors = ()
78 consumer.app = Mock()
79 consumer.app.connection.return_value = new_conn
80 consumer.Consumer = Mock(return_value=Mock(name='new_kombu_consumer'))
81
82 consumer.drain_events(timeout=1)
83
84 # The new Consumer should have been created with both old queues.
85 new_consumer_call = consumer.Consumer.call_args
86 assert list(new_consumer_call[0][1]) == [queue1, queue2]
87
88 def test_drain_events_no_reconnect_on_other_errors(self):
89 consumer = self.get_consumer()
90 mock_conn = Mock(name='connection')
91 mock_conn.connection_errors = (OSError,)
92 mock_conn.channel_errors = ()
93 mock_conn.drain_events.side_effect = RuntimeError('unexpected')
94 consumer._connection = mock_conn
95 consumer._connection_errors = mock_conn.connection_errors + mock_conn.channel_errors
96
97 with pytest.raises(RuntimeError, match='unexpected'):
98 consumer.drain_events(timeout=1)
99
100 def test_reconnect_handles_close_failures_gracefully(self):
101 consumer = self.get_consumer()
102 mock_conn = Mock(name='connection')
103 mock_conn.close.side_effect = OSError('already closed')
104 consumer._connection = mock_conn
105
106 mock_consumer = Mock(name='consumer')
107 mock_consumer.cancel.side_effect = OSError('channel gone')
108 mock_consumer.queues = [Mock(name='queue1')]
109 consumer._consumer = mock_consumer
110
111 new_conn = Mock(name='new_connection')
112 new_conn.connection_errors = (OSError,)
113 new_conn.channel_errors = ()
114 new_kombu_consumer = Mock(name='new_kombu_consumer')
115 consumer.app = Mock()
116 consumer.app.connection.return_value = new_conn
117 consumer.Consumer = Mock(return_value=new_kombu_consumer)
118
119 # _reconnect should NOT raise even if cancel/close fail
120 consumer._reconnect()
121
122 assert consumer._connection is new_conn
123 new_kombu_consumer.consume.assert_called_once()
124
125 def test_drain_events_channel_error_triggers_reconnect(self):
126 consumer = self.get_consumer()
127 mock_conn = Mock(name='connection')
128 mock_conn.connection_errors = ()
129 mock_conn.channel_errors = (KeyError,)
130 mock_conn.drain_events.side_effect = KeyError('channel closed')
131 consumer._connection = mock_conn
132 consumer._connection_errors = mock_conn.connection_errors + mock_conn.channel_errors
133
134 mock_consumer = Mock(name='consumer')
135 mock_consumer.queues = []
136 consumer._consumer = mock_consumer
137
138 new_conn = Mock(name='new_connection')
139 new_conn.connection_errors = ()
140 new_conn.channel_errors = (KeyError,)
141 consumer.app = Mock()
142 consumer.app.connection.return_value = new_conn
143 consumer.Consumer = Mock(return_value=Mock(name='new_kombu_consumer'))
144
145 consumer.drain_events(timeout=1)
146
147 assert consumer._connection is new_conn
148
149 def test_drain_events_raises_runtime_when_reconnect_also_fails(self):
150 consumer = self.get_consumer()
151
152 class FakeConnError(Exception):
153 pass
154
155 mock_conn = Mock(name='connection')
156 mock_conn.connection_errors = (FakeConnError,)
157 mock_conn.channel_errors = ()
158 mock_conn.drain_events.side_effect = FakeConnError('dropped')
159 consumer._connection = mock_conn
160 consumer._connection_errors = mock_conn.connection_errors + mock_conn.channel_errors
161
162 mock_consumer = Mock(name='consumer')
163 mock_consumer.queues = []
164 consumer._consumer = mock_consumer
165
166 consumer.app = Mock()
167 consumer.app.connection.side_effect = FakeConnError('still down')
168
169 with pytest.raises(RuntimeError, match='Retry limit exceeded'):
170 consumer.drain_events(timeout=1)
171
172
173 class test_RPCBackend:
174
175 def setup_method(self):
176 self.b = RPCBackend(app=self.app)
177
178 def test_oid(self):
179 oid = self.b.oid
180 oid2 = self.b.oid
181 assert uuid.UUID(oid)
182 assert oid == oid2
183 assert oid == self.app.thread_oid
184
185 def test_oid_threads(self):
186 # Verify that two RPC backends executed in different threads
187 # has different oid.
188 oid = self.b.oid
189 from concurrent.futures import ThreadPoolExecutor
190 with ThreadPoolExecutor(max_workers=1) as executor:
191 future = executor.submit(lambda: RPCBackend(app=self.app).oid)
192 thread_oid = future.result()
193 assert uuid.UUID(oid)
194 assert uuid.UUID(thread_oid)
195 assert oid == self.app.thread_oid
196 assert thread_oid != oid
197
198 def test_interface(self):
199 self.b.on_reply_declare('task_id')
200
201 def test_ensure_chords_allowed(self):
202 with pytest.raises(NotImplementedError):
203 self.b.ensure_chords_allowed()
204
205 def test_apply_chord(self):
206 with pytest.raises(NotImplementedError):
207 self.b.apply_chord(self.app.GroupResult(), None)
208
209 @pytest.mark.celery(result_backend='rpc')
210 def test_chord_raises_error(self):
211 with pytest.raises(NotImplementedError):
212 chord(self.add.s(i, i) for i in range(10))(self.add.s([2]))
213
214 @pytest.mark.celery(result_backend='rpc')
215 def test_chain_with_chord_raises_error(self):
216 with pytest.raises(NotImplementedError):
217 (self.add.s(2, 2) |
218 group(self.add.s(2, 2),
219 self.add.s(5, 6)) | self.add.s()).delay()
220
221 def test_destination_for(self):
222 req = Mock(name='request')
223 req.reply_to = 'reply_to'
224 req.correlation_id = 'corid'
225 assert self.b.destination_for('task_id', req) == ('reply_to', 'corid')
226 task = Mock()
227 _task_stack.push(task)
228 try:
229 task.request.reply_to = 'reply_to'
230 task.request.correlation_id = 'corid'
231 assert self.b.destination_for('task_id', None) == (
232 'reply_to', 'corid',
233 )
234 finally:
235 _task_stack.pop()
236
237 with pytest.raises(RuntimeError):
238 self.b.destination_for('task_id', None)
239
240 def test_binding(self):
241 queue = self.b.binding
242 assert queue.name == self.b.oid
243 assert queue.exchange == self.b.exchange
244 assert queue.routing_key == self.b.oid
245 assert not queue.durable
246 assert queue.auto_delete
247
248 def test_create_binding(self):
249 assert self.b._create_binding('id') == self.b.binding
250
251 def test_on_task_call(self):
252 with patch('celery.backends.rpc.maybe_declare') as md:
253 with self.app.amqp.producer_pool.acquire() as prod:
254 self.b.on_task_call(prod, 'task_id'),
255 md.assert_called_with(
256 self.b.binding(prod.channel),
257 retry=True,
258 )
259
260 def test_create_exchange(self):
261 ex = self.b._create_exchange('name')
262 assert isinstance(ex, self.b.Exchange)
263 assert ex.name == ''