Debian Codegraph @

neutron_lib/tests/unit/test_rpc.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 from unittest import mock
14
15 from oslo_config import cfg
16 import oslo_messaging as messaging
17 from oslo_messaging import conffixture as messaging_conffixture
18 from oslo_messaging import exceptions as oslomsg_exc
19 import testtools
20
21 from neutron_lib import fixture
22 from neutron_lib import rpc
23 from neutron_lib.tests import _base as base
24
25
26 CONF = cfg.CONF
27
28
29 class TestRPC(base.BaseTestCase):
30 def setUp(self):
31 super().setUp()
32 self.useFixture(fixture.RPCFixture())
33
34 @mock.patch.object(rpc, 'RequestContextSerializer')
35 @mock.patch.object(messaging, 'get_rpc_transport')
36 @mock.patch.object(messaging, 'get_notification_transport')
37 def test_init(self, mock_noti_trans, mock_trans, mock_ser):
38 transport = mock.Mock()
39 noti_transport = mock.Mock()
40 conf = mock.Mock()
41
42 mock_trans.return_value = transport
43 mock_noti_trans.return_value = noti_transport
44
45 rpc.init(conf, rpc_ext_mods=['foo'])
46
47 expected_mods = list(set(['foo'] + rpc._DFT_EXMODS))
48 mock_trans.assert_called_once_with(
49 conf, allowed_remote_exmods=expected_mods)
50 mock_noti_trans.assert_called_once_with(
51 conf, allowed_remote_exmods=expected_mods)
52 self.assertIsNotNone(rpc.TRANSPORT)
53 self.assertIsNotNone(rpc.NOTIFICATION_TRANSPORT)
54
55 def test_cleanup_transport_null(self):
56 rpc.NOTIFICATION_TRANSPORT = mock.Mock()
57 rpc.TRANSPORT = None
58 self.assertRaises(AssertionError, rpc.cleanup)
59 rpc.TRANSPORT = mock.Mock()
60
61 def test_cleanup_notification_transport_null(self):
62 rpc.TRANSPORT = mock.Mock()
63 rpc.NOTIFICATION_TRANSPORT = None
64 self.assertRaises(AssertionError, rpc.cleanup)
65 rpc.NOTIFICATION_TRANSPORT = mock.Mock()
66
67 def test_cleanup(self):
68 rpc.NOTIFICATION_TRANSPORT = mock.Mock()
69 rpc.TRANSPORT = mock.Mock()
70 trans_cleanup = mock.Mock()
71 not_trans_cleanup = mock.Mock()
72 rpc.TRANSPORT.cleanup = trans_cleanup
73 rpc.NOTIFICATION_TRANSPORT.cleanup = not_trans_cleanup
74
75 rpc.cleanup()
76
77 trans_cleanup.assert_called_once_with()
78 not_trans_cleanup.assert_called_once_with()
79 self.assertIsNone(rpc.TRANSPORT)
80 self.assertIsNone(rpc.NOTIFICATION_TRANSPORT)
81
82 rpc.TRANSPORT = mock.Mock()
83 rpc.NOTIFICATION_TRANSPORT = mock.Mock()
84
85 @mock.patch.object(rpc, 'RequestContextSerializer')
86 @mock.patch.object(messaging, 'get_rpc_client')
87 def test_get_client(self, mock_get, mock_ser):
88 rpc.TRANSPORT = mock.Mock()
89 tgt = mock.Mock()
90 ser = mock.Mock()
91 mock_get.return_value = 'client'
92 mock_ser.return_value = ser
93
94 client = rpc.get_client(tgt, version_cap='1.0', serializer='foo')
95
96 mock_ser.assert_called_once_with('foo')
97 mock_get.assert_called_once_with(rpc.TRANSPORT,
98 tgt, version_cap='1.0',
99 serializer=ser,
100 client_cls=rpc.BackingOffClient)
101 self.assertEqual('client', client)
102
103 @mock.patch.object(rpc, 'RequestContextSerializer')
104 @mock.patch.object(messaging, 'get_rpc_server')
105 def test_get_server(self, mock_get, mock_ser):
106 ser = mock.Mock()
107 tgt = mock.Mock()
108 ends = mock.Mock()
109 mock_ser.return_value = ser
110 mock_get.return_value = 'server'
111
112 server = rpc.get_server(tgt, ends, serializer='foo')
113
114 mock_ser.assert_called_once_with('foo')
115 mock_get.assert_called_once_with(rpc.TRANSPORT, tgt, ends,
116 serializer=ser)
117 self.assertEqual('server', server)
118
119 def test_get_notifier(self):
120 mock_notifier = mock.Mock(return_value=None)
121 messaging.Notifier.__init__ = mock_notifier
122 rpc.get_notifier('service', publisher_id='foo')
123 mock_notifier.assert_called_once_with(
124 mock.ANY, serializer=mock.ANY, publisher_id='foo')
125
126 def test_get_notifier_null_publisher(self):
127 mock_notifier = mock.Mock(return_value=None)
128 messaging.Notifier.__init__ = mock_notifier
129 rpc.get_notifier('service', host='bar')
130 mock_notifier.assert_called_once_with(
131 mock.ANY, serializer=mock.ANY, publisher_id='service.bar')
132
133
134 class TestRequestContextSerializer(base.BaseTestCase):
135 def setUp(self):
136 super().setUp()
137 self.mock_base = mock.Mock()
138 self.ser = rpc.RequestContextSerializer(self.mock_base)
139 self.ser_null = rpc.RequestContextSerializer(None)
140
141 def test_serialize_entity(self):
142 self.mock_base.serialize_entity.return_value = 'foo'
143
144 ser_ent = self.ser.serialize_entity('context', 'entity')
145
146 self.mock_base.serialize_entity.assert_called_once_with('context',
147 'entity')
148 self.assertEqual('foo', ser_ent)
149
150 def test_deserialize_entity(self):
151 self.mock_base.deserialize_entity.return_value = 'foo'
152
153 deser_ent = self.ser.deserialize_entity('context', 'entity')
154
155 self.mock_base.deserialize_entity.assert_called_once_with('context',
156 'entity')
157 self.assertEqual('foo', deser_ent)
158
159 def test_deserialize_entity_null_base(self):
160 deser_ent = self.ser_null.deserialize_entity('context', 'entity')
161
162 self.assertEqual('entity', deser_ent)
163
164 def test_serialize_context(self):
165 context = mock.Mock()
166
167 self.ser.serialize_context(context)
168
169 context.to_dict.assert_called_once_with()
170
171 def test_deserialize_context(self):
172 context_dict = {'foo': 'bar',
173 'user_id': 1,
174 'tenant_id': 1,
175 'is_admin': True}
176
177 c = self.ser.deserialize_context(context_dict)
178
179 self.assertEqual(1, c.user_id)
180 self.assertEqual(1, c.project_id)
181
182 def test_deserialize_context_no_user_id(self):
183 context_dict = {'foo': 'bar',
184 'user': 1,
185 'tenant_id': 1,
186 'is_admin': True}
187
188 c = self.ser.deserialize_context(context_dict)
189
190 self.assertEqual(1, c.user_id)
191 self.assertEqual(1, c.project_id)
192
193 def test_deserialize_context_no_tenant_id(self):
194 context_dict = {'foo': 'bar',
195 'user_id': 1,
196 'project_id': 1,
197 'is_admin': True}
198
199 c = self.ser.deserialize_context(context_dict)
200
201 self.assertEqual(1, c.user_id)
202 self.assertEqual(1, c.project_id)
203
204 def test_deserialize_context_no_ids(self):
205 context_dict = {'foo': 'bar', 'is_admin': True}
206
207 c = self.ser.deserialize_context(context_dict)
208
209 self.assertIsNone(c.user_id)
210 self.assertIsNone(c.project_id)
211
212
213 class ServiceTestCase(base.BaseTestCase):
214 # the class cannot be based on BaseTestCase since it mocks rpc.Connection
215
216 def setUp(self):
217 super().setUp()
218 self.host = 'foo'
219 self.topic = 'neutron-agent'
220
221 self.target_mock = mock.patch('oslo_messaging.Target')
222 self.target_mock.start()
223
224 self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
225 self.messaging_conf.transport_url = 'fake://'
226 self.messaging_conf.response_timeout = 0
227 self.useFixture(self.messaging_conf)
228
229 self.addCleanup(rpc.cleanup)
230 rpc.init(CONF)
231
232 @mock.patch.object(cfg, 'CONF')
233 def test_operations(self, mock_conf):
234 mock_conf.host = self.host
235 with mock.patch('oslo_messaging.get_rpc_server') as get_rpc_server:
236 rpc_server = get_rpc_server.return_value
237
238 service = rpc.Service(self.host, self.topic)
239 service.start()
240 rpc_server.start.assert_called_once_with()
241
242 service.stop()
243 rpc_server.stop.assert_called_once_with()
244 rpc_server.wait.assert_called_once_with()
245
246
247 class TimeoutTestCase(base.BaseTestCase):
248 def setUp(self):
249 super().setUp()
250
251 self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
252 self.messaging_conf.transport_url = 'fake://'
253 self.messaging_conf.response_timeout = 0
254 self.useFixture(self.messaging_conf)
255
256 self.addCleanup(rpc.cleanup)
257 rpc.init(CONF)
258 rpc.TRANSPORT = mock.MagicMock()
259 rpc.TRANSPORT._send.side_effect = messaging.MessagingTimeout
260 rpc.TRANSPORT.conf.oslo_messaging_metrics.metrics_enabled = False
261 target = messaging.Target(version='1.0', topic='testing')
262 self.client = rpc.get_client(target)
263 self.call_context = mock.Mock()
264 self.sleep = mock.patch('time.sleep').start()
265 rpc.TRANSPORT.conf.rpc_response_timeout = 10
266 rpc.TRANSPORT.conf.rpc_response_max_timeout = 300
267
268 def test_timeout_unaffected_when_explicitly_set(self):
269 rpc.TRANSPORT.conf.rpc_response_timeout = 5
270 ctx = self.client.prepare(topic='sandwiches', timeout=77)
271 with testtools.ExpectedException(messaging.MessagingTimeout):
272 ctx.call(self.call_context, 'create_pb_and_j')
273 # ensure that the timeout was not increased and the back-off sleep
274 # wasn't called
275 self.assertEqual(
276 5,
277 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['create_pb_and_j'])
278 self.assertFalse(self.sleep.called)
279
280 def test_timeout_store_defaults(self):
281 # any method should default to the configured timeout
282 self.assertEqual(
283 rpc.TRANSPORT.conf.rpc_response_timeout,
284 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'])
285 self.assertEqual(
286 rpc.TRANSPORT.conf.rpc_response_timeout,
287 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_2'])
288 # a change to an existing should not affect new or existing ones
289 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_2'] = 7000
290 self.assertEqual(
291 rpc.TRANSPORT.conf.rpc_response_timeout,
292 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'])
293 self.assertEqual(
294 rpc.TRANSPORT.conf.rpc_response_timeout,
295 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_3'])
296
297 def test_method_timeout_sleep(self):
298 rpc.TRANSPORT.conf.rpc_response_timeout = 2
299 for i in range(100):
300 with testtools.ExpectedException(messaging.MessagingTimeout):
301 self.client.call(self.call_context, 'method_1')
302 # sleep value should always be between 0 and configured timeout
303 self.assertGreaterEqual(self.sleep.call_args_list[0][0][0], 0)
304 self.assertLessEqual(self.sleep.call_args_list[0][0][0], 2)
305 self.sleep.reset_mock()
306
307 def test_method_timeout_increases_on_timeout_exception(self):
308 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'] = 1
309 for i in range(5):
310 with testtools.ExpectedException(messaging.MessagingTimeout):
311 self.client.call(self.call_context, 'method_1')
312
313 # we only care to check the timeouts sent to the transport
314 timeouts = [call[1]['timeout']
315 for call in rpc.TRANSPORT._send.call_args_list]
316 self.assertEqual([1, 2, 4, 8, 16], timeouts)
317
318 def test_method_timeout_config_ceiling(self):
319 rpc.TRANSPORT.conf.rpc_response_timeout = 10
320 # 5 doublings should max out at the 10xdefault ceiling
321 for i in range(5):
322 with testtools.ExpectedException(messaging.MessagingTimeout):
323 self.client.call(self.call_context, 'method_1')
324 self.assertEqual(
325 rpc.TRANSPORT.conf.rpc_response_max_timeout,
326 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'])
327 with testtools.ExpectedException(messaging.MessagingTimeout):
328 self.client.call(self.call_context, 'method_1')
329 self.assertEqual(
330 rpc.TRANSPORT.conf.rpc_response_max_timeout,
331 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'])
332
333 def test_timeout_unchanged_on_other_exception(self):
334 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'] = 1
335 rpc.TRANSPORT._send.side_effect = ValueError
336 with testtools.ExpectedException(ValueError):
337 self.client.call(self.call_context, 'method_1')
338 rpc.TRANSPORT._send.side_effect = messaging.MessagingTimeout
339 with testtools.ExpectedException(messaging.MessagingTimeout):
340 self.client.call(self.call_context, 'method_1')
341 timeouts = [call[1]['timeout']
342 for call in rpc.TRANSPORT._send.call_args_list]
343 self.assertEqual([1, 1], timeouts)
344
345 def test_timeouts_for_methods_tracked_independently(self):
346 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'] = 1
347 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_2'] = 1
348 for method in ('method_1', 'method_1', 'method_2',
349 'method_1', 'method_2'):
350 with testtools.ExpectedException(messaging.MessagingTimeout):
351 self.client.call(self.call_context, method)
352 timeouts = [call[1]['timeout']
353 for call in rpc.TRANSPORT._send.call_args_list]
354 self.assertEqual([1, 2, 1, 4, 2], timeouts)
355
356 def test_timeouts_for_namespaces_tracked_independently(self):
357 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['ns1.method'] = 1
358 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['ns2.method'] = 1
359 for ns in ('ns1', 'ns2'):
360 self.client.target.namespace = ns
361 for i in range(4):
362 with testtools.ExpectedException(messaging.MessagingTimeout):
363 self.client.call(self.call_context, 'method')
364 timeouts = [call[1]['timeout']
365 for call in rpc.TRANSPORT._send.call_args_list]
366 self.assertEqual([1, 2, 4, 8, 1, 2, 4, 8], timeouts)
367
368 def test_method_timeout_increases_with_prepare(self):
369 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'] = 1
370 ctx = self.client.prepare(version='1.4')
371 with testtools.ExpectedException(messaging.MessagingTimeout):
372 ctx.call(self.call_context, 'method_1')
373 with testtools.ExpectedException(messaging.MessagingTimeout):
374 ctx.call(self.call_context, 'method_1')
375
376 # we only care to check the timeouts sent to the transport
377 timeouts = [call[1]['timeout']
378 for call in rpc.TRANSPORT._send.call_args_list]
379 self.assertEqual([1, 2], timeouts)
380
381 def test_set_max_timeout_caps_all_methods(self):
382 rpc.TRANSPORT.conf.rpc_response_timeout = 300
383 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'] = 100
384 rpc.BackingOffClient.set_max_timeout(50)
385 # both explicitly tracked
386 self.assertEqual(
387 50, rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'])
388 # as well as new methods
389 self.assertEqual(
390 50, rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_2'])
391
392 def test_set_max_timeout_retains_lower_timeouts(self):
393 rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'] = 10
394 rpc.BackingOffClient.set_max_timeout(50)
395 self.assertEqual(
396 10, rpc._BackingOffContextWrapper._METHOD_TIMEOUTS['method_1'])
397
398 def test_set_max_timeout_overrides_default_timeout(self):
399 rpc.TRANSPORT.conf.rpc_response_timeout = 10
400 self.assertEqual(
401 rpc.TRANSPORT.conf.rpc_response_max_timeout,
402 rpc._BackingOffContextWrapper.get_max_timeout())
403 rpc._BackingOffContextWrapper.set_max_timeout(10)
404 self.assertEqual(10, rpc._BackingOffContextWrapper.get_max_timeout())
405
406
407 class CastExceptionTestCase(base.BaseTestCase):
408 def setUp(self):
409 super().setUp()
410
411 self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
412 self.messaging_conf.transport_url = 'fake://'
413 self.messaging_conf.response_timeout = 0
414 self.useFixture(self.messaging_conf)
415
416 self.addCleanup(rpc.cleanup)
417 rpc.init(CONF)
418 rpc.TRANSPORT = mock.MagicMock()
419 rpc.TRANSPORT._send.side_effect = oslomsg_exc.MessageDeliveryFailure
420 rpc.TRANSPORT.conf.oslo_messaging_metrics.metrics_enabled = False
421 target = messaging.Target(version='1.0', topic='testing')
422 self.client = rpc.get_client(target)
423 self.cast_context = mock.Mock()
424
425 def test_cast_catches_exception(self):
426 self.client.cast(self.cast_context, 'method_1')
427
428
429 class TestConnection(base.BaseTestCase):
430 def setUp(self):
431 super().setUp()
432 self.conn = rpc.Connection()
433
434 @mock.patch.object(messaging, 'Target')
435 @mock.patch.object(cfg, 'CONF')
436 @mock.patch.object(rpc, 'get_server')
437 def test_create_consumer(self, mock_get, mock_cfg, mock_tgt):
438 mock_cfg.host = 'foo'
439 server = mock.Mock()
440 target = mock.Mock()
441 mock_get.return_value = server
442 mock_tgt.return_value = target
443
444 self.conn.create_consumer('topic', 'endpoints', fanout=True)
445
446 mock_tgt.assert_called_once_with(topic='topic', server='foo',
447 fanout=True)
448 mock_get.assert_called_once_with(target, 'endpoints')
449 self.assertEqual([server], self.conn.servers)
450
451 def test_consume_in_threads(self):
452 self.conn.servers = [mock.Mock(), mock.Mock()]
453
454 servs = self.conn.consume_in_threads()
455
456 for serv in self.conn.servers:
457 serv.start.assert_called_once_with()
458 self.assertEqual(servs, self.conn.servers)
459
460 def test_close(self):
461 self.conn.servers = [mock.Mock(), mock.Mock()]
462
463 self.conn.close()
464
465 for serv in self.conn.servers:
466 serv.stop.assert_called_once_with()
467 serv.wait.assert_called_once_with()