Refactor NG_RO/ns.py _process_vdu_params method
[osm/RO.git] / RO-VIM-openstack / osm_rovim_openstack / tests / test_vimconn_openstack.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2017 Intel Corporation.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
16 # under the License.
17 #
18 # For those usages not covered by the Apache License, Version 2.0 please
19 # contact with: nfvlabs@tid.es
20 ##
21
22 """
23 This module contains unit tests for the OpenStack VIM connector
24 Run this directly with python2 or python3.
25 """
26 import copy
27 from copy import deepcopy
28 import logging
29 import unittest
30
31 import mock
32 from mock import MagicMock, patch
33 from neutronclient.v2_0.client import Client
34 from novaclient import exceptions as nvExceptions
35 from osm_ro_plugin import vimconn
36 from osm_ro_plugin.vimconn import (
37 VimConnConnectionException,
38 VimConnException,
39 VimConnNotFoundException,
40 )
41 from osm_rovim_openstack.vimconn_openstack import vimconnector
42
43 __author__ = "Igor D.C."
44 __date__ = "$23-aug-2017 23:59:59$"
45
46 # Variables Used in TestNewVmInstance Class
47 name = "basicvm"
48 description = "my firewall"
49 start = True
50 image_id = "408b73-e9cc-5a6a-t270-82cc4811bd4a"
51 flavor_id = "208b73-e9cc-5a6a-t270-82cc4811bd4a"
52 affinity_group_list = []
53 net_list = []
54 cloud_config = {}
55 disk_list = []
56 disk_list2 = [
57 {"size": 10, "image_id": image_id},
58 {"size": 20},
59 ]
60 availability_zone_index = 0
61 availability_zone_list = ["nova"]
62 floating_network_vim_id = "108b73-e9cc-5a6a-t270-82cc4811bd4a"
63 net_id = "83372685-f67f-49fd-8722-eabb7692fc22"
64 net2_id = "46472685-f67f-49fd-8722-eabb7692fc22"
65 mac_address = "00:00:5e:00:53:af"
66 port_id = "03372685-f67f-49fd-8722-eabb7692fc22"
67 time_return_value = 156570000
68 port2_id = "17472685-f67f-49fd-8722-eabb7692fc22"
69 root_vol_id = "tc408b73-r9cc-5a6a-a270-82cc4811bd4a"
70 ip_addr1 = "20.3.4.5"
71 volume_id = "ac408b73-b9cc-4a6a-a270-82cc4811bd4a"
72 volume_id2 = "o4e0e83-b9uu-4akk-a234-89cc4811bd4a"
73 volume_id3 = "44e0e83-t9uu-4akk-a234-p9cc4811bd4a"
74 virtual_mac_id = "64e0e83-t9uu-4akk-a234-p9cc4811bd4a"
75 created_items_all_true = {
76 f"floating_ip:{floating_network_vim_id}": True,
77 f"volume:{volume_id}": True,
78 f"port:{port_id}": True,
79 }
80
81
82 class TestSfcOperations(unittest.TestCase):
83 @mock.patch("logging.getLogger", autospec=True)
84 def setUp(self, mock_logger):
85 # Instantiate dummy VIM connector so we can test it
86 # It throws exception because of dummy parameters,
87 # We are disabling the logging of exception not to print them to console.
88 mock_logger = logging.getLogger()
89 mock_logger.disabled = True
90 self.vimconn = vimconnector(
91 "123",
92 "openstackvim",
93 "456",
94 "789",
95 "http://dummy.url",
96 None,
97 "user",
98 "pass",
99 )
100
101 def _test_new_sfi(
102 self,
103 create_sfc_port_pair,
104 sfc_encap,
105 ingress_ports=["5311c75d-d718-4369-bbda-cdcc6da60fcc"],
106 egress_ports=["230cdf1b-de37-4891-bc07-f9010cf1f967"],
107 ):
108 # input to VIM connector
109 name = "osm_sfi"
110 # + ingress_ports
111 # + egress_ports
112 # TODO(igordc): must be changed to NSH in Queens (MPLS is a workaround)
113 correlation = "nsh"
114 if sfc_encap is not None:
115 if not sfc_encap:
116 correlation = None
117
118 # what OpenStack is assumed to respond (patch OpenStack"s return value)
119 dict_from_neutron = {
120 "port_pair": {
121 "id": "3d7ddc13-923c-4332-971e-708ed82902ce",
122 "name": name,
123 "description": "",
124 "tenant_id": "130b1e97-b0f1-40a8-8804-b6ad9b8c3e0c",
125 "project_id": "130b1e97-b0f1-40a8-8804-b6ad9b8c3e0c",
126 "ingress": ingress_ports[0] if len(ingress_ports) else None,
127 "egress": egress_ports[0] if len(egress_ports) else None,
128 "service_function_parameters": {"correlation": correlation},
129 }
130 }
131 create_sfc_port_pair.return_value = dict_from_neutron
132
133 # what the VIM connector is expected to
134 # send to OpenStack based on the input
135 dict_to_neutron = {
136 "port_pair": {
137 "name": name,
138 "ingress": "5311c75d-d718-4369-bbda-cdcc6da60fcc",
139 "egress": "230cdf1b-de37-4891-bc07-f9010cf1f967",
140 "service_function_parameters": {"correlation": correlation},
141 }
142 }
143
144 # call the VIM connector
145 if sfc_encap is None:
146 result = self.vimconn.new_sfi(name, ingress_ports, egress_ports)
147 else:
148 result = self.vimconn.new_sfi(name, ingress_ports, egress_ports, sfc_encap)
149
150 # assert that the VIM connector made the expected call to OpenStack
151 create_sfc_port_pair.assert_called_with(dict_to_neutron)
152 # assert that the VIM connector had the expected result / return value
153 self.assertEqual(result, dict_from_neutron["port_pair"]["id"])
154
155 def _test_new_sf(self, create_sfc_port_pair_group):
156 # input to VIM connector
157 name = "osm_sf"
158 instances = [
159 "bbd01220-cf72-41f2-9e70-0669c2e5c4cd",
160 "12ba215e-3987-4892-bd3a-d0fd91eecf98",
161 "e25a7c79-14c8-469a-9ae1-f601c9371ffd",
162 ]
163
164 # what OpenStack is assumed to respond (patch OpenStack"s return value)
165 dict_from_neutron = {
166 "port_pair_group": {
167 "id": "3d7ddc13-923c-4332-971e-708ed82902ce",
168 "name": name,
169 "description": "",
170 "tenant_id": "130b1e97-b0f1-40a8-8804-b6ad9b8c3e0c",
171 "project_id": "130b1e97-b0f1-40a8-8804-b6ad9b8c3e0c",
172 "port_pairs": instances,
173 "group_id": 1,
174 "port_pair_group_parameters": {
175 "lb_fields": [],
176 "ppg_n_tuple_mapping": {
177 "ingress_n_tuple": {},
178 "egress_n_tuple": {},
179 },
180 },
181 }
182 }
183 create_sfc_port_pair_group.return_value = dict_from_neutron
184
185 # what the VIM connector is expected to
186 # send to OpenStack based on the input
187 dict_to_neutron = {
188 "port_pair_group": {
189 "name": name,
190 "port_pairs": [
191 "bbd01220-cf72-41f2-9e70-0669c2e5c4cd",
192 "12ba215e-3987-4892-bd3a-d0fd91eecf98",
193 "e25a7c79-14c8-469a-9ae1-f601c9371ffd",
194 ],
195 }
196 }
197
198 # call the VIM connector
199 result = self.vimconn.new_sf(name, instances)
200
201 # assert that the VIM connector made the expected call to OpenStack
202 create_sfc_port_pair_group.assert_called_with(dict_to_neutron)
203 # assert that the VIM connector had the expected result / return value
204 self.assertEqual(result, dict_from_neutron["port_pair_group"]["id"])
205
206 def _test_new_sfp(self, create_sfc_port_chain, sfc_encap, spi):
207 # input to VIM connector
208 name = "osm_sfp"
209 classifications = [
210 "2bd2a2e5-c5fd-4eac-a297-d5e255c35c19",
211 "00f23389-bdfa-43c2-8b16-5815f2582fa8",
212 ]
213 sfs = [
214 "2314daec-c262-414a-86e3-69bb6fa5bc16",
215 "d8bfdb5d-195e-4f34-81aa-6135705317df",
216 ]
217
218 # TODO(igordc): must be changed to NSH in Queens (MPLS is a workaround)
219 correlation = "nsh"
220 chain_id = 33
221 if spi:
222 chain_id = spi
223
224 # what OpenStack is assumed to respond (patch OpenStack"s return value)
225 dict_from_neutron = {
226 "port_chain": {
227 "id": "5bc05721-079b-4b6e-a235-47cac331cbb6",
228 "name": name,
229 "description": "",
230 "tenant_id": "130b1e97-b0f1-40a8-8804-b6ad9b8c3e0c",
231 "project_id": "130b1e97-b0f1-40a8-8804-b6ad9b8c3e0c",
232 "chain_id": chain_id,
233 "flow_classifiers": classifications,
234 "port_pair_groups": sfs,
235 "chain_parameters": {"correlation": correlation},
236 }
237 }
238 create_sfc_port_chain.return_value = dict_from_neutron
239
240 # what the VIM connector is expected to
241 # send to OpenStack based on the input
242 dict_to_neutron = {
243 "port_chain": {
244 "name": name,
245 "flow_classifiers": [
246 "2bd2a2e5-c5fd-4eac-a297-d5e255c35c19",
247 "00f23389-bdfa-43c2-8b16-5815f2582fa8",
248 ],
249 "port_pair_groups": [
250 "2314daec-c262-414a-86e3-69bb6fa5bc16",
251 "d8bfdb5d-195e-4f34-81aa-6135705317df",
252 ],
253 "chain_parameters": {"correlation": correlation},
254 }
255 }
256 if spi:
257 dict_to_neutron["port_chain"]["chain_id"] = spi
258
259 # call the VIM connector
260 if sfc_encap is None:
261 dict_to_neutron["port_chain"]["chain_parameters"] = {"correlation": "mpls"}
262 if spi is None:
263 result = self.vimconn.new_sfp(
264 name, classifications, sfs, sfc_encap=False
265 )
266 else:
267 result = self.vimconn.new_sfp(
268 name, classifications, sfs, sfc_encap=False, spi=spi
269 )
270 else:
271 if spi is None:
272 result = self.vimconn.new_sfp(name, classifications, sfs, sfc_encap)
273 else:
274 result = self.vimconn.new_sfp(
275 name, classifications, sfs, sfc_encap, spi
276 )
277
278 # assert that the VIM connector made the expected call to OpenStack
279 create_sfc_port_chain.assert_called_with(dict_to_neutron)
280 # assert that the VIM connector had the expected result / return value
281 self.assertEqual(result, dict_from_neutron["port_chain"]["id"])
282
283 def _test_new_classification(self, create_sfc_flow_classifier, ctype):
284 # input to VIM connector
285 name = "osm_classification"
286 definition = {
287 "ethertype": "IPv4",
288 "logical_source_port": "aaab0ab0-1452-4636-bb3b-11dca833fa2b",
289 "protocol": "tcp",
290 "source_ip_prefix": "192.168.2.0/24",
291 "source_port_range_max": 99,
292 "source_port_range_min": 50,
293 }
294
295 # what OpenStack is assumed to respond (patch OpenStack"s return value)
296 dict_from_neutron = {"flow_classifier": copy.copy(definition)}
297 dict_from_neutron["flow_classifier"][
298 "id"
299 ] = "7735ec2c-fddf-4130-9712-32ed2ab6a372"
300 dict_from_neutron["flow_classifier"]["name"] = name
301 dict_from_neutron["flow_classifier"]["description"] = ""
302 dict_from_neutron["flow_classifier"][
303 "tenant_id"
304 ] = "130b1e97-b0f1-40a8-8804-b6ad9b8c3e0c"
305 dict_from_neutron["flow_classifier"][
306 "project_id"
307 ] = "130b1e97-b0f1-40a8-8804-b6ad9b8c3e0c"
308 create_sfc_flow_classifier.return_value = dict_from_neutron
309
310 # what the VIM connector is expected to
311 # send to OpenStack based on the input
312 dict_to_neutron = {"flow_classifier": copy.copy(definition)}
313 dict_to_neutron["flow_classifier"]["name"] = "osm_classification"
314
315 # call the VIM connector
316 result = self.vimconn.new_classification(name, ctype, definition)
317
318 # assert that the VIM connector made the expected call to OpenStack
319 create_sfc_flow_classifier.assert_called_with(dict_to_neutron)
320 # assert that the VIM connector had the expected result / return value
321 self.assertEqual(result, dict_from_neutron["flow_classifier"]["id"])
322
323 @mock.patch.object(Client, "create_sfc_flow_classifier")
324 def test_new_classification(self, create_sfc_flow_classifier):
325 self._test_new_classification(
326 create_sfc_flow_classifier, "legacy_flow_classifier"
327 )
328
329 @mock.patch.object(Client, "create_sfc_flow_classifier")
330 def test_new_classification_unsupported_type(self, create_sfc_flow_classifier):
331 self.assertRaises(
332 vimconn.VimConnNotSupportedException,
333 self._test_new_classification,
334 create_sfc_flow_classifier,
335 "h265",
336 )
337
338 @mock.patch.object(Client, "create_sfc_port_pair")
339 def test_new_sfi_with_sfc_encap(self, create_sfc_port_pair):
340 self._test_new_sfi(create_sfc_port_pair, True)
341
342 @mock.patch.object(Client, "create_sfc_port_pair")
343 def test_new_sfi_without_sfc_encap(self, create_sfc_port_pair):
344 self._test_new_sfi(create_sfc_port_pair, False)
345
346 @mock.patch.object(Client, "create_sfc_port_pair")
347 def test_new_sfi_default_sfc_encap(self, create_sfc_port_pair):
348 self._test_new_sfi(create_sfc_port_pair, None)
349
350 @mock.patch.object(Client, "create_sfc_port_pair")
351 def test_new_sfi_bad_ingress_ports(self, create_sfc_port_pair):
352 ingress_ports = [
353 "5311c75d-d718-4369-bbda-cdcc6da60fcc",
354 "a0273f64-82c9-11e7-b08f-6328e53f0fa7",
355 ]
356 self.assertRaises(
357 vimconn.VimConnNotSupportedException,
358 self._test_new_sfi,
359 create_sfc_port_pair,
360 True,
361 ingress_ports=ingress_ports,
362 )
363 ingress_ports = []
364 self.assertRaises(
365 vimconn.VimConnNotSupportedException,
366 self._test_new_sfi,
367 create_sfc_port_pair,
368 True,
369 ingress_ports=ingress_ports,
370 )
371
372 @mock.patch.object(Client, "create_sfc_port_pair")
373 def test_new_sfi_bad_egress_ports(self, create_sfc_port_pair):
374 egress_ports = [
375 "230cdf1b-de37-4891-bc07-f9010cf1f967",
376 "b41228fe-82c9-11e7-9b44-17504174320b",
377 ]
378 self.assertRaises(
379 vimconn.VimConnNotSupportedException,
380 self._test_new_sfi,
381 create_sfc_port_pair,
382 True,
383 egress_ports=egress_ports,
384 )
385 egress_ports = []
386 self.assertRaises(
387 vimconn.VimConnNotSupportedException,
388 self._test_new_sfi,
389 create_sfc_port_pair,
390 True,
391 egress_ports=egress_ports,
392 )
393
394 @mock.patch.object(vimconnector, "get_sfi")
395 @mock.patch.object(Client, "create_sfc_port_pair_group")
396 def test_new_sf(self, create_sfc_port_pair_group, get_sfi):
397 get_sfi.return_value = {"sfc_encap": True}
398 self._test_new_sf(create_sfc_port_pair_group)
399
400 @mock.patch.object(vimconnector, "get_sfi")
401 @mock.patch.object(Client, "create_sfc_port_pair_group")
402 def test_new_sf_inconsistent_sfc_encap(self, create_sfc_port_pair_group, get_sfi):
403 get_sfi.return_value = {"sfc_encap": "nsh"}
404 self.assertRaises(
405 vimconn.VimConnNotSupportedException,
406 self._test_new_sf,
407 create_sfc_port_pair_group,
408 )
409
410 @mock.patch.object(Client, "create_sfc_port_chain")
411 def test_new_sfp_with_sfc_encap(self, create_sfc_port_chain):
412 self._test_new_sfp(create_sfc_port_chain, True, None)
413
414 @mock.patch.object(Client, "create_sfc_port_chain")
415 def test_new_sfp_without_sfc_encap(self, create_sfc_port_chain):
416 self._test_new_sfp(create_sfc_port_chain, None, None)
417 self._test_new_sfp(create_sfc_port_chain, None, 25)
418
419 @mock.patch.object(Client, "create_sfc_port_chain")
420 def test_new_sfp_default_sfc_encap(self, create_sfc_port_chain):
421 self._test_new_sfp(create_sfc_port_chain, None, None)
422
423 @mock.patch.object(Client, "create_sfc_port_chain")
424 def test_new_sfp_with_sfc_encap_spi(self, create_sfc_port_chain):
425 self._test_new_sfp(create_sfc_port_chain, True, 25)
426
427 @mock.patch.object(Client, "create_sfc_port_chain")
428 def test_new_sfp_default_sfc_encap_spi(self, create_sfc_port_chain):
429 self._test_new_sfp(create_sfc_port_chain, None, 25)
430
431 @mock.patch.object(Client, "list_sfc_flow_classifiers")
432 def test_get_classification_list(self, list_sfc_flow_classifiers):
433 # what OpenStack is assumed to return to the VIM connector
434 list_sfc_flow_classifiers.return_value = {
435 "flow_classifiers": [
436 {
437 "source_port_range_min": 2000,
438 "destination_ip_prefix": "192.168.3.0/24",
439 "protocol": "udp",
440 "description": "",
441 "ethertype": "IPv4",
442 "l7_parameters": {},
443 "source_port_range_max": 2000,
444 "destination_port_range_min": 3000,
445 "source_ip_prefix": "192.168.2.0/24",
446 "logical_destination_port": None,
447 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
448 "destination_port_range_max": None,
449 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
450 "logical_source_port": "aaab0ab0-1452-4636-bb3b-11dca833fa2b",
451 "id": "22198366-d4e8-4d6b-b4d2-637d5d6cbb7d",
452 "name": "fc1",
453 }
454 ]
455 }
456
457 # call the VIM connector
458 filter_dict = {"protocol": "tcp", "ethertype": "IPv4"}
459 result = self.vimconn.get_classification_list(filter_dict.copy())
460
461 # assert that VIM connector called OpenStack with the expected filter
462 list_sfc_flow_classifiers.assert_called_with(**filter_dict)
463 # assert that the VIM connector successfully
464 # translated and returned the OpenStack result
465 self.assertEqual(
466 result,
467 [
468 {
469 "id": "22198366-d4e8-4d6b-b4d2-637d5d6cbb7d",
470 "name": "fc1",
471 "description": "",
472 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
473 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
474 "ctype": "legacy_flow_classifier",
475 "definition": {
476 "source_port_range_min": 2000,
477 "destination_ip_prefix": "192.168.3.0/24",
478 "protocol": "udp",
479 "ethertype": "IPv4",
480 "l7_parameters": {},
481 "source_port_range_max": 2000,
482 "destination_port_range_min": 3000,
483 "source_ip_prefix": "192.168.2.0/24",
484 "logical_destination_port": None,
485 "destination_port_range_max": None,
486 "logical_source_port": "aaab0ab0-1452-4636-bb3b-11dca833fa2b",
487 },
488 }
489 ],
490 )
491
492 def _test_get_sfi_list(self, list_port_pair, correlation, sfc_encap):
493 # what OpenStack is assumed to return to the VIM connector
494 list_port_pair.return_value = {
495 "port_pairs": [
496 {
497 "ingress": "5311c75d-d718-4369-bbda-cdcc6da60fcc",
498 "description": "",
499 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
500 "egress": "5311c75d-d718-4369-bbda-cdcc6da60fcc",
501 "service_function_parameters": {"correlation": correlation},
502 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
503 "id": "c121ebdd-7f2d-4213-b933-3325298a6966",
504 "name": "osm_sfi",
505 }
506 ]
507 }
508
509 # call the VIM connector
510 filter_dict = {"name": "osm_sfi", "description": ""}
511 result = self.vimconn.get_sfi_list(filter_dict.copy())
512
513 # assert that VIM connector called OpenStack with the expected filter
514 list_port_pair.assert_called_with(**filter_dict)
515 # assert that the VIM connector successfully
516 # translated and returned the OpenStack result
517 self.assertEqual(
518 result,
519 [
520 {
521 "ingress_ports": ["5311c75d-d718-4369-bbda-cdcc6da60fcc"],
522 "description": "",
523 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
524 "egress_ports": ["5311c75d-d718-4369-bbda-cdcc6da60fcc"],
525 "sfc_encap": sfc_encap,
526 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
527 "id": "c121ebdd-7f2d-4213-b933-3325298a6966",
528 "name": "osm_sfi",
529 }
530 ],
531 )
532
533 @mock.patch.object(Client, "list_sfc_port_pairs")
534 def test_get_sfi_list_with_sfc_encap(self, list_sfc_port_pairs):
535 self._test_get_sfi_list(list_sfc_port_pairs, "nsh", True)
536
537 @mock.patch.object(Client, "list_sfc_port_pairs")
538 def test_get_sfi_list_without_sfc_encap(self, list_sfc_port_pairs):
539 self._test_get_sfi_list(list_sfc_port_pairs, None, False)
540
541 @mock.patch.object(Client, "list_sfc_port_pair_groups")
542 def test_get_sf_list(self, list_sfc_port_pair_groups):
543 # what OpenStack is assumed to return to the VIM connector
544 list_sfc_port_pair_groups.return_value = {
545 "port_pair_groups": [
546 {
547 "port_pairs": [
548 "08fbdbb0-82d6-11e7-ad95-9bb52fbec2f2",
549 "0d63799c-82d6-11e7-8deb-a746bb3ae9f5",
550 ],
551 "description": "",
552 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
553 "port_pair_group_parameters": {},
554 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
555 "id": "f4a0bde8-82d5-11e7-90e1-a72b762fa27f",
556 "name": "osm_sf",
557 }
558 ]
559 }
560
561 # call the VIM connector
562 filter_dict = {"name": "osm_sf", "description": ""}
563 result = self.vimconn.get_sf_list(filter_dict.copy())
564
565 # assert that VIM connector called OpenStack with the expected filter
566 list_sfc_port_pair_groups.assert_called_with(**filter_dict)
567 # assert that the VIM connector successfully
568 # translated and returned the OpenStack result
569 self.assertEqual(
570 result,
571 [
572 {
573 "sfis": [
574 "08fbdbb0-82d6-11e7-ad95-9bb52fbec2f2",
575 "0d63799c-82d6-11e7-8deb-a746bb3ae9f5",
576 ],
577 "description": "",
578 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
579 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
580 "id": "f4a0bde8-82d5-11e7-90e1-a72b762fa27f",
581 "name": "osm_sf",
582 }
583 ],
584 )
585
586 def _test_get_sfp_list(self, list_sfc_port_chains, correlation, sfc_encap):
587 # what OpenStack is assumed to return to the VIM connector
588 list_sfc_port_chains.return_value = {
589 "port_chains": [
590 {
591 "port_pair_groups": [
592 "7d8e3bf8-82d6-11e7-a032-8ff028839d25",
593 "7dc9013e-82d6-11e7-a5a6-a3a8d78a5518",
594 ],
595 "flow_classifiers": [
596 "1333c2f4-82d7-11e7-a5df-9327f33d104e",
597 "1387ab44-82d7-11e7-9bb0-476337183905",
598 ],
599 "description": "",
600 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
601 "chain_parameters": {"correlation": correlation},
602 "chain_id": 40,
603 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
604 "id": "821bc9be-82d7-11e7-8ce3-23a08a27ab47",
605 "name": "osm_sfp",
606 }
607 ]
608 }
609
610 # call the VIM connector
611 filter_dict = {"name": "osm_sfp", "description": ""}
612 result = self.vimconn.get_sfp_list(filter_dict.copy())
613
614 # assert that VIM connector called OpenStack with the expected filter
615 list_sfc_port_chains.assert_called_with(**filter_dict)
616 # assert that the VIM connector successfully
617 # translated and returned the OpenStack result
618 self.assertEqual(
619 result,
620 [
621 {
622 "service_functions": [
623 "7d8e3bf8-82d6-11e7-a032-8ff028839d25",
624 "7dc9013e-82d6-11e7-a5a6-a3a8d78a5518",
625 ],
626 "classifications": [
627 "1333c2f4-82d7-11e7-a5df-9327f33d104e",
628 "1387ab44-82d7-11e7-9bb0-476337183905",
629 ],
630 "description": "",
631 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
632 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
633 "sfc_encap": sfc_encap,
634 "spi": 40,
635 "id": "821bc9be-82d7-11e7-8ce3-23a08a27ab47",
636 "name": "osm_sfp",
637 }
638 ],
639 )
640
641 @mock.patch.object(Client, "list_sfc_port_chains")
642 def test_get_sfp_list_with_sfc_encap(self, list_sfc_port_chains):
643 self._test_get_sfp_list(list_sfc_port_chains, "nsh", True)
644
645 @mock.patch.object(Client, "list_sfc_port_chains")
646 def test_get_sfp_list_without_sfc_encap(self, list_sfc_port_chains):
647 self._test_get_sfp_list(list_sfc_port_chains, None, False)
648
649 @mock.patch.object(Client, "list_sfc_flow_classifiers")
650 def test_get_classification(self, list_sfc_flow_classifiers):
651 # what OpenStack is assumed to return to the VIM connector
652 list_sfc_flow_classifiers.return_value = {
653 "flow_classifiers": [
654 {
655 "source_port_range_min": 2000,
656 "destination_ip_prefix": "192.168.3.0/24",
657 "protocol": "udp",
658 "description": "",
659 "ethertype": "IPv4",
660 "l7_parameters": {},
661 "source_port_range_max": 2000,
662 "destination_port_range_min": 3000,
663 "source_ip_prefix": "192.168.2.0/24",
664 "logical_destination_port": None,
665 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
666 "destination_port_range_max": None,
667 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
668 "logical_source_port": "aaab0ab0-1452-4636-bb3b-11dca833fa2b",
669 "id": "22198366-d4e8-4d6b-b4d2-637d5d6cbb7d",
670 "name": "fc1",
671 }
672 ]
673 }
674
675 # call the VIM connector
676 result = self.vimconn.get_classification("22198366-d4e8-4d6b-b4d2-637d5d6cbb7d")
677
678 # assert that VIM connector called OpenStack with the expected filter
679 list_sfc_flow_classifiers.assert_called_with(
680 id="22198366-d4e8-4d6b-b4d2-637d5d6cbb7d"
681 )
682 # assert that VIM connector successfully returned the OpenStack result
683 self.assertEqual(
684 result,
685 {
686 "id": "22198366-d4e8-4d6b-b4d2-637d5d6cbb7d",
687 "name": "fc1",
688 "description": "",
689 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
690 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
691 "ctype": "legacy_flow_classifier",
692 "definition": {
693 "source_port_range_min": 2000,
694 "destination_ip_prefix": "192.168.3.0/24",
695 "protocol": "udp",
696 "ethertype": "IPv4",
697 "l7_parameters": {},
698 "source_port_range_max": 2000,
699 "destination_port_range_min": 3000,
700 "source_ip_prefix": "192.168.2.0/24",
701 "logical_destination_port": None,
702 "destination_port_range_max": None,
703 "logical_source_port": "aaab0ab0-1452-4636-bb3b-11dca833fa2b",
704 },
705 },
706 )
707
708 @mock.patch.object(Client, "list_sfc_flow_classifiers")
709 def test_get_classification_many_results(self, list_sfc_flow_classifiers):
710 # what OpenStack is assumed to return to the VIM connector
711 list_sfc_flow_classifiers.return_value = {
712 "flow_classifiers": [
713 {
714 "source_port_range_min": 2000,
715 "destination_ip_prefix": "192.168.3.0/24",
716 "protocol": "udp",
717 "description": "",
718 "ethertype": "IPv4",
719 "l7_parameters": {},
720 "source_port_range_max": 2000,
721 "destination_port_range_min": 3000,
722 "source_ip_prefix": "192.168.2.0/24",
723 "logical_destination_port": None,
724 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
725 "destination_port_range_max": None,
726 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
727 "logical_source_port": "aaab0ab0-1452-4636-bb3b-11dca833fa2b",
728 "id": "22198366-d4e8-4d6b-b4d2-637d5d6cbb7d",
729 "name": "fc1",
730 },
731 {
732 "source_port_range_min": 1000,
733 "destination_ip_prefix": "192.168.3.0/24",
734 "protocol": "udp",
735 "description": "",
736 "ethertype": "IPv4",
737 "l7_parameters": {},
738 "source_port_range_max": 1000,
739 "destination_port_range_min": 3000,
740 "source_ip_prefix": "192.168.2.0/24",
741 "logical_destination_port": None,
742 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
743 "destination_port_range_max": None,
744 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
745 "logical_source_port": "aaab0ab0-1452-4636-bb3b-11dca833fa2b",
746 "id": "3196bafc-82dd-11e7-a205-9bf6c14b0721",
747 "name": "fc2",
748 },
749 ]
750 }
751
752 # call the VIM connector
753 self.assertRaises(
754 vimconn.VimConnConflictException,
755 self.vimconn.get_classification,
756 "3196bafc-82dd-11e7-a205-9bf6c14b0721",
757 )
758
759 # assert the VIM connector called OpenStack with the expected filter
760 list_sfc_flow_classifiers.assert_called_with(
761 id="3196bafc-82dd-11e7-a205-9bf6c14b0721"
762 )
763
764 @mock.patch.object(Client, "list_sfc_flow_classifiers")
765 def test_get_classification_no_results(self, list_sfc_flow_classifiers):
766 # what OpenStack is assumed to return to the VIM connector
767 list_sfc_flow_classifiers.return_value = {"flow_classifiers": []}
768
769 # call the VIM connector
770 self.assertRaises(
771 vimconn.VimConnNotFoundException,
772 self.vimconn.get_classification,
773 "3196bafc-82dd-11e7-a205-9bf6c14b0721",
774 )
775
776 # assert the VIM connector called OpenStack with the expected filter
777 list_sfc_flow_classifiers.assert_called_with(
778 id="3196bafc-82dd-11e7-a205-9bf6c14b0721"
779 )
780
781 @mock.patch.object(Client, "list_sfc_port_pairs")
782 def test_get_sfi(self, list_sfc_port_pairs):
783 # what OpenStack is assumed to return to the VIM connector
784 list_sfc_port_pairs.return_value = {
785 "port_pairs": [
786 {
787 "ingress": "5311c75d-d718-4369-bbda-cdcc6da60fcc",
788 "description": "",
789 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
790 "egress": "5311c75d-d718-4369-bbda-cdcc6da60fcc",
791 "service_function_parameters": {"correlation": "nsh"},
792 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
793 "id": "c121ebdd-7f2d-4213-b933-3325298a6966",
794 "name": "osm_sfi1",
795 },
796 ]
797 }
798
799 # call the VIM connector
800 result = self.vimconn.get_sfi("c121ebdd-7f2d-4213-b933-3325298a6966")
801
802 # assert the VIM connector called OpenStack with the expected filter
803 list_sfc_port_pairs.assert_called_with(
804 id="c121ebdd-7f2d-4213-b933-3325298a6966"
805 )
806 # assert the VIM connector successfully returned the OpenStack result
807 self.assertEqual(
808 result,
809 {
810 "ingress_ports": ["5311c75d-d718-4369-bbda-cdcc6da60fcc"],
811 "egress_ports": ["5311c75d-d718-4369-bbda-cdcc6da60fcc"],
812 "sfc_encap": True,
813 "description": "",
814 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
815 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
816 "id": "c121ebdd-7f2d-4213-b933-3325298a6966",
817 "name": "osm_sfi1",
818 },
819 )
820
821 @mock.patch.object(Client, "list_sfc_port_pairs")
822 def test_get_sfi_many_results(self, list_sfc_port_pairs):
823 # what OpenStack is assumed to return to the VIM connector
824 list_sfc_port_pairs.return_value = {
825 "port_pairs": [
826 {
827 "ingress": "5311c75d-d718-4369-bbda-cdcc6da60fcc",
828 "description": "",
829 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
830 "egress": "5311c75d-d718-4369-bbda-cdcc6da60fcc",
831 "service_function_parameters": {"correlation": "nsh"},
832 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
833 "id": "c121ebdd-7f2d-4213-b933-3325298a6966",
834 "name": "osm_sfi1",
835 },
836 {
837 "ingress": "5311c75d-d718-4369-bbda-cdcc6da60fcc",
838 "description": "",
839 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
840 "egress": "5311c75d-d718-4369-bbda-cdcc6da60fcc",
841 "service_function_parameters": {"correlation": "nsh"},
842 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
843 "id": "c0436d92-82db-11e7-8f9c-5fa535f1261f",
844 "name": "osm_sfi2",
845 },
846 ]
847 }
848
849 # call the VIM connector
850 self.assertRaises(
851 vimconn.VimConnConflictException,
852 self.vimconn.get_sfi,
853 "c0436d92-82db-11e7-8f9c-5fa535f1261f",
854 )
855
856 # assert that VIM connector called OpenStack with the expected filter
857 list_sfc_port_pairs.assert_called_with(
858 id="c0436d92-82db-11e7-8f9c-5fa535f1261f"
859 )
860
861 @mock.patch.object(Client, "list_sfc_port_pairs")
862 def test_get_sfi_no_results(self, list_sfc_port_pairs):
863 # what OpenStack is assumed to return to the VIM connector
864 list_sfc_port_pairs.return_value = {"port_pairs": []}
865
866 # call the VIM connector
867 self.assertRaises(
868 vimconn.VimConnNotFoundException,
869 self.vimconn.get_sfi,
870 "b22892fc-82d9-11e7-ae85-0fea6a3b3757",
871 )
872
873 # assert that VIM connector called OpenStack with the expected filter
874 list_sfc_port_pairs.assert_called_with(
875 id="b22892fc-82d9-11e7-ae85-0fea6a3b3757"
876 )
877
878 @mock.patch.object(Client, "list_sfc_port_pair_groups")
879 def test_get_sf(self, list_sfc_port_pair_groups):
880 # what OpenStack is assumed to return to the VIM connector
881 list_sfc_port_pair_groups.return_value = {
882 "port_pair_groups": [
883 {
884 "port_pairs": ["08fbdbb0-82d6-11e7-ad95-9bb52fbec2f2"],
885 "description": "",
886 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
887 "port_pair_group_parameters": {},
888 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
889 "id": "aabba8a6-82d9-11e7-a18a-d3c7719b742d",
890 "name": "osm_sf1",
891 }
892 ]
893 }
894
895 # call the VIM connector
896 result = self.vimconn.get_sf("b22892fc-82d9-11e7-ae85-0fea6a3b3757")
897
898 # assert that VIM connector called OpenStack with the expected filter
899 list_sfc_port_pair_groups.assert_called_with(
900 id="b22892fc-82d9-11e7-ae85-0fea6a3b3757"
901 )
902 # assert that VIM connector successfully returned the OpenStack result
903 self.assertEqual(
904 result,
905 {
906 "description": "",
907 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
908 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
909 "sfis": ["08fbdbb0-82d6-11e7-ad95-9bb52fbec2f2"],
910 "id": "aabba8a6-82d9-11e7-a18a-d3c7719b742d",
911 "name": "osm_sf1",
912 },
913 )
914
915 @mock.patch.object(Client, "list_sfc_port_pair_groups")
916 def test_get_sf_many_results(self, list_sfc_port_pair_groups):
917 # what OpenStack is assumed to return to the VIM connector
918 list_sfc_port_pair_groups.return_value = {
919 "port_pair_groups": [
920 {
921 "port_pairs": ["08fbdbb0-82d6-11e7-ad95-9bb52fbec2f2"],
922 "description": "",
923 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
924 "port_pair_group_parameters": {},
925 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
926 "id": "aabba8a6-82d9-11e7-a18a-d3c7719b742d",
927 "name": "osm_sf1",
928 },
929 {
930 "port_pairs": ["0d63799c-82d6-11e7-8deb-a746bb3ae9f5"],
931 "description": "",
932 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
933 "port_pair_group_parameters": {},
934 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
935 "id": "b22892fc-82d9-11e7-ae85-0fea6a3b3757",
936 "name": "osm_sf2",
937 },
938 ]
939 }
940
941 # call the VIM connector
942 self.assertRaises(
943 vimconn.VimConnConflictException,
944 self.vimconn.get_sf,
945 "b22892fc-82d9-11e7-ae85-0fea6a3b3757",
946 )
947
948 # assert that VIM connector called OpenStack with the expected filter
949 list_sfc_port_pair_groups.assert_called_with(
950 id="b22892fc-82d9-11e7-ae85-0fea6a3b3757"
951 )
952
953 @mock.patch.object(Client, "list_sfc_port_pair_groups")
954 def test_get_sf_no_results(self, list_sfc_port_pair_groups):
955 # what OpenStack is assumed to return to the VIM connector
956 list_sfc_port_pair_groups.return_value = {"port_pair_groups": []}
957
958 # call the VIM connector
959 self.assertRaises(
960 vimconn.VimConnNotFoundException,
961 self.vimconn.get_sf,
962 "b22892fc-82d9-11e7-ae85-0fea6a3b3757",
963 )
964
965 # assert that VIM connector called OpenStack with the expected filter
966 list_sfc_port_pair_groups.assert_called_with(
967 id="b22892fc-82d9-11e7-ae85-0fea6a3b3757"
968 )
969
970 @mock.patch.object(Client, "list_sfc_port_chains")
971 def test_get_sfp(self, list_sfc_port_chains):
972 # what OpenStack is assumed to return to the VIM connector
973 list_sfc_port_chains.return_value = {
974 "port_chains": [
975 {
976 "port_pair_groups": ["7d8e3bf8-82d6-11e7-a032-8ff028839d25"],
977 "flow_classifiers": ["1333c2f4-82d7-11e7-a5df-9327f33d104e"],
978 "description": "",
979 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
980 "chain_parameters": {"correlation": "nsh"},
981 "chain_id": 40,
982 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
983 "id": "821bc9be-82d7-11e7-8ce3-23a08a27ab47",
984 "name": "osm_sfp1",
985 }
986 ]
987 }
988
989 # call the VIM connector
990 result = self.vimconn.get_sfp("821bc9be-82d7-11e7-8ce3-23a08a27ab47")
991
992 # assert that VIM connector called OpenStack with the expected filter
993 list_sfc_port_chains.assert_called_with(
994 id="821bc9be-82d7-11e7-8ce3-23a08a27ab47"
995 )
996 # assert that VIM connector successfully returned the OpenStack result
997 self.assertEqual(
998 result,
999 {
1000 "service_functions": ["7d8e3bf8-82d6-11e7-a032-8ff028839d25"],
1001 "classifications": ["1333c2f4-82d7-11e7-a5df-9327f33d104e"],
1002 "description": "",
1003 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
1004 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
1005 "sfc_encap": True,
1006 "spi": 40,
1007 "id": "821bc9be-82d7-11e7-8ce3-23a08a27ab47",
1008 "name": "osm_sfp1",
1009 },
1010 )
1011
1012 @mock.patch.object(Client, "list_sfc_port_chains")
1013 def test_get_sfp_many_results(self, list_sfc_port_chains):
1014 # what OpenStack is assumed to return to the VIM connector
1015 list_sfc_port_chains.return_value = {
1016 "port_chains": [
1017 {
1018 "port_pair_groups": ["7d8e3bf8-82d6-11e7-a032-8ff028839d25"],
1019 "flow_classifiers": ["1333c2f4-82d7-11e7-a5df-9327f33d104e"],
1020 "description": "",
1021 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
1022 "chain_parameters": {"correlation": "nsh"},
1023 "chain_id": 40,
1024 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
1025 "id": "821bc9be-82d7-11e7-8ce3-23a08a27ab47",
1026 "name": "osm_sfp1",
1027 },
1028 {
1029 "port_pair_groups": ["7d8e3bf8-82d6-11e7-a032-8ff028839d25"],
1030 "flow_classifiers": ["1333c2f4-82d7-11e7-a5df-9327f33d104e"],
1031 "description": "",
1032 "tenant_id": "8f3019ef06374fa880a0144ad4bc1d7b",
1033 "chain_parameters": {"correlation": "nsh"},
1034 "chain_id": 50,
1035 "project_id": "8f3019ef06374fa880a0144ad4bc1d7b",
1036 "id": "5d002f38-82de-11e7-a770-f303f11ce66a",
1037 "name": "osm_sfp2",
1038 },
1039 ]
1040 }
1041
1042 # call the VIM connector
1043 self.assertRaises(
1044 vimconn.VimConnConflictException,
1045 self.vimconn.get_sfp,
1046 "5d002f38-82de-11e7-a770-f303f11ce66a",
1047 )
1048
1049 # assert that VIM connector called OpenStack with the expected filter
1050 list_sfc_port_chains.assert_called_with(
1051 id="5d002f38-82de-11e7-a770-f303f11ce66a"
1052 )
1053
1054 @mock.patch.object(Client, "list_sfc_port_chains")
1055 def test_get_sfp_no_results(self, list_sfc_port_chains):
1056 # what OpenStack is assumed to return to the VIM connector
1057 list_sfc_port_chains.return_value = {"port_chains": []}
1058
1059 # call the VIM connector
1060 self.assertRaises(
1061 vimconn.VimConnNotFoundException,
1062 self.vimconn.get_sfp,
1063 "5d002f38-82de-11e7-a770-f303f11ce66a",
1064 )
1065
1066 # assert that VIM connector called OpenStack with the expected filter
1067 list_sfc_port_chains.assert_called_with(
1068 id="5d002f38-82de-11e7-a770-f303f11ce66a"
1069 )
1070
1071 @mock.patch.object(Client, "delete_sfc_flow_classifier")
1072 def test_delete_classification(self, delete_sfc_flow_classifier):
1073 result = self.vimconn.delete_classification(
1074 "638f957c-82df-11e7-b7c8-132706021464"
1075 )
1076 delete_sfc_flow_classifier.assert_called_with(
1077 "638f957c-82df-11e7-b7c8-132706021464"
1078 )
1079 self.assertEqual(result, "638f957c-82df-11e7-b7c8-132706021464")
1080
1081 @mock.patch.object(Client, "delete_sfc_port_pair")
1082 def test_delete_sfi(self, delete_sfc_port_pair):
1083 result = self.vimconn.delete_sfi("638f957c-82df-11e7-b7c8-132706021464")
1084 delete_sfc_port_pair.assert_called_with("638f957c-82df-11e7-b7c8-132706021464")
1085 self.assertEqual(result, "638f957c-82df-11e7-b7c8-132706021464")
1086
1087 @mock.patch.object(Client, "delete_sfc_port_pair_group")
1088 def test_delete_sf(self, delete_sfc_port_pair_group):
1089 result = self.vimconn.delete_sf("638f957c-82df-11e7-b7c8-132706021464")
1090 delete_sfc_port_pair_group.assert_called_with(
1091 "638f957c-82df-11e7-b7c8-132706021464"
1092 )
1093 self.assertEqual(result, "638f957c-82df-11e7-b7c8-132706021464")
1094
1095 @mock.patch.object(Client, "delete_sfc_port_chain")
1096 def test_delete_sfp(self, delete_sfc_port_chain):
1097 result = self.vimconn.delete_sfp("638f957c-82df-11e7-b7c8-132706021464")
1098 delete_sfc_port_chain.assert_called_with("638f957c-82df-11e7-b7c8-132706021464")
1099 self.assertEqual(result, "638f957c-82df-11e7-b7c8-132706021464")
1100
1101
1102 class Status:
1103 def __init__(self, s):
1104 self.status = s
1105
1106 def __str__(self):
1107 return self.status
1108
1109
1110 class CopyingMock(MagicMock):
1111 def __call__(self, *args, **kwargs):
1112 args = deepcopy(args)
1113 kwargs = deepcopy(kwargs)
1114 return super(CopyingMock, self).__call__(*args, **kwargs)
1115
1116
1117 class TestNewVmInstance(unittest.TestCase):
1118 @patch("logging.getLogger", autospec=True)
1119 def setUp(self, mock_logger):
1120 # Instantiate dummy VIM connector so we can test it
1121 # It throws exception because of dummy parameters,
1122 # We are disabling the logging of exception not to print them to console.
1123 mock_logger = logging.getLogger()
1124 mock_logger.disabled = True
1125 self.vimconn = vimconnector(
1126 "123",
1127 "openstackvim",
1128 "456",
1129 "789",
1130 "http://dummy.url",
1131 None,
1132 "user",
1133 "pass",
1134 )
1135 self.vimconn.neutron = CopyingMock()
1136 self.vimconn.nova = CopyingMock()
1137 self.vimconn.cinder = CopyingMock()
1138 self.server = MagicMock(object, autospec=True)
1139 self.server.tenant_id = "408b73-r9cc-5a6a-a270-82cc4811bd4a"
1140 self.server.id = "908b73-e9cc-5a6a-t270-82cc4811bd4a"
1141 self.vimconn.config["security_groups"] = "default"
1142 self.vimconn.config["keypair"] = "my_keypair"
1143 self.vimconn.security_groups_id = "12345"
1144 self.vimconn.nova.api_version.get_string.return_value = "2.32"
1145 self.vimconn.logger = CopyingMock()
1146
1147 @patch.object(vimconnector, "_get_ids_from_name")
1148 def test_prepare_port_dict_security_security_groups_exists_in_config(
1149 self, mock_get_ids
1150 ):
1151 """In VIM config security_groups exists, net port_security is True
1152 no_port_security_extension does not exist.
1153 """
1154 self.vimconn.config = {"security_groups": "example_security_group"}
1155 net = {"port_security": True}
1156 port_dict = {}
1157 result_dict = {"security_groups": "12345"}
1158
1159 self.vimconn._prepare_port_dict_security_groups(net, port_dict)
1160 self.assertDictEqual(result_dict, port_dict)
1161 mock_get_ids.assert_not_called()
1162
1163 @patch.object(vimconnector, "_get_ids_from_name")
1164 def test_prepare_port_dict_security_security_groups_exists_in_config_no_security_groups_id(
1165 self, mock_get_ids
1166 ):
1167 """In VIM config Security_groups exists, net port_security is True, vim security_groups_id does not exist,
1168 no_port_security_extension does not exist.
1169 """
1170 self.vimconn.config = {"security_groups": "example_security_group"}
1171 self.vimconn.security_groups_id = None
1172 net = {"port_security": True}
1173 port_dict = {}
1174 result_dict = {"security_groups": None}
1175
1176 self.vimconn._prepare_port_dict_security_groups(net, port_dict)
1177 self.assertDictEqual(result_dict, port_dict)
1178 mock_get_ids.assert_called()
1179
1180 @patch.object(vimconnector, "_get_ids_from_name")
1181 def test_prepare_port_dict_security_security_groups_exists_security_extension_true_in_config(
1182 self, mock_get_ids
1183 ):
1184 """In VIM config security_groups exists, net port_security is True, in VIM security_groups_id exists,
1185 no_port_security_extension set to True.
1186 """
1187 self.vimconn.config = {
1188 "security_groups": "example_security_group",
1189 "no_port_security_extension": True,
1190 }
1191 net = {"port_security": True}
1192 port_dict = {}
1193 result_dict = {}
1194
1195 self.vimconn._prepare_port_dict_security_groups(net, port_dict)
1196 self.assertDictEqual(result_dict, port_dict)
1197 mock_get_ids.assert_not_called()
1198
1199 @patch.object(vimconnector, "_get_ids_from_name")
1200 def test_prepare_port_dict_security_no_security_groups_in_config(
1201 self, mock_get_ids
1202 ):
1203 """In VIM config security_group does not exist, net port_security True, in VIM security_groups_id exists,
1204 no_port_security_extension does not exist."""
1205 self.vimconn.config = {}
1206 net = {"port_security": True}
1207 port_dict = {}
1208 result_dict = {}
1209
1210 self.vimconn._prepare_port_dict_security_groups(net, port_dict)
1211 self.assertDictEqual(result_dict, port_dict)
1212 mock_get_ids.assert_not_called()
1213
1214 @patch.object(vimconnector, "_get_ids_from_name")
1215 def test_prepare_port_dict_security_no_security_groups_security_extension_true_in_config(
1216 self, mock_get_ids
1217 ):
1218 """Security_group does not exist, net port_security is True, in VIM security_groups_id exists,
1219 no_port_security_extension set to True."""
1220 self.vimconn.config = {"no_port_security_extension": True}
1221 net = {"port_security": True}
1222 port_dict = {}
1223 result_dict = {}
1224
1225 self.vimconn._prepare_port_dict_security_groups(net, port_dict)
1226 self.assertDictEqual(result_dict, port_dict)
1227 mock_get_ids.assert_not_called()
1228
1229 @patch.object(vimconnector, "_get_ids_from_name")
1230 def test_prepare_port_dict_security_security_groups_exists_net_port_security_false(
1231 self, mock_get_ids
1232 ):
1233 """In VIM config security_group exists, net port_security False, security_groups_id exists,
1234 no_port_security_extension does not exist."""
1235 self.vimconn.config = {"security_groups": "example_security_group"}
1236 net = {"port_security": False}
1237 port_dict = {}
1238 result_dict = {}
1239
1240 self.vimconn._prepare_port_dict_security_groups(net, port_dict)
1241 self.assertDictEqual(result_dict, port_dict)
1242 mock_get_ids.assert_not_called()
1243
1244 @patch.object(vimconnector, "_get_ids_from_name")
1245 def test_prepare_port_dict_security_net_port_security_false_port_security_extension_true(
1246 self, mock_get_ids
1247 ):
1248 """In VIM config security_group exists, net port_security False, security_groups_id exists,
1249 no_port_security_extension set to True."""
1250 self.vimconn.config = {
1251 "security_groups": "example_security_group",
1252 "no_port_security_extension": True,
1253 }
1254 net = {"port_security": False}
1255 port_dict = {}
1256 result_dict = {}
1257
1258 self.vimconn._prepare_port_dict_security_groups(net, port_dict)
1259 self.assertDictEqual(result_dict, port_dict)
1260 mock_get_ids.assert_not_called()
1261
1262 def test_prepare_port_dict_binding_net_type_virtual(self):
1263 """net type is virtual."""
1264 net = {"type": "virtual"}
1265 port_dict = {}
1266 result_dict = {}
1267 self.vimconn._prepare_port_dict_binding(net, port_dict)
1268 self.assertDictEqual(result_dict, port_dict)
1269
1270 def test_prepare_port_dict_binding_net_type_vf(self):
1271 """net type is VF, vim_type is not VIO."""
1272 net = {"type": "VF"}
1273 self.vimconn.vim_type = None
1274 port_dict = {}
1275 result_dict = {"binding:vnic_type": "direct"}
1276 self.vimconn._prepare_port_dict_binding(net, port_dict)
1277 self.assertDictEqual(port_dict, result_dict)
1278
1279 def test_prepare_port_dict_binding_net_type_sriov_vim_type_vio(self):
1280 """net type is SR-IOV, vim_type is VIO."""
1281 net = {"type": "SR-IOV"}
1282 self.vimconn.vim_type = "VIO"
1283 port_dict = {}
1284 result_dict = {
1285 "binding:vnic_type": "direct",
1286 "port_security_enabled": False,
1287 "provider_security_groups": [],
1288 "security_groups": [],
1289 }
1290 self.vimconn._prepare_port_dict_binding(net, port_dict)
1291 self.assertDictEqual(port_dict, result_dict)
1292
1293 def test_prepare_port_dict_binding_net_type_passthrough(self):
1294 """net type is pci-passthrough."""
1295 net = {"type": "PCI-PASSTHROUGH"}
1296 port_dict = {}
1297 result_dict = {
1298 "binding:vnic_type": "direct-physical",
1299 }
1300 self.vimconn._prepare_port_dict_binding(net, port_dict)
1301 self.assertDictEqual(port_dict, result_dict)
1302
1303 def test_prepare_port_dict_binding_no_net_type(self):
1304 """net type is missing."""
1305 net = {}
1306 port_dict = {}
1307 with self.assertRaises(VimConnException) as err:
1308 self.vimconn._prepare_port_dict_binding(net, port_dict)
1309 self.assertEqual(str(err.exception), "Type is missing in the network details.")
1310
1311 def test_set_fixed_ip(self):
1312 """new_port has fixed ip."""
1313 net = {}
1314 new_port = {
1315 "port": {
1316 "fixed_ips": [{"ip_address": "10.1.2.3"}, {"ip_address": "20.1.2.3"}]
1317 }
1318 }
1319 result = {"ip": "10.1.2.3"}
1320 self.vimconn._set_fixed_ip(new_port, net)
1321 self.assertDictEqual(net, result)
1322
1323 def test_set_fixed_ip_no_fixed_ip(self):
1324 """new_port does not have fixed ip."""
1325 net = {}
1326 new_port = {"port": {}}
1327 result = {"ip": None}
1328 self.vimconn._set_fixed_ip(new_port, net)
1329 self.assertDictEqual(net, result)
1330
1331 def test_set_fixed_ip_raise_exception(self):
1332 """new_port does not have port details."""
1333 net = {}
1334 new_port = {}
1335 with self.assertRaises(Exception) as err:
1336 self.vimconn._set_fixed_ip(new_port, net)
1337 self.assertEqual(type(err.exception), KeyError)
1338
1339 def test_prepare_port_dict_mac_ip_addr(self):
1340 """mac address and ip address exist."""
1341 net = {
1342 "mac_address": mac_address,
1343 "ip_address": "10.0.1.5",
1344 }
1345 port_dict = {}
1346 result_dict = {
1347 "mac_address": mac_address,
1348 "fixed_ips": [{"ip_address": "10.0.1.5"}],
1349 }
1350 self.vimconn._prepare_port_dict_mac_ip_addr(net, port_dict)
1351 self.assertDictEqual(port_dict, result_dict)
1352
1353 def test_prepare_port_dict_mac_ip_addr_no_mac_and_ip(self):
1354 """mac address and ip address does not exist."""
1355 net = {}
1356 port_dict = {}
1357 result_dict = {}
1358 self.vimconn._prepare_port_dict_mac_ip_addr(net, port_dict)
1359 self.assertDictEqual(port_dict, result_dict)
1360
1361 def test_create_new_port(self):
1362 """new port has id and mac address."""
1363 new_port = {
1364 "port": {
1365 "id": port_id,
1366 "mac_address": mac_address,
1367 },
1368 }
1369 self.vimconn.neutron.create_port.return_value = new_port
1370 net, port_dict, created_items = {}, {}, {}
1371 expected_result = new_port
1372 expected_net = {
1373 "mac_adress": mac_address,
1374 "vim_id": port_id,
1375 }
1376 expected_created_items = {f"port:{port_id}": True}
1377 result = self.vimconn._create_new_port(port_dict, created_items, net)
1378 self.assertDictEqual(result, expected_result)
1379 self.assertEqual(net, expected_net)
1380 self.assertEqual(created_items, expected_created_items)
1381 self.vimconn.neutron.create_port.assert_called_once_with({"port": port_dict})
1382
1383 def test_create_new_port_without_mac_or_id(self):
1384 """new port does not have mac address or ID."""
1385 new_port = {}
1386 self.vimconn.neutron.create_port.return_value = new_port
1387 net, port_dict, created_items = {}, {}, {}
1388 with self.assertRaises(KeyError):
1389 self.vimconn._create_new_port(port_dict, created_items, net)
1390 self.vimconn.neutron.create_port.assert_called_once_with({"port": port_dict})
1391
1392 def test_create_new_port_neutron_create_port_raises_exception(self):
1393 """Neutron create port raises exception."""
1394 self.vimconn.neutron.create_port.side_effect = VimConnException(
1395 "New port is not created."
1396 )
1397 net, port_dict, created_items = {}, {}, {}
1398 with self.assertRaises(VimConnException):
1399 self.vimconn._create_new_port(port_dict, created_items, net)
1400 self.vimconn.neutron.create_port.assert_called_once_with({"port": port_dict})
1401
1402 @patch.object(vimconnector, "_prepare_port_dict_security_groups")
1403 @patch.object(vimconnector, "_prepare_port_dict_binding")
1404 @patch.object(vimconnector, "_prepare_port_dict_mac_ip_addr")
1405 @patch.object(vimconnector, "_create_new_port")
1406 @patch.object(vimconnector, "_set_fixed_ip")
1407 def test_create_port(
1408 self,
1409 mock_set_fixed_ip,
1410 mock_create_new_port,
1411 mock_prepare_port_dict_mac_ip_addr,
1412 mock_prepare_port_dict_binding,
1413 mock_prepare_port_dict_security_groups,
1414 ):
1415 """Net has name, type, net-id."""
1416
1417 net = {
1418 "net_id": net_id,
1419 "name": "management",
1420 "type": "virtual",
1421 }
1422 created_items = {}
1423 new_port = {
1424 "port": {
1425 "id": net_id,
1426 "mac_address": mac_address,
1427 "name": "management",
1428 "fixed_ips": [{"ip_address": ip_addr1}],
1429 },
1430 }
1431 mock_create_new_port.return_value = new_port
1432 expected_port = {
1433 "port-id": net_id,
1434 "tag": "management",
1435 }
1436 port_dict = {
1437 "network_id": net_id,
1438 "name": "management",
1439 "admin_state_up": True,
1440 }
1441
1442 new_port_result, port_result = self.vimconn._create_port(
1443 net, name, created_items
1444 )
1445
1446 self.assertDictEqual(new_port_result, new_port)
1447 self.assertDictEqual(port_result, expected_port)
1448
1449 mock_prepare_port_dict_security_groups.assert_called_once_with(net, port_dict)
1450 mock_prepare_port_dict_binding.assert_called_once_with(net, port_dict)
1451 mock_prepare_port_dict_mac_ip_addr.assert_called_once_with(net, port_dict)
1452 mock_create_new_port.assert_called_once_with(port_dict, created_items, net)
1453 mock_set_fixed_ip.assert_called_once_with(new_port, net)
1454
1455 @patch.object(vimconnector, "_prepare_port_dict_security_groups")
1456 @patch.object(vimconnector, "_prepare_port_dict_binding")
1457 @patch.object(vimconnector, "_prepare_port_dict_mac_ip_addr")
1458 @patch.object(vimconnector, "_create_new_port")
1459 @patch.object(vimconnector, "_set_fixed_ip")
1460 def test_create_port_no_port_name(
1461 self,
1462 mock_set_fixed_ip,
1463 mock_create_new_port,
1464 mock_prepare_port_dict_mac_ip_addr,
1465 mock_prepare_port_dict_binding,
1466 mock_prepare_port_dict_security_groups,
1467 ):
1468 """Net has no name."""
1469 net = {
1470 "net_id": net_id,
1471 "type": "virtual",
1472 }
1473 created_items = {}
1474 new_port = {
1475 "port": {
1476 "id": net_id,
1477 "mac_address": mac_address,
1478 "name": name,
1479 "fixed_ips": [{"ip_address": ip_addr1}],
1480 },
1481 }
1482 mock_create_new_port.return_value = new_port
1483 expected_port = {
1484 "port-id": net_id,
1485 "tag": name,
1486 }
1487 port_dict = {
1488 "network_id": net_id,
1489 "admin_state_up": True,
1490 "name": name,
1491 }
1492
1493 new_port_result, port_result = self.vimconn._create_port(
1494 net, name, created_items
1495 )
1496
1497 self.assertDictEqual(new_port_result, new_port)
1498 self.assertDictEqual(port_result, expected_port)
1499
1500 mock_prepare_port_dict_security_groups.assert_called_once_with(net, port_dict)
1501 mock_prepare_port_dict_binding.assert_called_once_with(net, port_dict)
1502 mock_prepare_port_dict_mac_ip_addr.assert_called_once_with(net, port_dict)
1503 mock_create_new_port.assert_called_once_with(port_dict, created_items, net)
1504 mock_set_fixed_ip.assert_called_once_with(new_port, net)
1505
1506 @patch.object(vimconnector, "_prepare_port_dict_security_groups")
1507 @patch.object(vimconnector, "_prepare_port_dict_binding")
1508 @patch.object(vimconnector, "_prepare_port_dict_mac_ip_addr")
1509 @patch.object(vimconnector, "_create_new_port")
1510 @patch.object(vimconnector, "_set_fixed_ip")
1511 def test_create_port_nova_api_version_smaller_than_232(
1512 self,
1513 mock_set_fixed_ip,
1514 mock_create_new_port,
1515 mock_prepare_port_dict_mac_ip_addr,
1516 mock_prepare_port_dict_binding,
1517 mock_prepare_port_dict_security_groups,
1518 ):
1519 """Nova api version is smaller than 2.32."""
1520 self.vimconn.nova.api_version.get_string.return_value = "2.30"
1521 net = {
1522 "net_id": net_id,
1523 "type": "virtual",
1524 }
1525 created_items = {}
1526 new_port = {
1527 "port": {
1528 "id": net_id,
1529 "mac_address": mac_address,
1530 "name": name,
1531 "fixed_ips": [{"ip_address": ip_addr1}],
1532 },
1533 }
1534 mock_create_new_port.return_value = new_port
1535 expected_port = {
1536 "port-id": net_id,
1537 }
1538 port_dict = {
1539 "network_id": net_id,
1540 "admin_state_up": True,
1541 "name": name,
1542 }
1543
1544 new_port_result, port_result = self.vimconn._create_port(
1545 net, name, created_items
1546 )
1547
1548 self.assertDictEqual(new_port_result, new_port)
1549 self.assertDictEqual(port_result, expected_port)
1550
1551 mock_prepare_port_dict_security_groups.assert_called_once_with(net, port_dict)
1552 mock_prepare_port_dict_binding.assert_called_once_with(net, port_dict)
1553 mock_prepare_port_dict_mac_ip_addr.assert_called_once_with(net, port_dict)
1554 mock_create_new_port.assert_called_once_with(port_dict, created_items, net)
1555 mock_set_fixed_ip.assert_called_once_with(new_port, net)
1556
1557 @patch.object(vimconnector, "_prepare_port_dict_security_groups")
1558 @patch.object(vimconnector, "_prepare_port_dict_binding")
1559 @patch.object(vimconnector, "_prepare_port_dict_mac_ip_addr")
1560 @patch.object(vimconnector, "_create_new_port")
1561 @patch.object(vimconnector, "_set_fixed_ip")
1562 def test_create_port_create_new_port_raise_exception(
1563 self,
1564 mock_set_fixed_ip,
1565 mock_create_new_port,
1566 mock_prepare_port_dict_mac_ip_addr,
1567 mock_prepare_port_dict_binding,
1568 mock_prepare_port_dict_security_groups,
1569 ):
1570 """_create_new_port method raises exception."""
1571 net = {
1572 "net_id": net_id,
1573 "type": "virtual",
1574 }
1575 created_items = {}
1576 mock_create_new_port.side_effect = Exception
1577 port_dict = {
1578 "network_id": net_id,
1579 "admin_state_up": True,
1580 "name": name,
1581 }
1582
1583 with self.assertRaises(Exception):
1584 self.vimconn._create_port(net, name, created_items)
1585
1586 mock_prepare_port_dict_security_groups.assert_called_once_with(net, port_dict)
1587 mock_prepare_port_dict_binding.assert_called_once_with(net, port_dict)
1588 mock_prepare_port_dict_mac_ip_addr.assert_called_once_with(net, port_dict)
1589 mock_create_new_port.assert_called_once_with(port_dict, created_items, net)
1590 mock_set_fixed_ip.assert_not_called()
1591
1592 @patch.object(vimconnector, "_prepare_port_dict_security_groups")
1593 @patch.object(vimconnector, "_prepare_port_dict_binding")
1594 @patch.object(vimconnector, "_prepare_port_dict_mac_ip_addr")
1595 @patch.object(vimconnector, "_create_new_port")
1596 @patch.object(vimconnector, "_set_fixed_ip")
1597 def test_create_port_create_sec_groups_raises_exception(
1598 self,
1599 mock_set_fixed_ip,
1600 mock_create_new_port,
1601 mock_prepare_port_dict_mac_ip_addr,
1602 mock_prepare_port_dict_binding,
1603 mock_prepare_port_dict_security_groups,
1604 ):
1605 """_prepare_port_dict_security_groups method raises exception."""
1606 net = {
1607 "net_id": net_id,
1608 "type": "virtual",
1609 }
1610 created_items = {}
1611 mock_prepare_port_dict_security_groups.side_effect = Exception
1612 port_dict = {
1613 "network_id": net_id,
1614 "admin_state_up": True,
1615 "name": name,
1616 }
1617
1618 with self.assertRaises(Exception):
1619 self.vimconn._create_port(net, name, created_items)
1620
1621 mock_prepare_port_dict_security_groups.assert_called_once_with(net, port_dict)
1622
1623 mock_prepare_port_dict_binding.assert_not_called()
1624 mock_prepare_port_dict_mac_ip_addr.assert_not_called()
1625 mock_create_new_port.assert_not_called()
1626 mock_set_fixed_ip.assert_not_called()
1627
1628 @patch.object(vimconnector, "_prepare_port_dict_security_groups")
1629 @patch.object(vimconnector, "_prepare_port_dict_binding")
1630 @patch.object(vimconnector, "_prepare_port_dict_mac_ip_addr")
1631 @patch.object(vimconnector, "_create_new_port")
1632 @patch.object(vimconnector, "_set_fixed_ip")
1633 def test_create_port_create_port_dict_binding_raise_exception(
1634 self,
1635 mock_set_fixed_ip,
1636 mock_create_new_port,
1637 mock_prepare_port_dict_mac_ip_addr,
1638 mock_prepare_port_dict_binding,
1639 mock_prepare_port_dict_security_groups,
1640 ):
1641 """_prepare_port_dict_binding method raises exception."""
1642
1643 net = {
1644 "net_id": net_id,
1645 "type": "virtual",
1646 }
1647 created_items = {}
1648 mock_prepare_port_dict_binding.side_effect = Exception
1649 port_dict = {
1650 "network_id": net_id,
1651 "admin_state_up": True,
1652 "name": name,
1653 }
1654
1655 with self.assertRaises(Exception):
1656 self.vimconn._create_port(net, name, created_items)
1657
1658 mock_prepare_port_dict_security_groups.assert_called_once_with(net, port_dict)
1659
1660 mock_prepare_port_dict_binding.assert_called_once_with(net, port_dict)
1661
1662 mock_prepare_port_dict_mac_ip_addr.assert_not_called()
1663 mock_create_new_port.assert_not_called()
1664 mock_set_fixed_ip.assert_not_called()
1665
1666 @patch.object(vimconnector, "_prepare_port_dict_security_groups")
1667 @patch.object(vimconnector, "_prepare_port_dict_binding")
1668 @patch.object(vimconnector, "_prepare_port_dict_mac_ip_addr")
1669 @patch.object(vimconnector, "_create_new_port")
1670 @patch.object(vimconnector, "_set_fixed_ip")
1671 def test_create_port_create_port_mac_ip_addr_raise_exception(
1672 self,
1673 mock_set_fixed_ip,
1674 mock_create_new_port,
1675 mock_prepare_port_dict_mac_ip_addr,
1676 mock_prepare_port_dict_binding,
1677 mock_prepare_port_dict_security_groups,
1678 ):
1679 """prepare_port_dict_mac_ip_addr method raises exception."""
1680 net = {
1681 "net_id": net_id,
1682 "type": "virtual",
1683 }
1684 created_items = {}
1685 mock_prepare_port_dict_mac_ip_addr.side_effect = Exception
1686 port_dict = {
1687 "network_id": net_id,
1688 "admin_state_up": True,
1689 "name": name,
1690 }
1691
1692 with self.assertRaises(Exception):
1693 self.vimconn._create_port(net, name, created_items)
1694
1695 mock_prepare_port_dict_security_groups.assert_called_once_with(net, port_dict)
1696 mock_prepare_port_dict_binding.assert_called_once_with(net, port_dict)
1697 mock_prepare_port_dict_mac_ip_addr.assert_called_once_with(net, port_dict)
1698
1699 mock_create_new_port.assert_not_called()
1700 mock_set_fixed_ip.assert_not_called()
1701
1702 @patch.object(vimconnector, "_prepare_port_dict_security_groups")
1703 @patch.object(vimconnector, "_prepare_port_dict_binding")
1704 @patch.object(vimconnector, "_prepare_port_dict_mac_ip_addr")
1705 @patch.object(vimconnector, "_create_new_port")
1706 @patch.object(vimconnector, "_set_fixed_ip")
1707 def test_create_port_create_port_set_fixed_ip_raise_exception(
1708 self,
1709 mock_set_fixed_ip,
1710 mock_create_new_port,
1711 mock_prepare_port_dict_mac_ip_addr,
1712 mock_prepare_port_dict_binding,
1713 mock_prepare_port_dict_security_groups,
1714 ):
1715 """_set_fixed_ip method raises exception."""
1716 net = {
1717 "net_id": net_id,
1718 "type": "virtual",
1719 }
1720 created_items = {}
1721 mock_set_fixed_ip.side_effect = VimConnException(
1722 "Port detail is missing in new_port."
1723 )
1724 port_dict = {
1725 "network_id": net_id,
1726 "admin_state_up": True,
1727 "name": name,
1728 }
1729 new_port = {
1730 "port": {
1731 "id": net_id,
1732 "mac_address": mac_address,
1733 "name": name,
1734 "fixed_ips": [{"ip_address": ip_addr1}],
1735 },
1736 }
1737 mock_create_new_port.return_value = new_port
1738
1739 with self.assertRaises(VimConnException):
1740 self.vimconn._create_port(net, name, created_items)
1741
1742 mock_prepare_port_dict_security_groups.assert_called_once_with(net, port_dict)
1743 mock_prepare_port_dict_binding.assert_called_once_with(net, port_dict)
1744 mock_prepare_port_dict_mac_ip_addr.assert_called_once_with(net, port_dict)
1745 mock_create_new_port.assert_called_once_with(port_dict, created_items, net)
1746 mock_set_fixed_ip.assert_called_once_with(new_port, net)
1747
1748 @patch.object(vimconnector, "_reload_connection")
1749 @patch.object(vimconnector, "_create_port")
1750 def test_prepare_network_for_vm_instance_no_net_id(
1751 self, mock_create_port, mock_reload_connection
1752 ):
1753 """Nets do not have net_id"""
1754 mock_reload_connection.side_effect = None
1755 created_items = {}
1756 net_list = [
1757 {
1758 "use": "mgmt",
1759 "port_security": False,
1760 "exit_on_floating_ip_error": False,
1761 "port_security_disable_strategy": "full",
1762 },
1763 {
1764 "port_security": True,
1765 "exit_on_floating_ip_error": False,
1766 "floating_ip": True,
1767 },
1768 ]
1769 net_list_vim = []
1770 external_network, no_secured_ports = [], []
1771 expected_external_network, expected_no_secured_ports = [], []
1772 expected_net_list_vim = []
1773
1774 self.vimconn._prepare_network_for_vminstance(
1775 name,
1776 net_list,
1777 created_items,
1778 net_list_vim,
1779 external_network,
1780 no_secured_ports,
1781 )
1782 self.assertEqual(expected_net_list_vim, net_list_vim)
1783 self.assertEqual(external_network, expected_external_network)
1784 self.assertEqual(expected_no_secured_ports, no_secured_ports)
1785
1786 mock_create_port.assert_not_called()
1787
1788 @patch.object(vimconnector, "_reload_connection")
1789 @patch.object(vimconnector, "_create_port")
1790 def test_prepare_network_for_vm_instance_empty_net_list(
1791 self, mock_create_port, mock_reload_connection
1792 ):
1793 """Net list is empty."""
1794 mock_reload_connection.side_effect = None
1795 created_items = {}
1796 net_list_vim = []
1797 external_network, no_secured_ports = [], []
1798 expected_external_network, expected_no_secured_ports = [], []
1799 expected_net_list_vim = []
1800
1801 self.vimconn._prepare_network_for_vminstance(
1802 name,
1803 net_list,
1804 created_items,
1805 net_list_vim,
1806 external_network,
1807 no_secured_ports,
1808 )
1809 self.assertEqual(expected_net_list_vim, net_list_vim)
1810 self.assertEqual(external_network, expected_external_network)
1811 self.assertEqual(expected_no_secured_ports, no_secured_ports)
1812
1813 mock_create_port.assert_not_called()
1814
1815 @patch.object(vimconnector, "_reload_connection")
1816 @patch.object(vimconnector, "_create_port")
1817 def test_prepare_network_for_vm_instance_use_floating_ip_false_mgmt_net(
1818 self, mock_create_port, mock_reload_connection
1819 ):
1820 """Nets have net-id, floating_ip False, mgmt network."""
1821 mock_reload_connection.side_effect = None
1822 created_items = {}
1823 net_list = [
1824 {
1825 "net_id": net2_id,
1826 "floating_ip": False,
1827 "use": "mgmt",
1828 }
1829 ]
1830 net_list_vim = []
1831 mock_create_port.side_effect = [
1832 (
1833 {
1834 "port": {
1835 "id": port2_id,
1836 "mac_address": mac_address,
1837 "name": name,
1838 },
1839 },
1840 {"port-dict": port2_id},
1841 ),
1842 ]
1843 external_network, no_secured_ports = [], []
1844 expected_external_network, expected_no_secured_ports = [], []
1845 expected_net_list_vim = [{"port-dict": port2_id}]
1846 self.vimconn._prepare_network_for_vminstance(
1847 name,
1848 net_list,
1849 created_items,
1850 net_list_vim,
1851 external_network,
1852 no_secured_ports,
1853 )
1854 self.assertEqual(expected_net_list_vim, net_list_vim)
1855 self.assertEqual(external_network, expected_external_network)
1856 self.assertEqual(expected_no_secured_ports, no_secured_ports)
1857
1858 mock_create_port.assert_called_once_with(
1859 {
1860 "net_id": net2_id,
1861 "floating_ip": False,
1862 "use": "mgmt",
1863 },
1864 name,
1865 created_items,
1866 )
1867
1868 @patch.object(vimconnector, "_reload_connection")
1869 def test_prepare_network_for_vm_instance_mgmt_net_net_port_security_and_floating_ip_true(
1870 self, mock_reload_connection
1871 ):
1872 """Nets have net-id, use_floating_ip False in VIM config, mgmt network, net floating_ip is True."""
1873 self.vimconn.config["use_floating_ip"] = False
1874 mock_create_port = CopyingMock()
1875 mock_reload_connection.side_effect = None
1876 created_items = {}
1877 net_list = [
1878 {
1879 "net_id": net2_id,
1880 "floating_ip": True,
1881 "use": "mgmt",
1882 }
1883 ]
1884 net_list_vim = []
1885 mock_create_port.side_effect = [
1886 (
1887 {
1888 "port": {
1889 "id": port2_id,
1890 "mac_address": mac_address,
1891 "name": name,
1892 },
1893 },
1894 {"port-dict": port2_id},
1895 ),
1896 ]
1897 external_network, no_secured_ports = [], []
1898 expected_external_network = [
1899 {
1900 "net_id": net2_id,
1901 "floating_ip": True,
1902 "use": "mgmt",
1903 "exit_on_floating_ip_error": True,
1904 },
1905 ]
1906 expected_no_secured_ports = []
1907 expected_net_list_vim = [{"port-dict": port2_id}]
1908 with patch.object(vimconnector, "_create_port", mock_create_port):
1909 self.vimconn._prepare_network_for_vminstance(
1910 name,
1911 net_list,
1912 created_items,
1913 net_list_vim,
1914 external_network,
1915 no_secured_ports,
1916 )
1917 self.assertEqual(expected_net_list_vim, net_list_vim)
1918 self.assertEqual(external_network, expected_external_network)
1919 self.assertEqual(expected_no_secured_ports, no_secured_ports)
1920
1921 mock_create_port.assert_called_once_with(
1922 {
1923 "net_id": net2_id,
1924 "floating_ip": True,
1925 "use": "mgmt",
1926 },
1927 name,
1928 created_items,
1929 )
1930
1931 @patch.object(vimconnector, "_reload_connection")
1932 def test_prepare_network_for_vm_instance_use_floating_ip_true_mgmt_net_port_security_false(
1933 self, mock_reload_connection
1934 ):
1935 """Nets have net-id, use_floating_ip is True in VIM config, mgmt network, net port security is False."""
1936 mock_create_port = CopyingMock()
1937 self.vimconn.config["use_floating_ip"] = True
1938 self.vimconn.config["no_port_security_extension"] = False
1939 mock_reload_connection.side_effect = None
1940 created_items = {}
1941
1942 net_list = [
1943 {
1944 "net_id": net2_id,
1945 "use": "mgmt",
1946 "port_security": False,
1947 "exit_on_floating_ip_error": False,
1948 "port_security_disable_strategy": "full",
1949 }
1950 ]
1951 net_list_vim = []
1952 mock_create_port.side_effect = [
1953 (
1954 {
1955 "port": {
1956 "id": port2_id,
1957 "mac_address": mac_address,
1958 "name": name,
1959 },
1960 },
1961 {"port-dict": port2_id},
1962 ),
1963 ]
1964 external_network, no_secured_ports = [], []
1965 expected_external_network = [
1966 {
1967 "net_id": net2_id,
1968 "use": "mgmt",
1969 "port_security": False,
1970 "exit_on_floating_ip_error": False,
1971 "port_security_disable_strategy": "full",
1972 "floating_ip": True,
1973 },
1974 ]
1975 expected_no_secured_ports = [(port2_id, "full")]
1976 expected_net_list_vim = [{"port-dict": port2_id}]
1977 with patch.object(vimconnector, "_create_port", mock_create_port):
1978 self.vimconn._prepare_network_for_vminstance(
1979 name,
1980 net_list,
1981 created_items,
1982 net_list_vim,
1983 external_network,
1984 no_secured_ports,
1985 )
1986
1987 mock_create_port.assert_called_once_with(
1988 {
1989 "net_id": net2_id,
1990 "use": "mgmt",
1991 "port_security": False,
1992 "exit_on_floating_ip_error": False,
1993 "port_security_disable_strategy": "full",
1994 },
1995 name,
1996 created_items,
1997 )
1998 self.assertEqual(expected_net_list_vim, net_list_vim)
1999 self.assertEqual(external_network, expected_external_network)
2000 self.assertEqual(expected_no_secured_ports, no_secured_ports)
2001
2002 @patch.object(vimconnector, "_reload_connection")
2003 def test_prepare_network_for_vm_instance_use_fip_true_non_mgmt_net_port_security_false(
2004 self, mock_reload_connection
2005 ):
2006 """Nets have net-id, use_floating_ip True in VIM config, non-mgmt network, port security is False."""
2007 mock_create_port = CopyingMock()
2008 self.vimconn.config["use_floating_ip"] = True
2009 self.vimconn.config["no_port_security_extension"] = False
2010 mock_reload_connection.side_effect = None
2011 created_items = {}
2012
2013 net_list = [
2014 {
2015 "net_id": net2_id,
2016 "use": "other",
2017 "port_security": False,
2018 "port_security_disable_strategy": "full",
2019 }
2020 ]
2021 net_list_vim = []
2022 mock_create_port.side_effect = [
2023 (
2024 {
2025 "port": {
2026 "id": port2_id,
2027 "mac_address": mac_address,
2028 "name": name,
2029 },
2030 },
2031 {"port-dict": port2_id},
2032 ),
2033 ]
2034 external_network, no_secured_ports = [], []
2035 expected_external_network = []
2036 expected_no_secured_ports = [(port2_id, "full")]
2037 expected_net_list_vim = [{"port-dict": port2_id}]
2038 with patch.object(vimconnector, "_create_port", mock_create_port):
2039 self.vimconn._prepare_network_for_vminstance(
2040 name,
2041 net_list,
2042 created_items,
2043 net_list_vim,
2044 external_network,
2045 no_secured_ports,
2046 )
2047
2048 mock_create_port.assert_called_once_with(
2049 {
2050 "net_id": net2_id,
2051 "use": "other",
2052 "port_security": False,
2053 "port_security_disable_strategy": "full",
2054 },
2055 name,
2056 created_items,
2057 )
2058 self.assertEqual(expected_net_list_vim, net_list_vim)
2059 self.assertEqual(external_network, expected_external_network)
2060 self.assertEqual(expected_no_secured_ports, no_secured_ports)
2061
2062 @patch.object(vimconnector, "_reload_connection")
2063 def test_prepare_network_for_vm_instance_use_fip_true_non_mgmt_net_port_security_true(
2064 self, mock_reload_connection
2065 ):
2066 """Nets have net-id, use_floating_ip is True in VIM config, non-mgmt network, net port security is True."""
2067 mock_create_port = CopyingMock()
2068 self.vimconn.config["use_floating_ip"] = True
2069 self.vimconn.config["no_port_security_extension"] = True
2070 mock_reload_connection.side_effect = None
2071 created_items = {}
2072
2073 net_list = [
2074 {
2075 "net_id": net2_id,
2076 "use": "other",
2077 "port_security": True,
2078 "port_security_disable_strategy": "full",
2079 }
2080 ]
2081 net_list_vim = []
2082 mock_create_port.side_effect = [
2083 (
2084 {
2085 "port": {
2086 "id": port2_id,
2087 "mac_address": mac_address,
2088 "name": name,
2089 },
2090 },
2091 {"port-dict": port2_id},
2092 ),
2093 ]
2094 external_network, no_secured_ports = [], []
2095 expected_external_network = []
2096 expected_no_secured_ports = []
2097 expected_net_list_vim = [{"port-dict": port2_id}]
2098 with patch.object(vimconnector, "_create_port", mock_create_port):
2099 self.vimconn._prepare_network_for_vminstance(
2100 name,
2101 net_list,
2102 created_items,
2103 net_list_vim,
2104 external_network,
2105 no_secured_ports,
2106 )
2107
2108 mock_create_port.assert_called_once_with(
2109 {
2110 "net_id": net2_id,
2111 "use": "other",
2112 "port_security": True,
2113 "port_security_disable_strategy": "full",
2114 },
2115 name,
2116 created_items,
2117 )
2118 self.assertEqual(expected_net_list_vim, net_list_vim)
2119 self.assertEqual(external_network, expected_external_network)
2120 self.assertEqual(expected_no_secured_ports, no_secured_ports)
2121
2122 @patch.object(vimconnector, "_reload_connection")
2123 def test_prepare_network_for_vm_instance_create_port_raise_exception(
2124 self, mock_reload_connection
2125 ):
2126 """_create_port method raise exception."""
2127 mock_create_port = CopyingMock()
2128 self.vimconn.config["use_floating_ip"] = True
2129 self.vimconn.config["no_port_security_extension"] = True
2130 mock_reload_connection.side_effect = None
2131 created_items = {}
2132
2133 net_list = [
2134 {
2135 "net_id": net2_id,
2136 "use": "other",
2137 "port_security": True,
2138 "port_security_disable_strategy": "full",
2139 }
2140 ]
2141 net_list_vim = []
2142 mock_create_port.side_effect = KeyError
2143 external_network, no_secured_ports = [], []
2144 expected_external_network = []
2145 expected_no_secured_ports = []
2146 expected_net_list_vim = []
2147 with patch.object(vimconnector, "_create_port", mock_create_port):
2148 with self.assertRaises(Exception) as err:
2149 self.vimconn._prepare_network_for_vminstance(
2150 name,
2151 net_list,
2152 created_items,
2153 net_list_vim,
2154 external_network,
2155 no_secured_ports,
2156 )
2157
2158 self.assertEqual(type(err.exception), KeyError)
2159
2160 mock_create_port.assert_called_once_with(
2161 {
2162 "net_id": net2_id,
2163 "use": "other",
2164 "port_security": True,
2165 "port_security_disable_strategy": "full",
2166 },
2167 name,
2168 created_items,
2169 )
2170 self.assertEqual(expected_net_list_vim, net_list_vim)
2171 self.assertEqual(external_network, expected_external_network)
2172 self.assertEqual(expected_no_secured_ports, no_secured_ports)
2173
2174 @patch.object(vimconnector, "_reload_connection")
2175 def test_prepare_network_for_vm_instance_reload_connection_raise_exception(
2176 self, mock_reload_connection
2177 ):
2178 """_reload_connection method raises exception."""
2179 mock_create_port = CopyingMock()
2180 mock_reload_connection.side_effect = VimConnConnectionException(
2181 "Connection failed."
2182 )
2183 self.vimconn.config["use_floating_ip"] = True
2184 self.vimconn.config["no_port_security_extension"] = True
2185 created_items = {}
2186
2187 net_list = [
2188 {
2189 "net_id": net2_id,
2190 "use": "other",
2191 "port_security": True,
2192 "port_security_disable_strategy": "full",
2193 }
2194 ]
2195 net_list_vim = []
2196 mock_create_port.side_effect = None
2197 external_network, no_secured_ports = [], []
2198 expected_external_network = []
2199 expected_no_secured_ports = []
2200 expected_net_list_vim = []
2201 with patch.object(vimconnector, "_create_port", mock_create_port):
2202 with self.assertRaises(Exception) as err:
2203 self.vimconn._prepare_network_for_vminstance(
2204 name,
2205 net_list,
2206 created_items,
2207 net_list_vim,
2208 external_network,
2209 no_secured_ports,
2210 )
2211
2212 self.assertEqual(type(err.exception), VimConnConnectionException)
2213 self.assertEqual(str(err.exception), "Connection failed.")
2214 mock_reload_connection.assert_called_once()
2215 mock_create_port.assert_not_called()
2216 self.assertEqual(expected_net_list_vim, net_list_vim)
2217 self.assertEqual(external_network, expected_external_network)
2218 self.assertEqual(expected_no_secured_ports, no_secured_ports)
2219
2220 def test_prepare_persistent_root_volumes_vim_using_volume_id(self):
2221 """Existing persistent root volume with vim_volume_id."""
2222 vm_av_zone = ["nova"]
2223 base_disk_index = ord("a")
2224 disk = {"vim_volume_id": volume_id}
2225 block_device_mapping = {}
2226 existing_vim_volumes = []
2227 created_items = {}
2228 expected_boot_vol_id = None
2229 expected_block_device_mapping = {"vda": volume_id}
2230 expected_existing_vim_volumes = [{"id": volume_id}]
2231 boot_volume_id = self.vimconn._prepare_persistent_root_volumes(
2232 name,
2233 vm_av_zone,
2234 disk,
2235 base_disk_index,
2236 block_device_mapping,
2237 existing_vim_volumes,
2238 created_items,
2239 )
2240 self.assertEqual(boot_volume_id, expected_boot_vol_id)
2241 self.assertDictEqual(block_device_mapping, expected_block_device_mapping)
2242 self.assertEqual(existing_vim_volumes, expected_existing_vim_volumes)
2243 self.vimconn.cinder.volumes.create.assert_not_called()
2244
2245 def test_prepare_persistent_non_root_volumes_vim_using_volume_id(self):
2246 """Existing persistent non root volume with vim_volume_id."""
2247 vm_av_zone = ["nova"]
2248 base_disk_index = ord("b")
2249 disk = {"vim_volume_id": volume_id}
2250 block_device_mapping = {}
2251 existing_vim_volumes = []
2252 created_items = {}
2253 expected_block_device_mapping = {"vdb": volume_id}
2254 expected_existing_vim_volumes = [{"id": volume_id}]
2255 self.vimconn._prepare_non_root_persistent_volumes(
2256 name,
2257 disk,
2258 vm_av_zone,
2259 block_device_mapping,
2260 base_disk_index,
2261 existing_vim_volumes,
2262 created_items,
2263 )
2264 self.assertDictEqual(block_device_mapping, expected_block_device_mapping)
2265 self.assertEqual(existing_vim_volumes, expected_existing_vim_volumes)
2266 self.vimconn.cinder.volumes.create.assert_not_called()
2267
2268 def test_prepare_persistent_root_volumes_using_vim_id(self):
2269 """Existing persistent root volume with vim_id."""
2270 vm_av_zone = ["nova"]
2271 base_disk_index = ord("a")
2272 disk = {"vim_id": volume_id}
2273 block_device_mapping = {}
2274 existing_vim_volumes = []
2275 created_items = {}
2276 expected_boot_vol_id = None
2277 expected_block_device_mapping = {"vda": volume_id}
2278 expected_existing_vim_volumes = [{"id": volume_id}]
2279 boot_volume_id = self.vimconn._prepare_persistent_root_volumes(
2280 name,
2281 vm_av_zone,
2282 disk,
2283 base_disk_index,
2284 block_device_mapping,
2285 existing_vim_volumes,
2286 created_items,
2287 )
2288 self.assertEqual(boot_volume_id, expected_boot_vol_id)
2289 self.assertDictEqual(block_device_mapping, expected_block_device_mapping)
2290 self.assertEqual(existing_vim_volumes, expected_existing_vim_volumes)
2291 self.vimconn.cinder.volumes.create.assert_not_called()
2292
2293 def test_prepare_persistent_non_root_volumes_using_vim_id(self):
2294 """Existing persistent root volume with vim_id."""
2295 vm_av_zone = ["nova"]
2296 base_disk_index = ord("b")
2297 disk = {"vim_id": volume_id}
2298 block_device_mapping = {}
2299 existing_vim_volumes = []
2300 created_items = {}
2301
2302 expected_block_device_mapping = {"vdb": volume_id}
2303 expected_existing_vim_volumes = [{"id": volume_id}]
2304 self.vimconn._prepare_non_root_persistent_volumes(
2305 name,
2306 disk,
2307 vm_av_zone,
2308 block_device_mapping,
2309 base_disk_index,
2310 existing_vim_volumes,
2311 created_items,
2312 )
2313
2314 self.assertDictEqual(block_device_mapping, expected_block_device_mapping)
2315 self.assertEqual(existing_vim_volumes, expected_existing_vim_volumes)
2316 self.vimconn.cinder.volumes.create.assert_not_called()
2317
2318 def test_prepare_persistent_root_volumes_create(self):
2319 """Create persistent root volume."""
2320 self.vimconn.cinder.volumes.create.return_value.id = volume_id2
2321 vm_av_zone = ["nova"]
2322 base_disk_index = ord("a")
2323 disk = {"size": 10, "image_id": image_id}
2324 block_device_mapping = {}
2325 existing_vim_volumes = []
2326 created_items = {}
2327 expected_boot_vol_id = volume_id2
2328 expected_block_device_mapping = {"vda": volume_id2}
2329 expected_existing_vim_volumes = []
2330 boot_volume_id = self.vimconn._prepare_persistent_root_volumes(
2331 name,
2332 vm_av_zone,
2333 disk,
2334 base_disk_index,
2335 block_device_mapping,
2336 existing_vim_volumes,
2337 created_items,
2338 )
2339 self.assertEqual(boot_volume_id, expected_boot_vol_id)
2340 self.assertDictEqual(block_device_mapping, expected_block_device_mapping)
2341 self.assertEqual(existing_vim_volumes, expected_existing_vim_volumes)
2342 self.vimconn.cinder.volumes.create.assert_called_once_with(
2343 size=10,
2344 name="basicvmvda",
2345 imageRef=image_id,
2346 availability_zone=["nova"],
2347 )
2348 self.assertEqual(created_items, {f"volume:{volume_id2}": True})
2349
2350 def test_prepare_persistent_non_root_volumes_create(self):
2351 """Create persistent non-root volume."""
2352 self.vimconn.cinder = CopyingMock()
2353 self.vimconn.cinder.volumes.create.return_value.id = volume_id2
2354 vm_av_zone = ["nova"]
2355 base_disk_index = ord("a")
2356 disk = {"size": 10}
2357 block_device_mapping = {}
2358 existing_vim_volumes = []
2359 created_items = {}
2360 expected_block_device_mapping = {"vda": volume_id2}
2361 expected_existing_vim_volumes = []
2362 self.vimconn._prepare_non_root_persistent_volumes(
2363 name,
2364 disk,
2365 vm_av_zone,
2366 block_device_mapping,
2367 base_disk_index,
2368 existing_vim_volumes,
2369 created_items,
2370 )
2371
2372 self.assertDictEqual(block_device_mapping, expected_block_device_mapping)
2373 self.assertEqual(existing_vim_volumes, expected_existing_vim_volumes)
2374 self.vimconn.cinder.volumes.create.assert_called_once_with(
2375 size=10, name="basicvmvda", availability_zone=["nova"]
2376 )
2377 self.assertEqual(created_items, {f"volume:{volume_id2}": True})
2378
2379 def test_prepare_persistent_root_volumes_create_raise_exception(self):
2380 """Create persistent root volume raise exception."""
2381 self.vimconn.cinder.volumes.create.side_effect = Exception
2382 vm_av_zone = ["nova"]
2383 base_disk_index = ord("a")
2384 disk = {"size": 10, "image_id": image_id}
2385 block_device_mapping = {}
2386 existing_vim_volumes = []
2387 created_items = {}
2388
2389 with self.assertRaises(Exception):
2390 result = self.vimconn._prepare_persistent_root_volumes(
2391 name,
2392 vm_av_zone,
2393 disk,
2394 base_disk_index,
2395 block_device_mapping,
2396 existing_vim_volumes,
2397 created_items,
2398 )
2399
2400 self.assertEqual(result, None)
2401
2402 self.vimconn.cinder.volumes.create.assert_called_once_with(
2403 size=10,
2404 name="basicvmvda",
2405 imageRef=image_id,
2406 availability_zone=["nova"],
2407 )
2408 self.assertEqual(existing_vim_volumes, [])
2409 self.assertEqual(block_device_mapping, {})
2410 self.assertEqual(created_items, {})
2411
2412 def test_prepare_persistent_non_root_volumes_create_raise_exception(self):
2413 """Create persistent non-root volume raise exception."""
2414 self.vimconn.cinder.volumes.create.side_effect = Exception
2415 vm_av_zone = ["nova"]
2416 base_disk_index = ord("b")
2417 disk = {"size": 10}
2418 block_device_mapping = {}
2419 existing_vim_volumes = []
2420 created_items = {}
2421
2422 with self.assertRaises(Exception):
2423 self.vimconn._prepare_non_root_persistent_volumes(
2424 name,
2425 disk,
2426 vm_av_zone,
2427 block_device_mapping,
2428 base_disk_index,
2429 existing_vim_volumes,
2430 created_items,
2431 )
2432
2433 self.vimconn.cinder.volumes.create.assert_called_once_with(
2434 size=10, name="basicvmvdb", availability_zone=["nova"]
2435 )
2436 self.assertEqual(existing_vim_volumes, [])
2437 self.assertEqual(block_device_mapping, {})
2438 self.assertEqual(created_items, {})
2439
2440 @patch("time.sleep")
2441 def test_wait_for_created_volumes_availability_volume_status_available(
2442 self, mock_sleep
2443 ):
2444 """Created volume status is available."""
2445 elapsed_time = 5
2446 created_items = {f"volume:{volume_id2}": True}
2447 self.vimconn.cinder.volumes.get.return_value.status = "available"
2448
2449 result = self.vimconn._wait_for_created_volumes_availability(
2450 elapsed_time, created_items
2451 )
2452 self.assertEqual(result, elapsed_time)
2453 self.vimconn.cinder.volumes.get.assert_called_with(volume_id2)
2454 mock_sleep.assert_not_called()
2455
2456 @patch("time.sleep")
2457 def test_wait_for_existing_volumes_availability_volume_status_available(
2458 self, mock_sleep
2459 ):
2460 """Existing volume status is available."""
2461 elapsed_time = 5
2462 existing_vim_volumes = [{"id": volume_id2}]
2463 self.vimconn.cinder.volumes.get.return_value.status = "available"
2464
2465 result = self.vimconn._wait_for_existing_volumes_availability(
2466 elapsed_time, existing_vim_volumes
2467 )
2468 self.assertEqual(result, elapsed_time)
2469 self.vimconn.cinder.volumes.get.assert_called_with(volume_id2)
2470 mock_sleep.assert_not_called()
2471
2472 @patch("time.sleep")
2473 def test_wait_for_created_volumes_availability_status_processing_multiple_volumes(
2474 self, mock_sleep
2475 ):
2476 """Created volume status is processing."""
2477 elapsed_time = 5
2478 created_items = {
2479 f"volume:{volume_id2}": True,
2480 f"volume:{volume_id3}": True,
2481 }
2482 self.vimconn.cinder.volumes.get.side_effect = [
2483 Status("processing"),
2484 Status("available"),
2485 Status("available"),
2486 ]
2487
2488 result = self.vimconn._wait_for_created_volumes_availability(
2489 elapsed_time, created_items
2490 )
2491 self.assertEqual(result, 10)
2492 _call_mock_get_volumes = self.vimconn.cinder.volumes.get.call_args_list
2493 self.assertEqual(_call_mock_get_volumes[0][0], (volume_id2,))
2494 self.assertEqual(_call_mock_get_volumes[1][0], (volume_id2,))
2495 self.assertEqual(_call_mock_get_volumes[2][0], (volume_id3,))
2496 mock_sleep.assert_called_with(5)
2497 self.assertEqual(1, mock_sleep.call_count)
2498
2499 @patch("time.sleep")
2500 def test_wait_for_existing_volumes_availability_status_processing_multiple_volumes(
2501 self, mock_sleep
2502 ):
2503 """Existing volume status is processing."""
2504 elapsed_time = 5
2505 existing_vim_volumes = [
2506 {"id": volume_id2},
2507 {"id": "44e0e83-b9uu-4akk-t234-p9cc4811bd4a"},
2508 ]
2509 self.vimconn.cinder.volumes.get.side_effect = [
2510 Status("processing"),
2511 Status("available"),
2512 Status("available"),
2513 ]
2514
2515 result = self.vimconn._wait_for_existing_volumes_availability(
2516 elapsed_time, existing_vim_volumes
2517 )
2518 self.assertEqual(result, 10)
2519 _call_mock_get_volumes = self.vimconn.cinder.volumes.get.call_args_list
2520 self.assertEqual(_call_mock_get_volumes[0][0], (volume_id2,))
2521 self.assertEqual(_call_mock_get_volumes[1][0], (volume_id2,))
2522 self.assertEqual(
2523 _call_mock_get_volumes[2][0], ("44e0e83-b9uu-4akk-t234-p9cc4811bd4a",)
2524 )
2525 mock_sleep.assert_called_with(5)
2526 self.assertEqual(1, mock_sleep.call_count)
2527
2528 @patch("time.sleep")
2529 def test_wait_for_created_volumes_availability_volume_status_processing_timeout(
2530 self, mock_sleep
2531 ):
2532 """Created volume status is processing, elapsed time greater than timeout (1800)."""
2533 elapsed_time = 1805
2534 created_items = {f"volume:{volume_id2}": True}
2535 self.vimconn.cinder.volumes.get.side_effect = [
2536 Status("processing"),
2537 Status("processing"),
2538 ]
2539 with patch("time.sleep", mock_sleep):
2540 result = self.vimconn._wait_for_created_volumes_availability(
2541 elapsed_time, created_items
2542 )
2543 self.assertEqual(result, 1805)
2544 self.vimconn.cinder.volumes.get.assert_not_called()
2545 mock_sleep.assert_not_called()
2546
2547 @patch("time.sleep")
2548 def test_wait_for_existing_volumes_availability_volume_status_processing_timeout(
2549 self, mock_sleep
2550 ):
2551 """Exsiting volume status is processing, elapsed time greater than timeout (1800)."""
2552 elapsed_time = 1805
2553 existing_vim_volumes = [{"id": volume_id2}]
2554 self.vimconn.cinder.volumes.get.side_effect = [
2555 Status("processing"),
2556 Status("processing"),
2557 ]
2558
2559 result = self.vimconn._wait_for_existing_volumes_availability(
2560 elapsed_time, existing_vim_volumes
2561 )
2562 self.assertEqual(result, 1805)
2563 self.vimconn.cinder.volumes.get.assert_not_called()
2564 mock_sleep.assert_not_called()
2565
2566 @patch("time.sleep")
2567 def test_wait_for_created_volumes_availability_cinder_raise_exception(
2568 self, mock_sleep
2569 ):
2570 """Cinder get volumes raises exception for created volumes."""
2571 elapsed_time = 1000
2572 created_items = {f"volume:{volume_id2}": True}
2573 self.vimconn.cinder.volumes.get.side_effect = Exception
2574 with self.assertRaises(Exception):
2575 result = self.vimconn._wait_for_created_volumes_availability(
2576 elapsed_time, created_items
2577 )
2578 self.assertEqual(result, 1000)
2579 self.vimconn.cinder.volumes.get.assert_called_with(volume_id2)
2580 mock_sleep.assert_not_called()
2581
2582 @patch("time.sleep")
2583 def test_wait_for_existing_volumes_availability_cinder_raise_exception(
2584 self, mock_sleep
2585 ):
2586 """Cinder get volumes raises exception for existing volumes."""
2587 elapsed_time = 1000
2588 existing_vim_volumes = [{"id": volume_id2}]
2589 self.vimconn.cinder.volumes.get.side_effect = Exception
2590 with self.assertRaises(Exception):
2591 result = self.vimconn._wait_for_existing_volumes_availability(
2592 elapsed_time, existing_vim_volumes
2593 )
2594 self.assertEqual(result, 1000)
2595 self.vimconn.cinder.volumes.get.assert_called_with(volume_id2)
2596 mock_sleep.assert_not_called()
2597
2598 @patch("time.sleep")
2599 def test_wait_for_created_volumes_availability_no_volume_in_created_items(
2600 self, mock_sleep
2601 ):
2602 """Created_items dict does not have volume-id."""
2603 elapsed_time = 10
2604 created_items = {}
2605
2606 self.vimconn.cinder.volumes.get.side_effect = [None]
2607
2608 result = self.vimconn._wait_for_created_volumes_availability(
2609 elapsed_time, created_items
2610 )
2611 self.assertEqual(result, 10)
2612 self.vimconn.cinder.volumes.get.assert_not_called()
2613 mock_sleep.assert_not_called()
2614
2615 @patch("time.sleep")
2616 def test_wait_for_existing_volumes_availability_no_volume_in_existing_vim_volumes(
2617 self, mock_sleep
2618 ):
2619 """Existing_vim_volumes list does not have volume."""
2620 elapsed_time = 10
2621 existing_vim_volumes = []
2622
2623 self.vimconn.cinder.volumes.get.side_effect = [None]
2624
2625 result = self.vimconn._wait_for_existing_volumes_availability(
2626 elapsed_time, existing_vim_volumes
2627 )
2628 self.assertEqual(result, 10)
2629 self.vimconn.cinder.volumes.get.assert_not_called()
2630 mock_sleep.assert_not_called()
2631
2632 @patch.object(vimconnector, "_prepare_persistent_root_volumes")
2633 @patch.object(vimconnector, "_prepare_non_root_persistent_volumes")
2634 @patch.object(vimconnector, "_wait_for_created_volumes_availability")
2635 @patch.object(vimconnector, "_wait_for_existing_volumes_availability")
2636 def test_prepare_disk_for_vm_instance(
2637 self,
2638 mock_existing_vol_availability,
2639 mock_created_vol_availability,
2640 mock_non_root_volumes,
2641 mock_root_volumes,
2642 ):
2643 """Prepare disks for VM instance successfully."""
2644 existing_vim_volumes = []
2645 created_items = {}
2646 vm_av_zone = ["nova"]
2647
2648 mock_root_volumes.return_value = root_vol_id
2649 mock_created_vol_availability.return_value = 10
2650 mock_existing_vol_availability.return_value = 15
2651 self.vimconn.cinder = CopyingMock()
2652
2653 self.vimconn._prepare_disk_for_vminstance(
2654 name, existing_vim_volumes, created_items, vm_av_zone, disk_list2
2655 )
2656 self.vimconn.cinder.volumes.set_bootable.assert_called_once_with(
2657 root_vol_id, True
2658 )
2659 mock_created_vol_availability.assert_called_once_with(0, created_items)
2660 mock_existing_vol_availability.assert_called_once_with(10, existing_vim_volumes)
2661 self.assertEqual(mock_root_volumes.call_count, 1)
2662 self.assertEqual(mock_non_root_volumes.call_count, 1)
2663 mock_root_volumes.assert_called_once_with(
2664 name="basicvm",
2665 vm_av_zone=["nova"],
2666 disk={"size": 10, "image_id": image_id},
2667 base_disk_index=97,
2668 block_device_mapping={},
2669 existing_vim_volumes=[],
2670 created_items={},
2671 )
2672 mock_non_root_volumes.assert_called_once_with(
2673 name="basicvm",
2674 disk={"size": 20},
2675 vm_av_zone=["nova"],
2676 base_disk_index=98,
2677 block_device_mapping={},
2678 existing_vim_volumes=[],
2679 created_items={},
2680 )
2681
2682 @patch.object(vimconnector, "_prepare_persistent_root_volumes")
2683 @patch.object(vimconnector, "_prepare_non_root_persistent_volumes")
2684 @patch.object(vimconnector, "_wait_for_created_volumes_availability")
2685 @patch.object(vimconnector, "_wait_for_existing_volumes_availability")
2686 def test_prepare_disk_for_vm_instance_timeout_exceeded(
2687 self,
2688 mock_existing_vol_availability,
2689 mock_created_vol_availability,
2690 mock_non_root_volumes,
2691 mock_root_volumes,
2692 ):
2693 """Timeout exceeded while waiting for disks."""
2694 existing_vim_volumes = []
2695 created_items = {}
2696 vm_av_zone = ["nova"]
2697
2698 mock_root_volumes.return_value = root_vol_id
2699 mock_created_vol_availability.return_value = 1700
2700 mock_existing_vol_availability.return_value = 1900
2701
2702 with self.assertRaises(VimConnException) as err:
2703 self.vimconn._prepare_disk_for_vminstance(
2704 name, existing_vim_volumes, created_items, vm_av_zone, disk_list2
2705 )
2706 self.assertEqual(
2707 str(err.exception), "Timeout creating volumes for instance basicvm"
2708 )
2709 self.vimconn.cinder.volumes.set_bootable.assert_not_called()
2710 mock_created_vol_availability.assert_called_once_with(0, created_items)
2711 mock_existing_vol_availability.assert_called_once_with(
2712 1700, existing_vim_volumes
2713 )
2714 self.assertEqual(mock_root_volumes.call_count, 1)
2715 self.assertEqual(mock_non_root_volumes.call_count, 1)
2716 mock_root_volumes.assert_called_once_with(
2717 name="basicvm",
2718 vm_av_zone=["nova"],
2719 disk={"size": 10, "image_id": image_id},
2720 base_disk_index=97,
2721 block_device_mapping={},
2722 existing_vim_volumes=[],
2723 created_items={},
2724 )
2725 mock_non_root_volumes.assert_called_once_with(
2726 name="basicvm",
2727 disk={"size": 20},
2728 vm_av_zone=["nova"],
2729 base_disk_index=98,
2730 block_device_mapping={},
2731 existing_vim_volumes=[],
2732 created_items={},
2733 )
2734
2735 @patch.object(vimconnector, "_prepare_persistent_root_volumes")
2736 @patch.object(vimconnector, "_prepare_non_root_persistent_volumes")
2737 @patch.object(vimconnector, "_wait_for_created_volumes_availability")
2738 @patch.object(vimconnector, "_wait_for_existing_volumes_availability")
2739 def test_prepare_disk_for_vm_instance_empty_disk_list(
2740 self,
2741 mock_existing_vol_availability,
2742 mock_created_vol_availability,
2743 mock_non_root_volumes,
2744 mock_root_volumes,
2745 ):
2746 """Disk list is empty."""
2747 existing_vim_volumes = []
2748 created_items = {}
2749 vm_av_zone = ["nova"]
2750 mock_created_vol_availability.return_value = 2
2751 mock_existing_vol_availability.return_value = 3
2752
2753 self.vimconn._prepare_disk_for_vminstance(
2754 name, existing_vim_volumes, created_items, vm_av_zone, disk_list
2755 )
2756 self.vimconn.cinder.volumes.set_bootable.assert_not_called()
2757 mock_created_vol_availability.assert_called_once_with(0, created_items)
2758 mock_existing_vol_availability.assert_called_once_with(2, existing_vim_volumes)
2759 mock_root_volumes.assert_not_called()
2760 mock_non_root_volumes.assert_not_called()
2761
2762 @patch.object(vimconnector, "_prepare_persistent_root_volumes")
2763 @patch.object(vimconnector, "_prepare_non_root_persistent_volumes")
2764 @patch.object(vimconnector, "_wait_for_created_volumes_availability")
2765 @patch.object(vimconnector, "_wait_for_existing_volumes_availability")
2766 def test_prepare_disk_for_vm_instance_persistent_root_volume_error(
2767 self,
2768 mock_existing_vol_availability,
2769 mock_created_vol_availability,
2770 mock_non_root_volumes,
2771 mock_root_volumes,
2772 ):
2773 """Persistent root volumes preparation raises error."""
2774 existing_vim_volumes = []
2775 created_items = {}
2776 vm_av_zone = ["nova"]
2777
2778 mock_root_volumes.side_effect = Exception()
2779 mock_created_vol_availability.return_value = 10
2780 mock_existing_vol_availability.return_value = 15
2781
2782 with self.assertRaises(Exception):
2783 self.vimconn._prepare_disk_for_vminstance(
2784 name, existing_vim_volumes, created_items, vm_av_zone, disk_list2
2785 )
2786 self.vimconn.cinder.volumes.set_bootable.assert_not_called()
2787 mock_created_vol_availability.assert_not_called()
2788 mock_existing_vol_availability.assert_not_called()
2789 mock_root_volumes.assert_called_once_with(
2790 name="basicvm",
2791 vm_av_zone=["nova"],
2792 disk={"size": 10, "image_id": image_id},
2793 base_disk_index=97,
2794 block_device_mapping={},
2795 existing_vim_volumes=[],
2796 created_items={},
2797 )
2798 mock_non_root_volumes.assert_not_called()
2799
2800 @patch.object(vimconnector, "_prepare_persistent_root_volumes")
2801 @patch.object(vimconnector, "_prepare_non_root_persistent_volumes")
2802 @patch.object(vimconnector, "_wait_for_created_volumes_availability")
2803 @patch.object(vimconnector, "_wait_for_existing_volumes_availability")
2804 def test_prepare_disk_for_vm_instance_non_root_volume_error(
2805 self,
2806 mock_existing_vol_availability,
2807 mock_created_vol_availability,
2808 mock_non_root_volumes,
2809 mock_root_volumes,
2810 ):
2811 """Non-root volumes preparation raises error."""
2812 existing_vim_volumes = []
2813 created_items = {}
2814 vm_av_zone = ["nova"]
2815
2816 mock_root_volumes.return_value = root_vol_id
2817 mock_non_root_volumes.side_effect = Exception
2818
2819 with self.assertRaises(Exception):
2820 self.vimconn._prepare_disk_for_vminstance(
2821 name, existing_vim_volumes, created_items, vm_av_zone, disk_list2
2822 )
2823 self.vimconn.cinder.volumes.set_bootable.assert_not_called()
2824 mock_created_vol_availability.assert_not_called()
2825 mock_existing_vol_availability.assert_not_called()
2826 self.assertEqual(mock_root_volumes.call_count, 1)
2827 self.assertEqual(mock_non_root_volumes.call_count, 1)
2828 mock_root_volumes.assert_called_once_with(
2829 name="basicvm",
2830 vm_av_zone=["nova"],
2831 disk={"size": 10, "image_id": image_id},
2832 base_disk_index=97,
2833 block_device_mapping={},
2834 existing_vim_volumes=[],
2835 created_items={},
2836 )
2837 mock_non_root_volumes.assert_called_once_with(
2838 name="basicvm",
2839 disk={"size": 20},
2840 vm_av_zone=["nova"],
2841 base_disk_index=98,
2842 block_device_mapping={},
2843 existing_vim_volumes=[],
2844 created_items={},
2845 )
2846
2847 def test_find_external_network_for_floating_ip_no_external_network(self):
2848 """External network could not be found."""
2849 self.vimconn.neutron.list_networks.return_value = {
2850 "networks": [
2851 {"id": "408b73-r9cc-5a6a-a270-82cc4811bd4a", "router:external": False}
2852 ]
2853 }
2854 with self.assertRaises(VimConnException) as err:
2855 self.vimconn._find_the_external_network_for_floating_ip()
2856 self.assertEqual(
2857 str(err.exception),
2858 "Cannot create floating_ip automatically since no external network is present",
2859 )
2860
2861 def test_find_external_network_for_floating_one_external_network(self):
2862 """One external network has been found."""
2863 self.vimconn.neutron.list_networks.return_value = {
2864 "networks": [
2865 {"id": "408b73-r9cc-5a6a-a270-82cc4811bd4a", "router:external": True}
2866 ]
2867 }
2868 expected_result = "408b73-r9cc-5a6a-a270-82cc4811bd4a"
2869 result = self.vimconn._find_the_external_network_for_floating_ip()
2870 self.assertEqual(result, expected_result)
2871
2872 def test_find_external_network_for_floating_neutron_raises_exception(self):
2873 """Neutron list networks raises exception."""
2874 self.vimconn.neutron.list_networks.side_effect = Exception
2875 with self.assertRaises(Exception):
2876 self.vimconn._find_the_external_network_for_floating_ip()
2877
2878 def test_find_external_network_for_floating_several_external_network(self):
2879 """Several exernal networks has been found."""
2880 self.vimconn.neutron.list_networks.return_value = {
2881 "networks": [
2882 {"id": "408b73-r9cc-5a6a-a270-82cc4811bd4a", "router:external": True},
2883 {"id": "608b73-y9cc-5a6a-a270-12cc4811bd4a", "router:external": True},
2884 ]
2885 }
2886 with self.assertRaises(VimConnException) as err:
2887 self.vimconn._find_the_external_network_for_floating_ip()
2888 self.assertEqual(
2889 str(err.exception),
2890 "Cannot create floating_ip automatically since multiple external networks are present",
2891 )
2892
2893 def test_neutron_create_float_ip(self):
2894 """Floating ip creation is successful."""
2895 param = {"net_id": "408b73-r9cc-5a6a-a270-p2cc4811bd9a"}
2896 created_items = {}
2897 self.vimconn.neutron.create_floatingip.return_value = {
2898 "floatingip": {"id": "308b73-t9cc-1a6a-a270-12cc4811bd4a"}
2899 }
2900 expected_created_items = {
2901 "floating_ip:308b73-t9cc-1a6a-a270-12cc4811bd4a": True
2902 }
2903 self.vimconn._neutron_create_float_ip(param, created_items)
2904 self.assertEqual(created_items, expected_created_items)
2905
2906 def test_neutron_create_float_ip_exception_occured(self):
2907 """Floating ip could not be created."""
2908 param = {
2909 "floatingip": {
2910 "floating_network_id": "408b73-r9cc-5a6a-a270-p2cc4811bd9a",
2911 "tenant_id": "308b73-19cc-8a6a-a270-02cc4811bd9a",
2912 }
2913 }
2914 created_items = {}
2915 self.vimconn.neutron = CopyingMock()
2916 self.vimconn.neutron.create_floatingip.side_effect = Exception(
2917 "Neutron floating ip create exception occured."
2918 )
2919 with self.assertRaises(VimConnException) as err:
2920 self.vimconn._neutron_create_float_ip(param, created_items)
2921 self.assertEqual(created_items, {})
2922 self.assertEqual(
2923 str(err.exception),
2924 "Exception: Cannot create new floating_ip Neutron floating ip create exception occured.",
2925 )
2926
2927 @patch.object(vimconnector, "_neutron_create_float_ip")
2928 @patch.object(vimconnector, "_find_the_external_network_for_floating_ip")
2929 def test_create_floating_ip_pool_id_available(
2930 self, mock_find_ext_network, mock_create_float_ip
2931 ):
2932 """Floating ip creation, ip pool is available."""
2933 floating_network = {"floating_ip": "308b73-t9cc-1a6a-a270-12cc4811bd4a"}
2934 created_items = {}
2935 expected_param = {
2936 "floatingip": {
2937 "floating_network_id": "308b73-t9cc-1a6a-a270-12cc4811bd4a",
2938 "tenant_id": "408b73-r9cc-5a6a-a270-82cc4811bd4a",
2939 }
2940 }
2941 self.vimconn._create_floating_ip(floating_network, self.server, created_items)
2942 mock_find_ext_network.assert_not_called()
2943 mock_create_float_ip.assert_called_once_with(expected_param, {})
2944
2945 @patch.object(vimconnector, "_neutron_create_float_ip")
2946 @patch.object(vimconnector, "_find_the_external_network_for_floating_ip")
2947 def test_create_floating_ip_finding_pool_id(
2948 self, mock_find_ext_network, mock_create_float_ip
2949 ):
2950 """Floating ip creation, pool id need to be found."""
2951 floating_network = {"floating_ip": True}
2952 created_items = {}
2953 mock_find_ext_network.return_value = "308b73-t9cc-1a6a-a270-12cc4811bd4a"
2954 expected_param = {
2955 "floatingip": {
2956 "floating_network_id": "308b73-t9cc-1a6a-a270-12cc4811bd4a",
2957 "tenant_id": "408b73-r9cc-5a6a-a270-82cc4811bd4a",
2958 }
2959 }
2960 self.vimconn._create_floating_ip(floating_network, self.server, created_items)
2961 mock_find_ext_network.assert_called_once()
2962 mock_create_float_ip.assert_called_once_with(expected_param, {})
2963
2964 @patch.object(vimconnector, "_neutron_create_float_ip")
2965 @patch.object(vimconnector, "_find_the_external_network_for_floating_ip")
2966 def test_create_floating_ip_neutron_create_floating_ip_exception(
2967 self, mock_find_ext_network, mock_create_float_ip
2968 ):
2969 """Neutron creat floating ip raises error."""
2970 floating_network = {"floating_ip": True}
2971 created_items = {}
2972 mock_create_float_ip.side_effect = VimConnException(
2973 "Can not create floating ip."
2974 )
2975 mock_find_ext_network.return_value = "308b73-t9cc-1a6a-a270-12cc4811bd4a"
2976 expected_param = {
2977 "floatingip": {
2978 "floating_network_id": "308b73-t9cc-1a6a-a270-12cc4811bd4a",
2979 "tenant_id": "408b73-r9cc-5a6a-a270-82cc4811bd4a",
2980 }
2981 }
2982
2983 with self.assertRaises(VimConnException) as err:
2984 self.vimconn._create_floating_ip(
2985 floating_network, self.server, created_items
2986 )
2987 self.assertEqual(str(err.exception), "Can not create floating ip.")
2988 mock_find_ext_network.assert_called_once()
2989 mock_create_float_ip.assert_called_once_with(expected_param, {})
2990
2991 @patch.object(vimconnector, "_neutron_create_float_ip")
2992 @patch.object(vimconnector, "_find_the_external_network_for_floating_ip")
2993 def test_create_floating_ip_can_not_find_pool_id(
2994 self, mock_find_ext_network, mock_create_float_ip
2995 ):
2996 """Floating ip creation, pool id could not be found."""
2997 floating_network = {"floating_ip": True}
2998 created_items = {}
2999 mock_find_ext_network.side_effect = VimConnException(
3000 "Cannot create floating_ip automatically since no external network is present"
3001 )
3002 with self.assertRaises(VimConnException) as err:
3003 self.vimconn._create_floating_ip(
3004 floating_network, self.server, created_items
3005 )
3006 self.assertEqual(
3007 str(err.exception),
3008 "Cannot create floating_ip automatically since no external network is present",
3009 )
3010 mock_find_ext_network.assert_called_once()
3011 mock_create_float_ip.assert_not_called()
3012
3013 def test_find_floating_ip_get_free_floating_ip(self):
3014 """Get free floating ips successfully."""
3015 floating_ips = [
3016 {
3017 "tenant_id": "408b73-r9cc-5a6a-a270-82cc4811bd4a",
3018 "floating_network_id": "308b73-t9cc-1a6a-a270-12cc4811bd4a",
3019 "id": "508b73-o9cc-5a6a-a270-72cc4811bd8",
3020 }
3021 ]
3022 floating_network = {"floating_ip": "308b73-t9cc-1a6a-a270-12cc4811bd4a"}
3023 expected_result = "508b73-o9cc-5a6a-a270-72cc4811bd8"
3024
3025 result = self.vimconn._find_floating_ip(
3026 self.server, floating_ips, floating_network
3027 )
3028 self.assertEqual(result, expected_result)
3029
3030 def test_find_floating_ip_different_floating_network_id(self):
3031 """Floating network id is different with floating_ip of floating network."""
3032 floating_ips = [
3033 {
3034 "floating_network_id": "308b73-t9cc-1a6a-a270-12cc4811bd4a",
3035 "id": "508b73-o9cc-5a6a-a270-72cc4811bd8",
3036 }
3037 ]
3038 floating_network = {"floating_ip": "508b73-t9cc-1a6a-a270-12cc4811bd4a"}
3039
3040 result = self.vimconn._find_floating_ip(
3041 self.server, floating_ips, floating_network
3042 )
3043 self.assertEqual(result, None)
3044
3045 def test_find_floating_ip_different_fip_tenant(self):
3046 """Items in floating_ips has port_id, tenant_is is not same with server tenant id."""
3047 floating_ips = [
3048 {
3049 "port_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3050 "floating_network_id": "308b73-t9cc-1a6a-a270-12cc4811bd4a",
3051 "id": "508b73-o9cc-5a6a-a270-72cc4811bd8",
3052 "tenant_id": self.server.id,
3053 }
3054 ]
3055 floating_network = {"floating_ip": "308b73-t9cc-1a6a-a270-12cc4811bd4a"}
3056 mock_create_floating_ip = CopyingMock()
3057 with patch.object(vimconnector, "_create_floating_ip", mock_create_floating_ip):
3058 result = self.vimconn._find_floating_ip(
3059 self.server, floating_ips, floating_network
3060 )
3061 self.assertEqual(result, None)
3062
3063 @patch("time.sleep")
3064 def test_assign_floating_ip(self, mock_sleep):
3065 """Assign floating ip successfully."""
3066 free_floating_ip = "508b73-o9cc-5a6a-a270-72cc4811bd8"
3067 floating_network = {"vim_id": floating_network_vim_id}
3068 fip = {
3069 "port_id": floating_network_vim_id,
3070 "floating_network_id": "p08b73-e9cc-5a6a-t270-82cc4811bd4a",
3071 "id": "508b73-o9cc-5a6a-a270-72cc4811bd8",
3072 "tenant_id": "k08b73-e9cc-5a6a-t270-82cc4811bd4a",
3073 }
3074 self.vimconn.neutron.update_floatingip.side_effect = None
3075 self.vimconn.neutron.show_floatingip.return_value = fip
3076 expected_result = fip
3077
3078 result = self.vimconn._assign_floating_ip(free_floating_ip, floating_network)
3079 self.assertEqual(result, expected_result)
3080 self.vimconn.neutron.update_floatingip.assert_called_once_with(
3081 free_floating_ip,
3082 {"floatingip": {"port_id": floating_network_vim_id}},
3083 )
3084 mock_sleep.assert_called_once_with(5)
3085 self.vimconn.neutron.show_floatingip.assert_called_once_with(free_floating_ip)
3086
3087 @patch("time.sleep")
3088 def test_assign_floating_ip_update_floating_ip_exception(self, mock_sleep):
3089 """Neutron update floating ip raises exception."""
3090 free_floating_ip = "508b73-o9cc-5a6a-a270-72cc4811bd8"
3091 floating_network = {"vim_id": floating_network_vim_id}
3092 self.vimconn.neutron = CopyingMock()
3093 self.vimconn.neutron.update_floatingip.side_effect = Exception(
3094 "Floating ip is not updated."
3095 )
3096
3097 with self.assertRaises(Exception) as err:
3098 result = self.vimconn._assign_floating_ip(
3099 free_floating_ip, floating_network
3100 )
3101 self.assertEqual(result, None)
3102 self.assertEqual(str(err.exception), "Floating ip is not updated.")
3103
3104 self.vimconn.neutron.update_floatingip.assert_called_once_with(
3105 free_floating_ip,
3106 {"floatingip": {"port_id": floating_network_vim_id}},
3107 )
3108 mock_sleep.assert_not_called()
3109 self.vimconn.neutron.show_floatingip.assert_not_called()
3110
3111 @patch("time.sleep")
3112 def test_assign_floating_ip_show_floating_ip_exception(self, mock_sleep):
3113 """Neutron show floating ip raises exception."""
3114 free_floating_ip = "508b73-o9cc-5a6a-a270-72cc4811bd8"
3115 floating_network = {"vim_id": floating_network_vim_id}
3116 self.vimconn.neutron.update_floatingip.side_effect = None
3117 self.vimconn.neutron.show_floatingip.side_effect = Exception(
3118 "Floating ip could not be shown."
3119 )
3120
3121 with self.assertRaises(Exception) as err:
3122 result = self.vimconn._assign_floating_ip(
3123 free_floating_ip, floating_network
3124 )
3125 self.assertEqual(result, None)
3126 self.assertEqual(str(err.exception), "Floating ip could not be shown.")
3127 self.vimconn.neutron.update_floatingip.assert_called_once_with(
3128 free_floating_ip,
3129 {"floatingip": {"port_id": floating_network_vim_id}},
3130 )
3131 mock_sleep.assert_called_once_with(5)
3132 self.vimconn.neutron.show_floatingip.assert_called_once_with(free_floating_ip)
3133
3134 @patch("random.shuffle")
3135 @patch.object(vimconnector, "_find_floating_ip")
3136 def test_get_free_floating_ip(self, mock_find_floating_ip, mock_shuffle):
3137 """Get free floating ip successfully."""
3138 floating_network = {"floating_ip": "308b73-t9cc-1a6a-a270-12cc4811bd4a"}
3139 floating_ips = [
3140 {
3141 "port_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3142 "floating_network_id": "308b73-t9cc-1a6a-a270-12cc4811bd4a",
3143 "id": "508b73-o9cc-5a6a-a270-72cc4811bd8",
3144 "tenant_id": "208b73-e9cc-5a6a-t270-82cc4811bd4a",
3145 },
3146 {
3147 "port_id": "508b73-r9cc-5a6a-5270-o2cc4811bd4a",
3148 "floating_network_id": "308b73-t9cc-1a6a-a270-12cc4811bd4a",
3149 "id": "208b73-o9cc-5a6a-a270-52cc4811bd8",
3150 "tenant_id": "208b73-e9cc-5a6a-t270-82cc4811bd4a",
3151 },
3152 ]
3153 self.vimconn.neutron.list_floatingips.return_value = {
3154 "floatingips": floating_ips
3155 }
3156 mock_find_floating_ip.return_value = "508b73-o9cc-5a6a-a270-72cc4811bd8"
3157 expected_result = "508b73-o9cc-5a6a-a270-72cc4811bd8"
3158
3159 result = self.vimconn._get_free_floating_ip(self.server, floating_network)
3160 self.assertEqual(result, expected_result)
3161 mock_shuffle.assert_called_once_with(floating_ips)
3162 mock_find_floating_ip.assert_called_once_with(
3163 self.server, floating_ips, floating_network
3164 )
3165
3166 @patch("random.shuffle")
3167 @patch.object(vimconnector, "_find_floating_ip")
3168 def test_get_free_floating_ip_list_floating_ip_exception(
3169 self, mock_find_floating_ip, mock_shuffle
3170 ):
3171 """Neutron list floating IPs raises exception."""
3172 floating_network = {"floating_ip": "308b73-t9cc-1a6a-a270-12cc4811bd4a"}
3173 self.vimconn.neutron = CopyingMock()
3174 self.vimconn.neutron.list_floatingips.side_effect = Exception(
3175 "Floating ips could not be listed."
3176 )
3177 with self.assertRaises(Exception) as err:
3178 result = self.vimconn._get_free_floating_ip(self.server, floating_network)
3179 self.assertEqual(result, None)
3180 self.assertEqual(str(err.exception), "Floating ips could not be listed.")
3181 mock_shuffle.assert_not_called()
3182 mock_find_floating_ip.assert_not_called()
3183
3184 @patch("random.shuffle")
3185 @patch.object(vimconnector, "_find_floating_ip")
3186 def test_get_free_floating_ip_find_floating_ip_exception(
3187 self, mock_find_floating_ip, mock_shuffle
3188 ):
3189 """_find_floating_ip method raises exception."""
3190 floating_network = {"floating_ip": "308b73-t9cc-1a6a-a270-12cc4811bd4a"}
3191 floating_ips = [
3192 {
3193 "port_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3194 "floating_network_id": "308b73-t9cc-1a6a-a270-12cc4811bd4a",
3195 "id": "508b73-o9cc-5a6a-a270-72cc4811bd8",
3196 "tenant_id": "208b73-e9cc-5a6a-t270-82cc4811bd4a",
3197 },
3198 {
3199 "port_id": "508b73-r9cc-5a6a-5270-o2cc4811bd4a",
3200 "floating_network_id": "308b73-t9cc-1a6a-a270-12cc4811bd4a",
3201 "id": "208b73-o9cc-5a6a-a270-52cc4811bd8",
3202 "tenant_id": "208b73-e9cc-5a6a-t270-82cc4811bd4a",
3203 },
3204 ]
3205 self.vimconn.neutron = CopyingMock()
3206 self.vimconn.neutron.list_floatingips.return_value = {
3207 "floatingips": floating_ips
3208 }
3209 mock_find_floating_ip.side_effect = Exception(
3210 "Free floating ip could not be found."
3211 )
3212
3213 with self.assertRaises(Exception) as err:
3214 result = self.vimconn._get_free_floating_ip(self.server, floating_network)
3215 self.assertEqual(result, None)
3216 self.assertEqual(str(err.exception), "Free floating ip could not be found.")
3217 mock_shuffle.assert_called_once_with(floating_ips)
3218 mock_find_floating_ip.assert_called_once_with(
3219 self.server, floating_ips, floating_network
3220 )
3221
3222 @patch.object(vimconnector, "_create_floating_ip")
3223 @patch.object(vimconnector, "_get_free_floating_ip")
3224 @patch.object(vimconnector, "_assign_floating_ip")
3225 def test_prepare_external_network_for_vm_instance(
3226 self,
3227 mock_assign_floating_ip,
3228 mock_get_free_floating_ip,
3229 mock_create_floating_ip,
3230 ):
3231 """Prepare external network successfully."""
3232 external_network = [
3233 {
3234 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3235 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3236 },
3237 ]
3238 created_items = {}
3239 vm_start_time = time_return_value
3240 mock_get_free_floating_ip.side_effect = ["y08b73-o9cc-1a6a-a270-12cc4811bd4u"]
3241 mock_assign_floating_ip.return_value = {
3242 "floatingip": {"port_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a"}
3243 }
3244 self.vimconn.neutron = CopyingMock()
3245 self.vimconn.nova = CopyingMock()
3246 self.vimconn.neutron.show_floatingip.return_value = {
3247 "floatingip": {"port_id": ""}
3248 }
3249
3250 self.vimconn._prepare_external_network_for_vminstance(
3251 external_network, self.server, created_items, vm_start_time
3252 )
3253
3254 self.assertEqual(mock_get_free_floating_ip.call_count, 1)
3255 mock_get_free_floating_ip.assert_called_once_with(
3256 self.server,
3257 {
3258 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3259 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3260 },
3261 )
3262 self.vimconn.neutron.show_floatingip.assert_called_once_with(
3263 "y08b73-o9cc-1a6a-a270-12cc4811bd4u"
3264 )
3265 self.vimconn.nova.servers.get.assert_not_called()
3266 mock_create_floating_ip.assert_not_called()
3267 mock_assign_floating_ip.assert_called_once_with(
3268 "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3269 {
3270 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3271 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3272 },
3273 )
3274
3275 @patch("time.time")
3276 @patch("time.sleep")
3277 @patch.object(vimconnector, "_create_floating_ip")
3278 @patch.object(vimconnector, "_get_free_floating_ip")
3279 @patch.object(vimconnector, "_assign_floating_ip")
3280 def test_prepare_external_network_for_vm_instance_no_free_floating_ip(
3281 self,
3282 mock_assign_floating_ip,
3283 mock_get_free_floating_ip,
3284 mock_create_floating_ip,
3285 mock_sleep,
3286 mock_time,
3287 ):
3288 """There is not any free floating ip."""
3289 floating_network = {
3290 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3291 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3292 }
3293 external_network = [floating_network]
3294
3295 created_items = {}
3296 vm_start_time = time_return_value
3297 mock_get_free_floating_ip.return_value = None
3298 mock_assign_floating_ip.return_value = {}
3299 self.vimconn.nova.servers.get.return_value.status = "ERROR"
3300 self.vimconn.neutron.show_floatingip.return_value = {}
3301
3302 with self.assertRaises(KeyError):
3303 self.vimconn._prepare_external_network_for_vminstance(
3304 external_network, self.server, created_items, vm_start_time
3305 )
3306
3307 self.assertEqual(mock_get_free_floating_ip.call_count, 4)
3308 mock_get_free_floating_ip.assert_called_with(
3309 self.server,
3310 {
3311 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3312 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3313 },
3314 )
3315 self.vimconn.neutron.show_floatingip.assert_called_with(None)
3316 mock_sleep.assert_not_called()
3317 mock_time.assert_not_called()
3318 self.assertEqual(self.vimconn.nova.servers.get.call_count, 4)
3319 mock_create_floating_ip.assert_called_with(
3320 floating_network, self.server, created_items
3321 )
3322 self.assertEqual(mock_create_floating_ip.call_count, 4)
3323 mock_assign_floating_ip.assert_not_called()
3324 self.vimconn.nova.servers.get.assert_called_with(self.server.id)
3325
3326 @patch("time.time")
3327 @patch("time.sleep")
3328 @patch.object(vimconnector, "_create_floating_ip")
3329 @patch.object(vimconnector, "_get_free_floating_ip")
3330 @patch.object(vimconnector, "_assign_floating_ip")
3331 def test_prepare_external_network_for_vm_instance_no_free_fip_can_not_create_fip_exit_on_error_false(
3332 self,
3333 mock_assign_floating_ip,
3334 mock_get_free_floating_ip,
3335 mock_create_floating_ip,
3336 mock_sleep,
3337 mock_time,
3338 ):
3339 """There is not any free floating ip, create_floating ip method raise exception
3340 exit_on_floating_ip_error set to False."""
3341 floating_network = {
3342 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3343 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3344 "exit_on_floating_ip_error": False,
3345 }
3346 external_network = [floating_network]
3347
3348 created_items = {}
3349 vm_start_time = time_return_value
3350 mock_get_free_floating_ip.return_value = None
3351 mock_assign_floating_ip.return_value = {}
3352 mock_create_floating_ip.side_effect = VimConnException(
3353 "Can not create floating ip."
3354 )
3355 self.vimconn.nova.servers.get.return_value.status = "ERROR"
3356 self.vimconn.neutron.show_floatingip.return_value = {}
3357
3358 self.vimconn._prepare_external_network_for_vminstance(
3359 external_network, self.server, created_items, vm_start_time
3360 )
3361 self.assertEqual(mock_get_free_floating_ip.call_count, 1)
3362 mock_get_free_floating_ip.assert_called_with(
3363 self.server,
3364 {
3365 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3366 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3367 "exit_on_floating_ip_error": False,
3368 },
3369 )
3370 self.vimconn.neutron.show_floatingip.assert_not_called()
3371 mock_sleep.assert_not_called()
3372 mock_time.assert_not_called()
3373 self.vimconn.nova.servers.get.assert_not_called()
3374 mock_create_floating_ip.assert_called_with(
3375 floating_network, self.server, created_items
3376 )
3377 self.assertEqual(mock_create_floating_ip.call_count, 1)
3378 mock_assign_floating_ip.assert_not_called()
3379
3380 @patch("time.time")
3381 @patch("time.sleep")
3382 @patch.object(vimconnector, "_create_floating_ip")
3383 @patch.object(vimconnector, "_get_free_floating_ip")
3384 @patch.object(vimconnector, "_assign_floating_ip")
3385 def test_prepare_external_network_for_vm_instance_no_free_fip_can_not_create_fip_exit_on_error_true(
3386 self,
3387 mock_assign_floating_ip,
3388 mock_get_free_floating_ip,
3389 mock_create_floating_ip,
3390 mock_sleep,
3391 mock_time,
3392 ):
3393 """There is not any free floating ip, create_floating ip method raise exception
3394 exit_on_floating_ip_error set to False."""
3395 floating_network = {
3396 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3397 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3398 "exit_on_floating_ip_error": True,
3399 }
3400 external_network = [floating_network]
3401
3402 created_items = {}
3403 vm_start_time = time_return_value
3404 mock_get_free_floating_ip.return_value = None
3405 mock_assign_floating_ip.return_value = {}
3406 mock_create_floating_ip.side_effect = VimConnException(
3407 "Can not create floating ip."
3408 )
3409 self.vimconn.nova.servers.get.return_value.status = "ERROR"
3410 self.vimconn.neutron.show_floatingip.return_value = {}
3411 with self.assertRaises(VimConnException):
3412 self.vimconn._prepare_external_network_for_vminstance(
3413 external_network, self.server, created_items, vm_start_time
3414 )
3415 self.assertEqual(mock_get_free_floating_ip.call_count, 1)
3416 mock_get_free_floating_ip.assert_called_with(
3417 self.server,
3418 {
3419 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3420 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3421 "exit_on_floating_ip_error": True,
3422 },
3423 )
3424 self.vimconn.neutron.show_floatingip.assert_not_called()
3425 mock_sleep.assert_not_called()
3426 mock_time.assert_not_called()
3427 self.vimconn.nova.servers.get.assert_not_called()
3428 mock_create_floating_ip.assert_called_with(
3429 floating_network, self.server, created_items
3430 )
3431 self.assertEqual(mock_create_floating_ip.call_count, 1)
3432 mock_assign_floating_ip.assert_not_called()
3433
3434 @patch.object(vimconnector, "_create_floating_ip")
3435 @patch.object(vimconnector, "_get_free_floating_ip")
3436 @patch.object(vimconnector, "_assign_floating_ip")
3437 def test_prepare_external_network_for_vm_instance_fip_has_port_id(
3438 self,
3439 mock_assign_floating_ip,
3440 mock_get_free_floating_ip,
3441 mock_create_floating_ip,
3442 ):
3443 """Neutron show floating ip return the fip with port_id and floating network vim_id
3444 is different from port_id."""
3445 floating_network = {
3446 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3447 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3448 }
3449 external_network = [floating_network]
3450 created_items = {}
3451 vm_start_time = 150
3452 mock_get_free_floating_ip.side_effect = [
3453 "t08b73-o9cc-1a6a-a270-12cc4811bd4u",
3454 "r08b73-o9cc-1a6a-a270-12cc4811bd4u",
3455 "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3456 ]
3457 mock_assign_floating_ip.side_effect = [
3458 {"floatingip": {"port_id": "k08b73-r9cc-5a6a-a270-82cc4811bd4a"}},
3459 {"floatingip": {"port_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a"}},
3460 ]
3461 self.vimconn.neutron = CopyingMock()
3462 self.vimconn.nova = CopyingMock()
3463 self.vimconn.neutron.show_floatingip.side_effect = [
3464 {"floatingip": {"port_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a"}},
3465 {"floatingip": {"port_id": ""}},
3466 {"floatingip": {"port_id": ""}},
3467 ]
3468 self.vimconn._prepare_external_network_for_vminstance(
3469 external_network, self.server, created_items, vm_start_time
3470 )
3471 self.assertEqual(mock_get_free_floating_ip.call_count, 3)
3472 _call_mock_get_free_floating_ip = mock_get_free_floating_ip.call_args_list
3473 self.assertEqual(
3474 _call_mock_get_free_floating_ip[0][0],
3475 (
3476 self.server,
3477 floating_network,
3478 ),
3479 )
3480 self.assertEqual(
3481 _call_mock_get_free_floating_ip[1][0],
3482 (
3483 self.server,
3484 floating_network,
3485 ),
3486 )
3487 self.assertEqual(
3488 _call_mock_get_free_floating_ip[2][0],
3489 (
3490 self.server,
3491 floating_network,
3492 ),
3493 )
3494 self.assertEqual(self.vimconn.neutron.show_floatingip.call_count, 3)
3495 self.vimconn.nova.servers.get.assert_not_called()
3496 mock_create_floating_ip.assert_not_called()
3497 self.assertEqual(mock_assign_floating_ip.call_count, 2)
3498 _call_mock_assign_floating_ip = mock_assign_floating_ip.call_args_list
3499 self.assertEqual(
3500 _call_mock_assign_floating_ip[0][0],
3501 ("r08b73-o9cc-1a6a-a270-12cc4811bd4u", floating_network),
3502 )
3503 self.assertEqual(
3504 _call_mock_assign_floating_ip[1][0],
3505 ("y08b73-o9cc-1a6a-a270-12cc4811bd4u", floating_network),
3506 )
3507
3508 @patch("time.time")
3509 @patch("time.sleep")
3510 @patch.object(vimconnector, "_create_floating_ip")
3511 @patch.object(vimconnector, "_get_free_floating_ip")
3512 @patch.object(vimconnector, "_assign_floating_ip")
3513 def test_prepare_external_network_for_vm_instance_neutron_show_fip_exception_vm_status_in_error(
3514 self,
3515 mock_assign_floating_ip,
3516 mock_get_free_floating_ip,
3517 mock_create_floating_ip,
3518 mock_sleep,
3519 mock_time,
3520 ):
3521 """Neutron show floating ip gives exception, exit_on_floating_ip_error set to True,
3522 VM status is in error."""
3523 floating_network = {
3524 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3525 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3526 "exit_on_floating_ip_error": True,
3527 }
3528 external_network = [floating_network]
3529 created_items = {}
3530 vm_start_time = time_return_value
3531
3532 mock_time.side_effect = [156570150, 156570800, 156571200]
3533
3534 self.vimconn.nova.servers.get.return_value.status = "ERROR"
3535 self.vimconn.neutron.show_floatingip.side_effect = [
3536 Exception("Floating ip could not be shown.")
3537 ] * 4
3538 with self.assertRaises(Exception) as err:
3539 self.vimconn._prepare_external_network_for_vminstance(
3540 external_network, self.server, created_items, vm_start_time
3541 )
3542 self.assertEqual(
3543 str(err.exception),
3544 "Cannot create floating_ip: Exception Floating ip could not be shown.",
3545 )
3546
3547 self.assertEqual(mock_get_free_floating_ip.call_count, 4)
3548 _call_mock_get_free_floating_ip = mock_get_free_floating_ip.call_args_list
3549 self.assertEqual(
3550 _call_mock_get_free_floating_ip[0][0],
3551 (
3552 self.server,
3553 floating_network,
3554 ),
3555 )
3556 self.assertEqual(
3557 _call_mock_get_free_floating_ip[1][0],
3558 (
3559 self.server,
3560 floating_network,
3561 ),
3562 )
3563 self.assertEqual(
3564 _call_mock_get_free_floating_ip[2][0],
3565 (
3566 self.server,
3567 floating_network,
3568 ),
3569 )
3570 self.assertEqual(
3571 _call_mock_get_free_floating_ip[3][0],
3572 (
3573 self.server,
3574 floating_network,
3575 ),
3576 )
3577
3578 self.assertEqual(self.vimconn.neutron.show_floatingip.call_count, 4)
3579 self.vimconn.nova.servers.get.assert_called_with(self.server.id)
3580 mock_create_floating_ip.assert_not_called()
3581 mock_assign_floating_ip.assert_not_called()
3582 mock_time.assert_not_called()
3583 mock_sleep.assert_not_called()
3584
3585 @patch("time.time")
3586 @patch("time.sleep")
3587 @patch.object(vimconnector, "_create_floating_ip")
3588 @patch.object(vimconnector, "_get_free_floating_ip")
3589 @patch.object(vimconnector, "_assign_floating_ip")
3590 def test_prepare_external_network_for_vm_instance_neutron_show_fip_exception_vm_status_in_active(
3591 self,
3592 mock_assign_floating_ip,
3593 mock_get_free_floating_ip,
3594 mock_create_floating_ip,
3595 mock_sleep,
3596 mock_time,
3597 ):
3598 """Neutron show floating ip gives exception, exit_on_floating_ip_error is set to False,
3599 VM status is in active."""
3600 floating_network = {
3601 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3602 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3603 "exit_on_floating_ip_error": False,
3604 }
3605 external_network = [floating_network]
3606 created_items = {}
3607 vm_start_time = time_return_value
3608
3609 mock_time.side_effect = [156570150, 156570800, 156571200]
3610
3611 self.vimconn.nova.servers.get.return_value.status = "ACTIVE"
3612 self.vimconn.neutron.show_floatingip.side_effect = [
3613 Exception("Floating ip could not be shown.")
3614 ] * 4
3615
3616 self.vimconn._prepare_external_network_for_vminstance(
3617 external_network, self.server, created_items, vm_start_time
3618 )
3619 # self.assertEqual(str(err.exception), "Cannot create floating_ip")
3620
3621 self.assertEqual(mock_get_free_floating_ip.call_count, 4)
3622 _call_mock_get_free_floating_ip = mock_get_free_floating_ip.call_args_list
3623 self.assertEqual(
3624 _call_mock_get_free_floating_ip[0][0],
3625 (
3626 self.server,
3627 floating_network,
3628 ),
3629 )
3630 self.assertEqual(
3631 _call_mock_get_free_floating_ip[1][0],
3632 (
3633 self.server,
3634 floating_network,
3635 ),
3636 )
3637 self.assertEqual(
3638 _call_mock_get_free_floating_ip[2][0],
3639 (
3640 self.server,
3641 floating_network,
3642 ),
3643 )
3644 self.assertEqual(
3645 _call_mock_get_free_floating_ip[3][0],
3646 (
3647 self.server,
3648 floating_network,
3649 ),
3650 )
3651
3652 self.assertEqual(self.vimconn.neutron.show_floatingip.call_count, 4)
3653 self.vimconn.nova.servers.get.assert_called_with(self.server.id)
3654 mock_create_floating_ip.assert_not_called()
3655 mock_assign_floating_ip.assert_not_called()
3656 mock_time.assert_not_called()
3657 mock_sleep.assert_not_called()
3658
3659 @patch("time.time")
3660 @patch("time.sleep")
3661 @patch.object(vimconnector, "_create_floating_ip")
3662 @patch.object(vimconnector, "_get_free_floating_ip")
3663 @patch.object(vimconnector, "_assign_floating_ip")
3664 def test_prepare_external_network_for_vm_instance_neutron_show_fip_exception_exit_on_error(
3665 self,
3666 mock_assign_floating_ip,
3667 mock_get_free_floating_ip,
3668 mock_create_floating_ip,
3669 mock_sleep,
3670 mock_time,
3671 ):
3672 """Neutron show floating ip gives exception, but exit_on_floating_ip_error is set to True.
3673 VM status is not ACTIVE or ERROR, server timeout happened."""
3674 floating_network = {
3675 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3676 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3677 "exit_on_floating_ip_error": True,
3678 }
3679 external_network = [floating_network]
3680 created_items = {}
3681 vm_start_time = time_return_value
3682 mock_get_free_floating_ip.side_effect = None
3683 mock_time.side_effect = [156571790, 156571795, 156571800, 156571805]
3684 self.vimconn.nova.servers.get.return_value.status = "OTHER"
3685 self.vimconn.neutron.show_floatingip.side_effect = [
3686 Exception("Floating ip could not be shown.")
3687 ] * 5
3688
3689 with self.assertRaises(VimConnException) as err:
3690 self.vimconn._prepare_external_network_for_vminstance(
3691 external_network, self.server, created_items, vm_start_time
3692 )
3693 self.assertEqual(
3694 str(err.exception),
3695 "Cannot create floating_ip: Exception Floating ip could not be shown.",
3696 )
3697
3698 self.assertEqual(mock_get_free_floating_ip.call_count, 3)
3699 _call_mock_get_free_floating_ip = mock_get_free_floating_ip.call_args_list
3700 self.assertEqual(
3701 _call_mock_get_free_floating_ip[0][0],
3702 (
3703 self.server,
3704 floating_network,
3705 ),
3706 )
3707 self.assertEqual(
3708 _call_mock_get_free_floating_ip[1][0],
3709 (
3710 self.server,
3711 floating_network,
3712 ),
3713 )
3714 self.assertEqual(
3715 _call_mock_get_free_floating_ip[2][0],
3716 (
3717 self.server,
3718 floating_network,
3719 ),
3720 )
3721
3722 self.assertEqual(self.vimconn.neutron.show_floatingip.call_count, 3)
3723 self.vimconn.nova.servers.get.assert_called_with(self.server.id)
3724 mock_create_floating_ip.assert_not_called()
3725 mock_assign_floating_ip.assert_not_called()
3726 self.assertEqual(mock_time.call_count, 3)
3727 self.assertEqual(mock_sleep.call_count, 2)
3728
3729 @patch("time.time")
3730 @patch("time.sleep")
3731 @patch.object(vimconnector, "_create_floating_ip")
3732 @patch.object(vimconnector, "_get_free_floating_ip")
3733 @patch.object(vimconnector, "_assign_floating_ip")
3734 def test_prepare_external_network_for_vm_instance_assign_floating_ip_exception_exit_on_error(
3735 self,
3736 mock_assign_floating_ip,
3737 mock_get_free_floating_ip,
3738 mock_create_floating_ip,
3739 mock_sleep,
3740 mock_time,
3741 ):
3742 """Assign floating ip method gives exception, exit_on_floating_ip_error is set to True.
3743 VM status is in ERROR."""
3744 floating_network = {
3745 "floating_ip": "y08b73-o9cc-1a6a-a270-12cc4811bd4u",
3746 "vim_id": "608b73-r9cc-5a6a-a270-82cc4811bd4a",
3747 "exit_on_floating_ip_error": True,
3748 }
3749 external_network = [floating_network]
3750 created_items = {}
3751 vm_start_time = time_return_value
3752
3753 mock_get_free_floating_ip.side_effect = [
3754 "y08b73-o9cc-1a6a-a270-12cc4811bd4u"
3755 ] * 4
3756
3757 mock_time.side_effect = [156571790, 156571795, 156571800, 156571805]
3758
3759 mock_assign_floating_ip.side_effect = [
3760 Exception("Floating ip could not be assigned.")
3761 ] * 4
3762
3763 self.vimconn.nova.servers.get.return_value.status = "ERROR"
3764 self.vimconn.neutron.show_floatingip.side_effect = [
3765 {"floatingip": {"port_id": ""}}
3766 ] * 4
3767
3768 with self.assertRaises(VimConnException) as err:
3769 self.vimconn._prepare_external_network_for_vminstance(
3770 external_network, self.server, created_items, vm_start_time
3771 )
3772 self.assertEqual(
3773 str(err.exception),
3774 "Cannot create floating_ip: Exception Floating ip could not be assigned.",
3775 )
3776
3777 self.assertEqual(mock_get_free_floating_ip.call_count, 4)
3778 _call_mock_get_free_floating_ip = mock_get_free_floating_ip.call_args_list
3779 self.assertEqual(
3780 _call_mock_get_free_floating_ip[0][0],
3781 (
3782 self.server,
3783 floating_network,
3784 ),
3785 )
3786 self.assertEqual(
3787 _call_mock_get_free_floating_ip[1][0],
3788 (
3789 self.server,
3790 floating_network,
3791 ),
3792 )
3793 self.assertEqual(
3794 _call_mock_get_free_floating_ip[2][0],
3795 (
3796 self.server,
3797 floating_network,
3798 ),
3799 )
3800
3801 self.assertEqual(self.vimconn.neutron.show_floatingip.call_count, 4)
3802 self.vimconn.neutron.show_floatingip.assert_called_with(
3803 "y08b73-o9cc-1a6a-a270-12cc4811bd4u"
3804 )
3805 self.assertEqual(self.vimconn.nova.servers.get.call_count, 4)
3806 self.vimconn.nova.servers.get.assert_called_with(self.server.id)
3807 mock_time.assert_not_called()
3808 mock_sleep.assert_not_called()
3809 mock_create_floating_ip.assert_not_called()
3810
3811 @patch("time.time")
3812 @patch("time.sleep")
3813 @patch.object(vimconnector, "_create_floating_ip")
3814 @patch.object(vimconnector, "_get_free_floating_ip")
3815 @patch.object(vimconnector, "_assign_floating_ip")
3816 def test_prepare_external_network_for_vm_instance_empty_external_network_list(
3817 self,
3818 mock_assign_floating_ip,
3819 mock_get_free_floating_ip,
3820 mock_create_floating_ip,
3821 mock_sleep,
3822 mock_time,
3823 ):
3824 """External network list is empty."""
3825 external_network = []
3826 created_items = {}
3827 vm_start_time = time_return_value
3828
3829 self.vimconn._prepare_external_network_for_vminstance(
3830 external_network, self.server, created_items, vm_start_time
3831 )
3832 mock_create_floating_ip.assert_not_called()
3833 mock_time.assert_not_called()
3834 mock_sleep.assert_not_called()
3835 mock_assign_floating_ip.assert_not_called()
3836 mock_get_free_floating_ip.assert_not_called()
3837 self.vimconn.neutron.show.show_floatingip.assert_not_called()
3838 self.vimconn.nova.servers.get.assert_not_called()
3839
3840 @patch.object(vimconnector, "_vimconnector__wait_for_vm")
3841 def test_update_port_security_for_vm_instance(self, mock_wait_for_vm):
3842 """no_secured_ports has port and the port has allow-address-pairs."""
3843 no_secured_ports = [(port2_id, "allow-address-pairs")]
3844
3845 self.vimconn._update_port_security_for_vminstance(no_secured_ports, self.server)
3846
3847 mock_wait_for_vm.assert_called_once_with(self.server.id, "ACTIVE")
3848
3849 self.vimconn.neutron.update_port.assert_called_once_with(
3850 port2_id,
3851 {"port": {"allowed_address_pairs": [{"ip_address": "0.0.0.0/0"}]}},
3852 )
3853
3854 @patch.object(vimconnector, "_vimconnector__wait_for_vm")
3855 def test_update_port_security_for_vm_instance_no_allowed_address_pairs(
3856 self, mock_wait_for_vm
3857 ):
3858 """no_secured_ports has port and the port does not have allow-address-pairs."""
3859 no_secured_ports = [(port2_id, "something")]
3860
3861 self.vimconn._update_port_security_for_vminstance(no_secured_ports, self.server)
3862
3863 mock_wait_for_vm.assert_called_once_with(self.server.id, "ACTIVE")
3864
3865 self.vimconn.neutron.update_port.assert_called_once_with(
3866 port2_id,
3867 {"port": {"port_security_enabled": False, "security_groups": None}},
3868 )
3869
3870 @patch.object(vimconnector, "_vimconnector__wait_for_vm")
3871 def test_update_port_security_for_vm_instance_wait_for_vm_raise_exception(
3872 self, mock_wait_for_vm
3873 ):
3874 """__wait_for_vm raises timeout exception."""
3875 no_secured_ports = [(port2_id, "something")]
3876
3877 mock_wait_for_vm.side_effect = VimConnException("Timeout waiting for instance.")
3878
3879 with self.assertRaises(VimConnException) as err:
3880 self.vimconn._update_port_security_for_vminstance(
3881 no_secured_ports, self.server
3882 )
3883 self.assertEqual(str(err.exception), "Timeout waiting for instance.")
3884
3885 mock_wait_for_vm.assert_called_once_with(self.server.id, "ACTIVE")
3886
3887 self.vimconn.neutron.update_port.assert_not_called()
3888
3889 @patch.object(vimconnector, "_vimconnector__wait_for_vm")
3890 def test_update_port_security_for_vm_instance_neutron_update_port_raise_exception(
3891 self, mock_wait_for_vm
3892 ):
3893 """neutron_update_port method raises exception."""
3894 no_secured_ports = [(port2_id, "something")]
3895
3896 self.vimconn.neutron.update_port.side_effect = Exception(
3897 "Port security could not be updated."
3898 )
3899
3900 with self.assertRaises(VimConnException) as err:
3901 self.vimconn._update_port_security_for_vminstance(
3902 no_secured_ports, self.server
3903 )
3904 self.assertEqual(
3905 str(err.exception),
3906 "It was not possible to disable port security for port 17472685-f67f-49fd-8722-eabb7692fc22",
3907 )
3908 mock_wait_for_vm.assert_called_once_with(self.server.id, "ACTIVE")
3909
3910 self.vimconn.neutron.update_port.assert_called_once_with(
3911 port2_id,
3912 {"port": {"port_security_enabled": False, "security_groups": None}},
3913 )
3914
3915 @patch.object(vimconnector, "_vimconnector__wait_for_vm")
3916 def test_update_port_security_for_vm_instance_empty_port_list(
3917 self, mock_wait_for_vm
3918 ):
3919 """no_secured_ports list does not have any ports."""
3920 no_secured_ports = []
3921
3922 self.vimconn._update_port_security_for_vminstance(no_secured_ports, self.server)
3923
3924 mock_wait_for_vm.assert_not_called()
3925
3926 self.vimconn.neutron.update_port.assert_not_called()
3927
3928 @patch("time.time")
3929 @patch.object(vimconnector, "_reload_connection")
3930 @patch.object(vimconnector, "_prepare_network_for_vminstance")
3931 @patch.object(vimconnector, "_create_user_data")
3932 @patch.object(vimconnector, "_get_vm_availability_zone")
3933 @patch.object(vimconnector, "_prepare_disk_for_vminstance")
3934 @patch.object(vimconnector, "_update_port_security_for_vminstance")
3935 @patch.object(vimconnector, "_prepare_external_network_for_vminstance")
3936 @patch.object(vimconnector, "delete_vminstance")
3937 @patch.object(vimconnector, "_format_exception")
3938 def test_new_vm_instance(
3939 self,
3940 mock_format_exception,
3941 mock_delete_vm_instance,
3942 mock_prepare_external_network,
3943 mock_update_port_security,
3944 mock_prepare_disk_for_vm_instance,
3945 mock_get_vm_availability_zone,
3946 mock_create_user_data,
3947 mock_prepare_network_for_vm_instance,
3948 mock_reload_connection,
3949 mock_time,
3950 ):
3951 """New VM instance creation is successful."""
3952
3953 mock_create_user_data.return_value = True, "userdata"
3954
3955 mock_get_vm_availability_zone.return_value = "nova"
3956
3957 self.vimconn.nova.servers.create.return_value = self.server
3958
3959 mock_time.return_value = time_return_value
3960
3961 expected_result = self.server.id, {}
3962
3963 result = self.vimconn.new_vminstance(
3964 name,
3965 description,
3966 start,
3967 image_id,
3968 flavor_id,
3969 affinity_group_list,
3970 net_list,
3971 cloud_config,
3972 disk_list2,
3973 availability_zone_index,
3974 availability_zone_list,
3975 )
3976 self.assertEqual(result, expected_result)
3977
3978 mock_reload_connection.assert_called_once()
3979 mock_prepare_network_for_vm_instance.assert_called_once_with(
3980 name=name,
3981 net_list=net_list,
3982 created_items={},
3983 net_list_vim=[],
3984 external_network=[],
3985 no_secured_ports=[],
3986 )
3987 mock_create_user_data.assert_called_once_with(cloud_config)
3988 mock_get_vm_availability_zone.assert_called_once_with(
3989 availability_zone_index, availability_zone_list
3990 )
3991 mock_prepare_disk_for_vm_instance.assert_called_once_with(
3992 name=name,
3993 existing_vim_volumes=[],
3994 created_items={},
3995 vm_av_zone="nova",
3996 disk_list=disk_list2,
3997 )
3998 self.vimconn.nova.servers.create.assert_called_once_with(
3999 name=name,
4000 image=image_id,
4001 flavor=flavor_id,
4002 nics=[],
4003 security_groups="default",
4004 availability_zone="nova",
4005 key_name="my_keypair",
4006 userdata="userdata",
4007 config_drive=True,
4008 block_device_mapping=None,
4009 scheduler_hints={},
4010 )
4011 mock_time.assert_called_once()
4012 mock_update_port_security.assert_called_once_with([], self.server)
4013 mock_prepare_external_network.assert_called_once_with(
4014 external_network=[],
4015 server=self.server,
4016 created_items={},
4017 vm_start_time=time_return_value,
4018 )
4019 mock_delete_vm_instance.assert_not_called()
4020 mock_format_exception.assert_not_called()
4021
4022 @patch("time.time")
4023 @patch.object(vimconnector, "_reload_connection")
4024 @patch.object(vimconnector, "_prepare_network_for_vminstance")
4025 @patch.object(vimconnector, "_create_user_data")
4026 @patch.object(vimconnector, "_get_vm_availability_zone")
4027 @patch.object(vimconnector, "_prepare_disk_for_vminstance")
4028 @patch.object(vimconnector, "_update_port_security_for_vminstance")
4029 @patch.object(vimconnector, "_prepare_external_network_for_vminstance")
4030 @patch.object(vimconnector, "delete_vminstance")
4031 @patch.object(vimconnector, "_format_exception")
4032 def test_new_vm_instance_create_user_data_fails(
4033 self,
4034 mock_format_exception,
4035 mock_delete_vm_instance,
4036 mock_prepare_external_network,
4037 mock_update_port_security,
4038 mock_prepare_disk_for_vm_instance,
4039 mock_get_vm_availability_zone,
4040 mock_create_user_data,
4041 mock_prepare_network_for_vm_instance,
4042 mock_reload_connection,
4043 mock_time,
4044 ):
4045 """New VM instance creation failed because of user data creation failure."""
4046
4047 mock_create_user_data.side_effect = Exception(
4048 "User data could not be retrieved."
4049 )
4050
4051 mock_get_vm_availability_zone.return_value = "nova"
4052
4053 self.vimconn.nova.servers.create.return_value = self.server
4054
4055 mock_time.return_value = time_return_value
4056
4057 self.vimconn.new_vminstance(
4058 name,
4059 description,
4060 start,
4061 image_id,
4062 flavor_id,
4063 affinity_group_list,
4064 net_list,
4065 cloud_config,
4066 disk_list,
4067 availability_zone_index,
4068 availability_zone_list,
4069 )
4070
4071 mock_reload_connection.assert_called_once()
4072 mock_prepare_network_for_vm_instance.assert_called_once_with(
4073 name=name,
4074 net_list=net_list,
4075 created_items={},
4076 net_list_vim=[],
4077 external_network=[],
4078 no_secured_ports=[],
4079 )
4080 mock_create_user_data.assert_called_once_with(cloud_config)
4081 mock_get_vm_availability_zone.assert_not_called()
4082 mock_prepare_disk_for_vm_instance.assert_not_called()
4083 self.vimconn.nova.servers.create.assert_not_called()
4084 mock_time.assert_not_called()
4085 mock_update_port_security.assert_not_called()
4086 mock_prepare_external_network.assert_not_called()
4087 mock_delete_vm_instance.assert_called_once_with(None, {})
4088 mock_format_exception.assert_called_once()
4089 arg = mock_format_exception.call_args[0][0]
4090 self.assertEqual(str(arg), "User data could not be retrieved.")
4091
4092 @patch("time.time")
4093 @patch.object(vimconnector, "_reload_connection")
4094 @patch.object(vimconnector, "_prepare_network_for_vminstance")
4095 @patch.object(vimconnector, "_create_user_data")
4096 @patch.object(vimconnector, "_get_vm_availability_zone")
4097 @patch.object(vimconnector, "_prepare_disk_for_vminstance")
4098 @patch.object(vimconnector, "_update_port_security_for_vminstance")
4099 @patch.object(vimconnector, "_prepare_external_network_for_vminstance")
4100 @patch.object(vimconnector, "delete_vminstance")
4101 @patch.object(vimconnector, "_format_exception")
4102 def test_new_vm_instance_external_network_exception(
4103 self,
4104 mock_format_exception,
4105 mock_delete_vm_instance,
4106 mock_prepare_external_network,
4107 mock_update_port_security,
4108 mock_prepare_disk_for_vm_instance,
4109 mock_get_vm_availability_zone,
4110 mock_create_user_data,
4111 mock_prepare_network_for_vm_instance,
4112 mock_reload_connection,
4113 mock_time,
4114 ):
4115 """New VM instance creation, external network connection has failed as floating
4116 ip could not be created."""
4117
4118 mock_create_user_data.return_value = True, "userdata"
4119
4120 mock_get_vm_availability_zone.return_value = "nova"
4121
4122 self.vimconn.nova.servers.create.return_value = self.server
4123
4124 mock_time.return_value = time_return_value
4125
4126 mock_prepare_external_network.side_effect = VimConnException(
4127 "Can not create floating ip."
4128 )
4129
4130 self.vimconn.new_vminstance(
4131 name,
4132 description,
4133 start,
4134 image_id,
4135 flavor_id,
4136 affinity_group_list,
4137 net_list,
4138 cloud_config,
4139 disk_list2,
4140 availability_zone_index,
4141 availability_zone_list,
4142 )
4143
4144 mock_reload_connection.assert_called_once()
4145 mock_prepare_network_for_vm_instance.assert_called_once_with(
4146 name=name,
4147 net_list=net_list,
4148 created_items={},
4149 net_list_vim=[],
4150 external_network=[],
4151 no_secured_ports=[],
4152 )
4153 mock_create_user_data.assert_called_once_with(cloud_config)
4154 mock_get_vm_availability_zone.assert_called_once_with(
4155 availability_zone_index, availability_zone_list
4156 )
4157 mock_prepare_disk_for_vm_instance.assert_called_once_with(
4158 name=name,
4159 existing_vim_volumes=[],
4160 created_items={},
4161 vm_av_zone="nova",
4162 disk_list=disk_list2,
4163 )
4164 self.vimconn.nova.servers.create.assert_called_once_with(
4165 name=name,
4166 image=image_id,
4167 flavor=flavor_id,
4168 nics=[],
4169 security_groups="default",
4170 availability_zone="nova",
4171 key_name="my_keypair",
4172 userdata="userdata",
4173 config_drive=True,
4174 block_device_mapping=None,
4175 scheduler_hints={},
4176 )
4177 mock_time.assert_called_once()
4178 mock_update_port_security.assert_called_once_with([], self.server)
4179 mock_prepare_external_network.assert_called_once_with(
4180 external_network=[],
4181 server=self.server,
4182 created_items={},
4183 vm_start_time=time_return_value,
4184 )
4185 mock_delete_vm_instance.assert_called_once_with(self.server.id, {})
4186 mock_format_exception.assert_called_once()
4187 arg = mock_format_exception.call_args[0][0]
4188 self.assertEqual(str(arg), "Can not create floating ip.")
4189
4190 @patch("time.time")
4191 @patch.object(vimconnector, "_reload_connection")
4192 @patch.object(vimconnector, "_prepare_network_for_vminstance")
4193 @patch.object(vimconnector, "_create_user_data")
4194 @patch.object(vimconnector, "_get_vm_availability_zone")
4195 @patch.object(vimconnector, "_prepare_disk_for_vminstance")
4196 @patch.object(vimconnector, "_update_port_security_for_vminstance")
4197 @patch.object(vimconnector, "_prepare_external_network_for_vminstance")
4198 @patch.object(vimconnector, "delete_vminstance")
4199 @patch.object(vimconnector, "_format_exception")
4200 def test_new_vm_instance_with_affinity_group(
4201 self,
4202 mock_format_exception,
4203 mock_delete_vm_instance,
4204 mock_prepare_external_network,
4205 mock_update_port_security,
4206 mock_prepare_disk_for_vm_instance,
4207 mock_get_vm_availability_zone,
4208 mock_create_user_data,
4209 mock_prepare_network_for_vm_instance,
4210 mock_reload_connection,
4211 mock_time,
4212 ):
4213 """New VM creation with affinity group."""
4214 affinity_group_list = [
4215 {"affinity_group_id": "38b73-e9cc-5a6a-t270-82cc4811bd4a"}
4216 ]
4217 mock_create_user_data.return_value = True, "userdata"
4218 mock_get_vm_availability_zone.return_value = "nova"
4219 self.vimconn.nova.servers.create.return_value = self.server
4220 mock_time.return_value = time_return_value
4221 expected_result = self.server.id, {}
4222
4223 result = self.vimconn.new_vminstance(
4224 name,
4225 description,
4226 start,
4227 image_id,
4228 flavor_id,
4229 affinity_group_list,
4230 net_list,
4231 cloud_config,
4232 disk_list2,
4233 availability_zone_index,
4234 availability_zone_list,
4235 )
4236 self.assertEqual(result, expected_result)
4237
4238 mock_reload_connection.assert_called_once()
4239 mock_prepare_network_for_vm_instance.assert_called_once_with(
4240 name=name,
4241 net_list=net_list,
4242 created_items={},
4243 net_list_vim=[],
4244 external_network=[],
4245 no_secured_ports=[],
4246 )
4247 mock_create_user_data.assert_called_once_with(cloud_config)
4248 mock_get_vm_availability_zone.assert_called_once_with(
4249 availability_zone_index, availability_zone_list
4250 )
4251 mock_prepare_disk_for_vm_instance.assert_called_once_with(
4252 name=name,
4253 existing_vim_volumes=[],
4254 created_items={},
4255 vm_av_zone="nova",
4256 disk_list=disk_list2,
4257 )
4258 self.vimconn.nova.servers.create.assert_called_once_with(
4259 name=name,
4260 image=image_id,
4261 flavor=flavor_id,
4262 nics=[],
4263 security_groups="default",
4264 availability_zone="nova",
4265 key_name="my_keypair",
4266 userdata="userdata",
4267 config_drive=True,
4268 block_device_mapping=None,
4269 scheduler_hints={"group": "38b73-e9cc-5a6a-t270-82cc4811bd4a"},
4270 )
4271 mock_time.assert_called_once()
4272 mock_update_port_security.assert_called_once_with([], self.server)
4273 mock_prepare_external_network.assert_called_once_with(
4274 external_network=[],
4275 server=self.server,
4276 created_items={},
4277 vm_start_time=time_return_value,
4278 )
4279 mock_delete_vm_instance.assert_not_called()
4280 mock_format_exception.assert_not_called()
4281
4282 @patch("time.time")
4283 @patch.object(vimconnector, "_reload_connection")
4284 @patch.object(vimconnector, "_prepare_network_for_vminstance")
4285 @patch.object(vimconnector, "_create_user_data")
4286 @patch.object(vimconnector, "_get_vm_availability_zone")
4287 @patch.object(vimconnector, "_prepare_disk_for_vminstance")
4288 @patch.object(vimconnector, "_update_port_security_for_vminstance")
4289 @patch.object(vimconnector, "_prepare_external_network_for_vminstance")
4290 @patch.object(vimconnector, "delete_vminstance")
4291 @patch.object(vimconnector, "_format_exception")
4292 def test_new_vm_instance_nova_server_create_failed(
4293 self,
4294 mock_format_exception,
4295 mock_delete_vm_instance,
4296 mock_prepare_external_network,
4297 mock_update_port_security,
4298 mock_prepare_disk_for_vm_instance,
4299 mock_get_vm_availability_zone,
4300 mock_create_user_data,
4301 mock_prepare_network_for_vm_instance,
4302 mock_reload_connection,
4303 mock_time,
4304 ):
4305 """New VM(server) creation failed."""
4306
4307 mock_create_user_data.return_value = True, "userdata"
4308
4309 mock_get_vm_availability_zone.return_value = "nova"
4310
4311 self.vimconn.nova.servers.create.side_effect = Exception(
4312 "Server could not be created."
4313 )
4314
4315 mock_time.return_value = time_return_value
4316
4317 self.vimconn.new_vminstance(
4318 name,
4319 description,
4320 start,
4321 image_id,
4322 flavor_id,
4323 affinity_group_list,
4324 net_list,
4325 cloud_config,
4326 disk_list2,
4327 availability_zone_index,
4328 availability_zone_list,
4329 )
4330
4331 mock_reload_connection.assert_called_once()
4332 mock_prepare_network_for_vm_instance.assert_called_once_with(
4333 name=name,
4334 net_list=net_list,
4335 created_items={},
4336 net_list_vim=[],
4337 external_network=[],
4338 no_secured_ports=[],
4339 )
4340 mock_create_user_data.assert_called_once_with(cloud_config)
4341 mock_get_vm_availability_zone.assert_called_once_with(
4342 availability_zone_index, availability_zone_list
4343 )
4344 mock_prepare_disk_for_vm_instance.assert_called_once_with(
4345 name=name,
4346 existing_vim_volumes=[],
4347 created_items={},
4348 vm_av_zone="nova",
4349 disk_list=disk_list2,
4350 )
4351
4352 self.vimconn.nova.servers.create.assert_called_once_with(
4353 name=name,
4354 image=image_id,
4355 flavor=flavor_id,
4356 nics=[],
4357 security_groups="default",
4358 availability_zone="nova",
4359 key_name="my_keypair",
4360 userdata="userdata",
4361 config_drive=True,
4362 block_device_mapping=None,
4363 scheduler_hints={},
4364 )
4365 mock_time.assert_not_called()
4366 mock_update_port_security.assert_not_called()
4367 mock_prepare_external_network.assert_not_called()
4368 mock_delete_vm_instance.assert_called_once_with(None, {})
4369 mock_format_exception.assert_called_once()
4370 arg = mock_format_exception.call_args[0][0]
4371 self.assertEqual(str(arg), "Server could not be created.")
4372
4373 @patch("time.time")
4374 @patch.object(vimconnector, "_reload_connection")
4375 @patch.object(vimconnector, "_prepare_network_for_vminstance")
4376 @patch.object(vimconnector, "_create_user_data")
4377 @patch.object(vimconnector, "_get_vm_availability_zone")
4378 @patch.object(vimconnector, "_prepare_disk_for_vminstance")
4379 @patch.object(vimconnector, "_update_port_security_for_vminstance")
4380 @patch.object(vimconnector, "_prepare_external_network_for_vminstance")
4381 @patch.object(vimconnector, "delete_vminstance")
4382 @patch.object(vimconnector, "_format_exception")
4383 def test_new_vm_instance_connection_exception(
4384 self,
4385 mock_format_exception,
4386 mock_delete_vm_instance,
4387 mock_prepare_external_network,
4388 mock_update_port_security,
4389 mock_prepare_disk_for_vm_instance,
4390 mock_get_vm_availability_zone,
4391 mock_create_user_data,
4392 mock_prepare_network_for_vm_instance,
4393 mock_reload_connection,
4394 mock_time,
4395 ):
4396 """Connection to Cloud API has failed."""
4397 mock_reload_connection.side_effect = Exception("Can not connect to Cloud APIs.")
4398 mock_create_user_data.return_value = True, "userdata"
4399 mock_get_vm_availability_zone.return_value = "nova"
4400 self.vimconn.nova.servers.create.return_value = self.server
4401 mock_time.return_value = time_return_value
4402
4403 self.vimconn.new_vminstance(
4404 name,
4405 description,
4406 start,
4407 image_id,
4408 flavor_id,
4409 affinity_group_list,
4410 net_list,
4411 cloud_config,
4412 disk_list,
4413 availability_zone_index,
4414 availability_zone_list,
4415 )
4416 mock_format_exception.assert_called_once()
4417 arg = mock_format_exception.call_args[0][0]
4418 self.assertEqual(str(arg), "Can not connect to Cloud APIs.")
4419 mock_reload_connection.assert_called_once()
4420 mock_prepare_network_for_vm_instance.assert_not_called()
4421 mock_create_user_data.assert_not_called()
4422 mock_get_vm_availability_zone.assert_not_called()
4423 mock_prepare_disk_for_vm_instance.assert_not_called()
4424 self.vimconn.nova.servers.create.assert_not_called()
4425 mock_time.assert_not_called()
4426 mock_update_port_security.assert_not_called()
4427 mock_prepare_external_network.assert_not_called()
4428 mock_delete_vm_instance.assert_called_once_with(None, {})
4429
4430 @patch.object(vimconnector, "_delete_ports_by_id_wth_neutron")
4431 def test_delete_vm_ports_attached_to_network_empty_created_items(
4432 self, mock_delete_ports_by_id_wth_neutron
4433 ):
4434 """Created_items is emtpty."""
4435 created_items = {}
4436 self.vimconn._delete_vm_ports_attached_to_network(created_items)
4437 self.vimconn.neutron.list_ports.assert_not_called()
4438 self.vimconn.neutron.delete_port.assert_not_called()
4439 mock_delete_ports_by_id_wth_neutron.assert_not_called()
4440
4441 @patch.object(vimconnector, "_delete_ports_by_id_wth_neutron")
4442 def test_delete_vm_ports_attached_to_network(
4443 self, mock_delete_ports_by_id_wth_neutron
4444 ):
4445 created_items = {
4446 "floating_ip:308b73-t9cc-1a6a-a270-12cc4811bd4a": True,
4447 f"volume:{volume_id2}": True,
4448 f"volume:{volume_id}": True,
4449 f"port:{port_id}": True,
4450 }
4451 self.vimconn._delete_vm_ports_attached_to_network(created_items)
4452 mock_delete_ports_by_id_wth_neutron.assert_called_once_with(f"{port_id}")
4453 self.vimconn.logger.error.assert_not_called()
4454
4455 @patch.object(vimconnector, "_delete_ports_by_id_wth_neutron")
4456 def test_delete_vm_ports_attached_to_network_wthout_port(
4457 self, mock_delete_ports_by_id_wth_neutron
4458 ):
4459 """Created_items does not have port."""
4460 created_items = {
4461 f"floating_ip:{floating_network_vim_id}": True,
4462 f"volume:{volume_id2}": True,
4463 f"volume:{volume_id}": True,
4464 }
4465 self.vimconn._delete_vm_ports_attached_to_network(created_items)
4466 mock_delete_ports_by_id_wth_neutron.assert_not_called()
4467 self.vimconn.logger.error.assert_not_called()
4468
4469 @patch.object(vimconnector, "_delete_ports_by_id_wth_neutron")
4470 def test_delete_vm_ports_attached_to_network_delete_port_raise_vimconnexception(
4471 self, mock_delete_ports_by_id_wth_neutron
4472 ):
4473 """_delete_ports_by_id_wth_neutron raises vimconnexception."""
4474 created_items = deepcopy(created_items_all_true)
4475 mock_delete_ports_by_id_wth_neutron.side_effect = VimConnException(
4476 "Can not delete port"
4477 )
4478 self.vimconn._delete_vm_ports_attached_to_network(created_items)
4479 mock_delete_ports_by_id_wth_neutron.assert_called_once_with(f"{port_id}")
4480 self.vimconn.logger.error.assert_called_once_with(
4481 "Error deleting port: VimConnException: Can not delete port"
4482 )
4483
4484 @patch.object(vimconnector, "_delete_ports_by_id_wth_neutron")
4485 def test_delete_vm_ports_attached_to_network_delete_port_raise_nvexception(
4486 self, mock_delete_ports_by_id_wth_neutron
4487 ):
4488 """_delete_ports_by_id_wth_neutron raises nvExceptions.ClientException."""
4489 created_items = deepcopy(created_items_all_true)
4490 mock_delete_ports_by_id_wth_neutron.side_effect = nvExceptions.ClientException(
4491 "Connection aborted."
4492 )
4493 self.vimconn._delete_vm_ports_attached_to_network(created_items)
4494 mock_delete_ports_by_id_wth_neutron.assert_called_once_with(f"{port_id}")
4495 self.vimconn.logger.error.assert_called_once_with(
4496 "Error deleting port: ClientException: Unknown Error (HTTP Connection aborted.)"
4497 )
4498
4499 @patch.object(vimconnector, "_delete_ports_by_id_wth_neutron")
4500 def test_delete_vm_ports_attached_to_network_delete_port_invalid_port_item(
4501 self, mock_delete_ports_by_id_wth_neutron
4502 ):
4503 """port item is invalid."""
4504 created_items = {
4505 f"floating_ip:{floating_network_vim_id}": True,
4506 f"volume:{volume_id2}": True,
4507 f"volume:{volume_id}": True,
4508 f"port:{port_id}:": True,
4509 }
4510 mock_delete_ports_by_id_wth_neutron.side_effect = VimConnException(
4511 "Port is not valid."
4512 )
4513 self.vimconn._delete_vm_ports_attached_to_network(created_items)
4514 mock_delete_ports_by_id_wth_neutron.assert_called_once_with(f"{port_id}:")
4515 self.vimconn.logger.error.assert_called_once_with(
4516 "Error deleting port: VimConnException: Port is not valid."
4517 )
4518
4519 @patch.object(vimconnector, "_delete_ports_by_id_wth_neutron")
4520 def test_delete_vm_ports_attached_to_network_delete_port_already_deleted(
4521 self, mock_delete_ports_by_id_wth_neutron
4522 ):
4523 """port is already deleted."""
4524 created_items = {
4525 f"floating_ip:{floating_network_vim_id}": True,
4526 f"volume:{volume_id2}": True,
4527 f"volume:{volume_id}": None,
4528 f"port:{port_id}": None,
4529 }
4530 self.vimconn._delete_vm_ports_attached_to_network(created_items)
4531 mock_delete_ports_by_id_wth_neutron.assert_not_called()
4532 self.vimconn.logger.error.assert_not_called()
4533
4534 def test_delete_floating_ip_by_id(self):
4535 created_items = {
4536 f"floating_ip:{floating_network_vim_id}": True,
4537 f"port:{port_id}": True,
4538 }
4539 expected_created_items = {
4540 f"floating_ip:{floating_network_vim_id}": None,
4541 f"port:{port_id}": True,
4542 }
4543 k_id = floating_network_vim_id
4544 k = f"floating_ip:{floating_network_vim_id}"
4545 self.vimconn._delete_floating_ip_by_id(k, k_id, created_items)
4546 self.vimconn.neutron.delete_floatingip.assert_called_once_with(k_id)
4547 self.assertEqual(created_items, expected_created_items)
4548
4549 def test_delete_floating_ip_by_id_floating_ip_already_deleted(self):
4550 """floating ip is already deleted."""
4551 created_items = {
4552 f"floating_ip:{floating_network_vim_id}": None,
4553 f"port:{port_id}": True,
4554 }
4555 k_id = floating_network_vim_id
4556 k = f"floating_ip:{floating_network_vim_id}"
4557 self.vimconn._delete_floating_ip_by_id(k, k_id, created_items)
4558 self.vimconn.neutron.delete_floatingip.assert_called_once_with(k_id)
4559 self.assertEqual(
4560 created_items,
4561 {
4562 f"floating_ip:{floating_network_vim_id}": None,
4563 f"port:{port_id}": True,
4564 },
4565 )
4566
4567 def test_delete_floating_ip_by_id_floating_ip_raises_nvexception(self):
4568 """netron delete floating ip raises nvExceptions.ClientException."""
4569 created_items = {
4570 f"floating_ip:{floating_network_vim_id}": True,
4571 f"port:{port_id}": True,
4572 }
4573 k_id = floating_network_vim_id
4574 k = f"floating_ip:{floating_network_vim_id}"
4575 self.vimconn.neutron.delete_floatingip.side_effect = (
4576 nvExceptions.ClientException("Client exception occured.")
4577 )
4578 self.vimconn._delete_floating_ip_by_id(k, k_id, created_items)
4579 self.vimconn.neutron.delete_floatingip.assert_called_once_with(k_id)
4580 self.assertEqual(
4581 created_items,
4582 {
4583 f"floating_ip:{floating_network_vim_id}": True,
4584 f"port:{port_id}": True,
4585 },
4586 )
4587 self.vimconn.logger.error.assert_called_once_with(
4588 "Error deleting floating ip: ClientException: Unknown Error (HTTP Client exception occured.)"
4589 )
4590
4591 def test_delete_floating_ip_by_id_floating_ip_raises_vimconnexception(self):
4592 """netron delete floating ip raises VimConnNotFoundException."""
4593 created_items = {
4594 f"floating_ip:{floating_network_vim_id}": True,
4595 f"port:{port_id}": True,
4596 }
4597 k_id = floating_network_vim_id
4598 k = f"floating_ip:{floating_network_vim_id}"
4599 self.vimconn.neutron.delete_floatingip.side_effect = VimConnNotFoundException(
4600 "Port id could not found."
4601 )
4602 self.vimconn._delete_floating_ip_by_id(k, k_id, created_items)
4603 self.vimconn.neutron.delete_floatingip.assert_called_once_with(k_id)
4604 self.assertEqual(
4605 created_items,
4606 {
4607 f"floating_ip:{floating_network_vim_id}": True,
4608 f"port:{port_id}": True,
4609 },
4610 )
4611 self.vimconn.logger.error.assert_called_once_with(
4612 "Error deleting floating ip: VimConnNotFoundException: Port id could not found."
4613 )
4614
4615 def test_delete_floating_ip_by_id_floating_ip_invalid_k_item(self):
4616 """invalid floating ip item."""
4617 created_items = {
4618 f"floating_ip:{floating_network_vim_id}": True,
4619 f"port:{port_id}": True,
4620 }
4621 expected_created_items = {
4622 f"floating_ip:{floating_network_vim_id}::": None,
4623 f"floating_ip:{floating_network_vim_id}": True,
4624 f"port:{port_id}": True,
4625 }
4626 k_id = floating_network_vim_id
4627 k = f"floating_ip:{floating_network_vim_id}::"
4628 self.vimconn._delete_floating_ip_by_id(k, k_id, created_items)
4629 self.vimconn.neutron.delete_floatingip.assert_called_once_with(k_id)
4630 self.assertEqual(created_items, expected_created_items)
4631
4632 def test_delete_volumes_by_id_with_cinder_volume_status_available(self):
4633 """volume status is available."""
4634 created_items = {
4635 f"floating_ip:{floating_network_vim_id}": True,
4636 f"volume:{volume_id2}": True,
4637 f"volume:{volume_id}": True,
4638 f"port:{port_id}": None,
4639 }
4640 expected_created_items = {
4641 f"floating_ip:{floating_network_vim_id}": True,
4642 f"volume:{volume_id2}": True,
4643 f"volume:{volume_id}": None,
4644 f"port:{port_id}": None,
4645 }
4646 volumes_to_hold = []
4647 k = f"volume:{volume_id}"
4648 k_id = volume_id
4649 self.vimconn.cinder.volumes.get.return_value.status = "available"
4650 result = self.vimconn._delete_volumes_by_id_wth_cinder(
4651 k, k_id, volumes_to_hold, created_items
4652 )
4653 self.assertEqual(result, None)
4654 self.vimconn.cinder.volumes.get.assert_called_once_with(k_id)
4655 self.vimconn.cinder.volumes.delete.assert_called_once_with(k_id)
4656 self.vimconn.logger.error.assert_not_called()
4657 self.assertEqual(created_items, expected_created_items)
4658
4659 def test_delete_volumes_by_id_with_cinder_volume_already_deleted(self):
4660 """volume is already deleted."""
4661 created_items = {
4662 f"floating_ip:{floating_network_vim_id}": True,
4663 f"volume:{volume_id2}": True,
4664 f"volume:{volume_id}": None,
4665 f"port:{port_id}": None,
4666 }
4667 expected_created_items = {
4668 f"floating_ip:{floating_network_vim_id}": True,
4669 f"volume:{volume_id2}": True,
4670 f"volume:{volume_id}": None,
4671 f"port:{port_id}": None,
4672 }
4673 volumes_to_hold = []
4674 k = f"volume:{volume_id}"
4675 k_id = volume_id
4676 self.vimconn.cinder.volumes.get.return_value.status = "available"
4677 result = self.vimconn._delete_volumes_by_id_wth_cinder(
4678 k, k_id, volumes_to_hold, created_items
4679 )
4680 self.assertEqual(result, None)
4681 self.vimconn.cinder.volumes.get.assert_called_once_with(k_id)
4682 self.vimconn.cinder.volumes.delete.assert_called_once_with(k_id)
4683 self.vimconn.logger.error.assert_not_called()
4684 self.assertEqual(created_items, expected_created_items)
4685
4686 def test_delete_volumes_by_id_with_cinder_get_volume_raise_exception(self):
4687 """cinder get volume raises exception."""
4688 created_items = {
4689 f"floating_ip:{floating_network_vim_id}": True,
4690 f"volume:{volume_id2}": True,
4691 f"volume:{volume_id}": True,
4692 f"port:{port_id}": None,
4693 }
4694 expected_created_items = {
4695 f"floating_ip:{floating_network_vim_id}": True,
4696 f"volume:{volume_id2}": True,
4697 f"volume:{volume_id}": True,
4698 f"port:{port_id}": None,
4699 }
4700 volumes_to_hold = []
4701 k = f"volume:{volume_id}"
4702 k_id = volume_id
4703 self.vimconn.cinder.volumes.get.side_effect = Exception(
4704 "Can not get volume status."
4705 )
4706 result = self.vimconn._delete_volumes_by_id_wth_cinder(
4707 k, k_id, volumes_to_hold, created_items
4708 )
4709 self.assertEqual(result, None)
4710 self.vimconn.cinder.volumes.get.assert_called_once_with(k_id)
4711 self.vimconn.cinder.volumes.delete.assert_not_called()
4712 self.vimconn.logger.error.assert_called_once_with(
4713 "Error deleting volume: Exception: Can not get volume status."
4714 )
4715 self.assertEqual(created_items, expected_created_items)
4716
4717 def test_delete_volumes_by_id_with_cinder_delete_volume_raise_exception(self):
4718 """cinder delete volume raises exception."""
4719 created_items = {
4720 f"floating_ip:{floating_network_vim_id}": True,
4721 f"volume:{volume_id2}": True,
4722 f"volume:{volume_id}": True,
4723 f"port:{port_id}": None,
4724 }
4725 expected_created_items = {
4726 f"floating_ip:{floating_network_vim_id}": True,
4727 f"volume:{volume_id2}": True,
4728 f"volume:{volume_id}": True,
4729 f"port:{port_id}": None,
4730 }
4731 volumes_to_hold = []
4732 k = f"volume:{volume_id}"
4733 k_id = volume_id
4734 self.vimconn.cinder.volumes.get.return_value.status = "available"
4735 self.vimconn.cinder.volumes.delete.side_effect = nvExceptions.ClientException(
4736 "Connection aborted."
4737 )
4738 result = self.vimconn._delete_volumes_by_id_wth_cinder(
4739 k, k_id, volumes_to_hold, created_items
4740 )
4741 self.assertEqual(result, None)
4742 self.vimconn.cinder.volumes.get.assert_called_once_with(k_id)
4743 self.vimconn.cinder.volumes.delete.assert_called_once_with(k_id)
4744 self.vimconn.logger.error.assert_called_once_with(
4745 "Error deleting volume: ClientException: Unknown Error (HTTP Connection aborted.)"
4746 )
4747 self.assertEqual(created_items, expected_created_items)
4748
4749 def test_delete_volumes_by_id_with_cinder_volume_to_be_hold(self):
4750 """volume_to_hold has item."""
4751 created_items = {
4752 f"floating_ip:{floating_network_vim_id}": True,
4753 f"volume:{volume_id2}": True,
4754 f"volume:{volume_id}": True,
4755 f"port:{port_id}": None,
4756 }
4757 expected_created_items = {
4758 f"floating_ip:{floating_network_vim_id}": True,
4759 f"volume:{volume_id2}": True,
4760 f"volume:{volume_id}": True,
4761 f"port:{port_id}": None,
4762 }
4763 volumes_to_hold = [volume_id]
4764 k = f"volume:{volume_id}"
4765 k_id = volume_id
4766 result = self.vimconn._delete_volumes_by_id_wth_cinder(
4767 k, k_id, volumes_to_hold, created_items
4768 )
4769 self.assertEqual(result, None)
4770 self.vimconn.cinder.volumes.get.assert_not_called()
4771 self.vimconn.cinder.volumes.delete.assert_not_called()
4772 self.vimconn.logger.error.assert_not_called()
4773 self.assertEqual(created_items, expected_created_items)
4774
4775 def test_delete_volumes_by_id_with_cinder_volume_status_not_available(self):
4776 """volume status is not available."""
4777 created_items = {
4778 f"floating_ip:{floating_network_vim_id}": True,
4779 f"volume:{volume_id2}": True,
4780 f"volume:{volume_id}": True,
4781 f"port:{port_id}": None,
4782 }
4783 expected_created_items = {
4784 f"floating_ip:{floating_network_vim_id}": True,
4785 f"volume:{volume_id2}": True,
4786 f"volume:{volume_id}": True,
4787 f"port:{port_id}": None,
4788 }
4789 volumes_to_hold = []
4790 k = f"volume:{volume_id}"
4791 k_id = volume_id
4792 self.vimconn.cinder.volumes.get.return_value.status = "unavailable"
4793 result = self.vimconn._delete_volumes_by_id_wth_cinder(
4794 k, k_id, volumes_to_hold, created_items
4795 )
4796 self.assertEqual(result, True)
4797 self.vimconn.cinder.volumes.get.assert_called_once_with(k_id)
4798 self.vimconn.cinder.volumes.delete.assert_not_called()
4799 self.vimconn.logger.error.assert_not_called()
4800 self.assertEqual(created_items, expected_created_items)
4801
4802 def test_delete_ports_by_id_by_neutron(self):
4803 """neutron delete ports."""
4804 k_id = port_id
4805 self.vimconn.neutron.list_ports.return_value = {
4806 "ports": [{"id": port_id}, {"id": port2_id}]
4807 }
4808
4809 self.vimconn._delete_ports_by_id_wth_neutron(k_id)
4810 self.vimconn.neutron.list_ports.assert_called_once()
4811 self.vimconn.neutron.delete_port.assert_called_once_with(k_id)
4812 self.vimconn.logger.error.assert_not_called()
4813
4814 def test_delete_ports_by_id_by_neutron_id_not_in_port_list(self):
4815 """port id not in the port list."""
4816 k_id = volume_id
4817 self.vimconn.neutron.list_ports.return_value = {
4818 "ports": [{"id": port_id}, {"id": port2_id}]
4819 }
4820
4821 self.vimconn._delete_ports_by_id_wth_neutron(k_id)
4822 self.vimconn.neutron.list_ports.assert_called_once()
4823 self.vimconn.neutron.delete_port.assert_not_called()
4824 self.vimconn.logger.error.assert_not_called()
4825
4826 def test_delete_ports_by_id_by_neutron_list_port_raise_exception(self):
4827 """neutron list port raises exception."""
4828 k_id = port_id
4829 self.vimconn.neutron.list_ports.side_effect = nvExceptions.ClientException(
4830 "Connection aborted."
4831 )
4832 self.vimconn._delete_ports_by_id_wth_neutron(k_id)
4833 self.vimconn.neutron.list_ports.assert_called_once()
4834 self.vimconn.neutron.delete_port.assert_not_called()
4835 self.vimconn.logger.error.assert_called_once_with(
4836 "Error deleting port: ClientException: Unknown Error (HTTP Connection aborted.)"
4837 )
4838
4839 def test_delete_ports_by_id_by_neutron_delete_port_raise_exception(self):
4840 """neutron delete port raises exception."""
4841 k_id = port_id
4842 self.vimconn.neutron.list_ports.return_value = {
4843 "ports": [{"id": port_id}, {"id": port2_id}]
4844 }
4845 self.vimconn.neutron.delete_port.side_effect = nvExceptions.ClientException(
4846 "Connection aborted."
4847 )
4848 self.vimconn._delete_ports_by_id_wth_neutron(k_id)
4849 self.vimconn.neutron.list_ports.assert_called_once()
4850 self.vimconn.neutron.delete_port.assert_called_once_with(k_id)
4851 self.vimconn.logger.error.assert_called_once_with(
4852 "Error deleting port: ClientException: Unknown Error (HTTP Connection aborted.)"
4853 )
4854
4855 def test_get_item_name_id(self):
4856 """Get name and id successfully."""
4857 k = f"some:{port_id}"
4858 result = self.vimconn._get_item_name_id(k)
4859 self.assertEqual(result, ("some", f"{port_id}"))
4860
4861 def test_get_item_name_id_wthout_semicolon(self):
4862 """Does not have seperator."""
4863 k = f"some{port_id}"
4864 result = self.vimconn._get_item_name_id(k)
4865 self.assertEqual(result, (f"some{port_id}", ""))
4866
4867 def test_get_item_name_id_empty_string(self):
4868 """Empty string."""
4869 k = ""
4870 result = self.vimconn._get_item_name_id(k)
4871 self.assertEqual(result, ("", ""))
4872
4873 def test_get_item_name_id_k_is_none(self):
4874 """item is None."""
4875 k = None
4876 with self.assertRaises(AttributeError):
4877 self.vimconn._get_item_name_id(k)
4878
4879 @patch.object(vimconnector, "_get_item_name_id")
4880 @patch.object(vimconnector, "_delete_volumes_by_id_wth_cinder")
4881 @patch.object(vimconnector, "_delete_floating_ip_by_id")
4882 def test_delete_created_items(
4883 self,
4884 mock_delete_floating_ip_by_id,
4885 mock_delete_volumes_by_id_wth_cinder,
4886 mock_get_item_name_id,
4887 ):
4888 """Created items has floating ip and volume."""
4889 created_items = {
4890 f"floating_ip:{floating_network_vim_id}": True,
4891 f"volume:{volume_id}": True,
4892 f"port:{port_id}": None,
4893 }
4894 mock_get_item_name_id.side_effect = [
4895 ("floating_ip", f"{floating_network_vim_id}"),
4896 ("volume", f"{volume_id}"),
4897 ]
4898 mock_delete_volumes_by_id_wth_cinder.return_value = True
4899 volumes_to_hold = []
4900 keep_waiting = False
4901 result = self.vimconn._delete_created_items(
4902 created_items, volumes_to_hold, keep_waiting
4903 )
4904 self.assertEqual(result, True)
4905 self.assertEqual(mock_get_item_name_id.call_count, 2)
4906 mock_delete_volumes_by_id_wth_cinder.assert_called_once_with(
4907 f"volume:{volume_id}", f"{volume_id}", [], created_items
4908 )
4909 mock_delete_floating_ip_by_id.assert_called_once_with(
4910 f"floating_ip:{floating_network_vim_id}",
4911 f"{floating_network_vim_id}",
4912 created_items,
4913 )
4914 self.vimconn.logger.error.assert_not_called()
4915
4916 @patch.object(vimconnector, "_get_item_name_id")
4917 @patch.object(vimconnector, "_delete_volumes_by_id_wth_cinder")
4918 @patch.object(vimconnector, "_delete_floating_ip_by_id")
4919 def test_delete_created_items_wth_volumes_to_hold(
4920 self,
4921 mock_delete_floating_ip_by_id,
4922 mock_delete_volumes_by_id_wth_cinder,
4923 mock_get_item_name_id,
4924 ):
4925 """Created items has floating ip and volume and volumes_to_hold has items."""
4926 created_items = {
4927 f"floating_ip:{floating_network_vim_id}": True,
4928 f"volume:{volume_id}": True,
4929 f"port:{port_id}": None,
4930 }
4931 mock_get_item_name_id.side_effect = [
4932 ("floating_ip", f"{floating_network_vim_id}"),
4933 ("volume", f"{volume_id}"),
4934 ]
4935 mock_delete_volumes_by_id_wth_cinder.return_value = True
4936 volumes_to_hold = [f"{volume_id}", f"{volume_id2}"]
4937 keep_waiting = False
4938 result = self.vimconn._delete_created_items(
4939 created_items, volumes_to_hold, keep_waiting
4940 )
4941 self.assertEqual(result, True)
4942 self.assertEqual(mock_get_item_name_id.call_count, 2)
4943 mock_delete_volumes_by_id_wth_cinder.assert_called_once_with(
4944 f"volume:{volume_id}", f"{volume_id}", volumes_to_hold, created_items
4945 )
4946 mock_delete_floating_ip_by_id.assert_called_once_with(
4947 f"floating_ip:{floating_network_vim_id}",
4948 f"{floating_network_vim_id}",
4949 created_items,
4950 )
4951 self.vimconn.logger.error.assert_not_called()
4952
4953 @patch.object(vimconnector, "_get_item_name_id")
4954 @patch.object(vimconnector, "_delete_volumes_by_id_wth_cinder")
4955 @patch.object(vimconnector, "_delete_floating_ip_by_id")
4956 def test_delete_created_items_wth_keep_waiting_true(
4957 self,
4958 mock_delete_floating_ip_by_id,
4959 mock_delete_volumes_by_id_wth_cinder,
4960 mock_get_item_name_id,
4961 ):
4962 """Keep waiting initial value is True."""
4963 created_items = {
4964 f"floating_ip:{floating_network_vim_id}": True,
4965 f"volume:{volume_id}": True,
4966 f"port:{port_id}": None,
4967 }
4968 mock_get_item_name_id.side_effect = [
4969 ("floating_ip", f"{floating_network_vim_id}"),
4970 ("volume", f"{volume_id}"),
4971 ]
4972 mock_delete_volumes_by_id_wth_cinder.return_value = False
4973 volumes_to_hold = [f"{volume_id}", f"{volume_id2}"]
4974 keep_waiting = True
4975 result = self.vimconn._delete_created_items(
4976 created_items, volumes_to_hold, keep_waiting
4977 )
4978 self.assertEqual(result, True)
4979 self.assertEqual(mock_get_item_name_id.call_count, 2)
4980 mock_delete_volumes_by_id_wth_cinder.assert_called_once_with(
4981 f"volume:{volume_id}", f"{volume_id}", volumes_to_hold, created_items
4982 )
4983 mock_delete_floating_ip_by_id.assert_called_once_with(
4984 f"floating_ip:{floating_network_vim_id}",
4985 f"{floating_network_vim_id}",
4986 created_items,
4987 )
4988 self.vimconn.logger.error.assert_not_called()
4989
4990 @patch.object(vimconnector, "_get_item_name_id")
4991 @patch.object(vimconnector, "_delete_volumes_by_id_wth_cinder")
4992 @patch.object(vimconnector, "_delete_floating_ip_by_id")
4993 def test_delete_created_items_delete_vol_raises(
4994 self,
4995 mock_delete_floating_ip_by_id,
4996 mock_delete_volumes_by_id_wth_cinder,
4997 mock_get_item_name_id,
4998 ):
4999 """Delete volume raises exception."""
5000 created_items = {
5001 f"floating_ip:{floating_network_vim_id}": True,
5002 f"volume:{volume_id}": True,
5003 f"port:{port_id}": None,
5004 }
5005 mock_get_item_name_id.side_effect = [
5006 ("floating_ip", f"{floating_network_vim_id}"),
5007 ("volume", f"{volume_id}"),
5008 ]
5009 mock_delete_volumes_by_id_wth_cinder.side_effect = ConnectionError(
5010 "Connection failed."
5011 )
5012 volumes_to_hold = []
5013 keep_waiting = False
5014 result = self.vimconn._delete_created_items(
5015 created_items, volumes_to_hold, keep_waiting
5016 )
5017 self.assertEqual(result, False)
5018 self.assertEqual(mock_get_item_name_id.call_count, 2)
5019 mock_delete_volumes_by_id_wth_cinder.assert_called_once_with(
5020 f"volume:{volume_id}", f"{volume_id}", [], created_items
5021 )
5022 mock_delete_floating_ip_by_id.assert_called_once_with(
5023 f"floating_ip:{floating_network_vim_id}",
5024 f"{floating_network_vim_id}",
5025 created_items,
5026 )
5027 self.vimconn.logger.error.assert_called_once_with(
5028 "Error deleting volume:ac408b73-b9cc-4a6a-a270-82cc4811bd4a: Connection failed."
5029 )
5030
5031 @patch.object(vimconnector, "_get_item_name_id")
5032 @patch.object(vimconnector, "_delete_volumes_by_id_wth_cinder")
5033 @patch.object(vimconnector, "_delete_floating_ip_by_id")
5034 def test_delete_created_items_delete_fip_raises(
5035 self,
5036 mock_delete_floating_ip_by_id,
5037 mock_delete_volumes_by_id_wth_cinder,
5038 mock_get_item_name_id,
5039 ):
5040 """Delete floating ip raises exception."""
5041 created_items = {
5042 f"floating_ip:{floating_network_vim_id}": True,
5043 f"volume:{volume_id}": True,
5044 f"port:{port_id}": None,
5045 }
5046 mock_get_item_name_id.side_effect = [
5047 ("floating_ip", f"{floating_network_vim_id}"),
5048 ("volume", f"{volume_id}"),
5049 ]
5050 mock_delete_volumes_by_id_wth_cinder.return_value = False
5051 mock_delete_floating_ip_by_id.side_effect = ConnectionError(
5052 "Connection failed."
5053 )
5054 volumes_to_hold = []
5055 keep_waiting = True
5056 result = self.vimconn._delete_created_items(
5057 created_items, volumes_to_hold, keep_waiting
5058 )
5059 self.assertEqual(result, True)
5060 self.assertEqual(mock_get_item_name_id.call_count, 2)
5061 mock_delete_volumes_by_id_wth_cinder.assert_called_once_with(
5062 f"volume:{volume_id}", f"{volume_id}", [], created_items
5063 )
5064 mock_delete_floating_ip_by_id.assert_called_once_with(
5065 f"floating_ip:{floating_network_vim_id}",
5066 f"{floating_network_vim_id}",
5067 created_items,
5068 )
5069 self.vimconn.logger.error.assert_called_once_with(
5070 "Error deleting floating_ip:108b73-e9cc-5a6a-t270-82cc4811bd4a: Connection failed."
5071 )
5072
5073 @patch.object(vimconnector, "_get_item_name_id")
5074 @patch.object(vimconnector, "_delete_volumes_by_id_wth_cinder")
5075 @patch.object(vimconnector, "_delete_floating_ip_by_id")
5076 def test_delete_created_items_get_item_name_raises(
5077 self,
5078 mock_delete_floating_ip_by_id,
5079 mock_delete_volumes_by_id_wth_cinder,
5080 mock_get_item_name_id,
5081 ):
5082 """Get item, name raises exception."""
5083 created_items = {
5084 3: True,
5085 f"volume{volume_id}": True,
5086 f"port:{port_id}": None,
5087 }
5088 mock_get_item_name_id.side_effect = [
5089 TypeError("Invalid Type"),
5090 AttributeError("Invalid attribute"),
5091 ]
5092 volumes_to_hold = []
5093 keep_waiting = False
5094 result = self.vimconn._delete_created_items(
5095 created_items, volumes_to_hold, keep_waiting
5096 )
5097 self.assertEqual(result, False)
5098 self.assertEqual(mock_get_item_name_id.call_count, 2)
5099 mock_delete_volumes_by_id_wth_cinder.assert_not_called()
5100 mock_delete_floating_ip_by_id.assert_not_called()
5101 _call_logger = self.vimconn.logger.error.call_args_list
5102 self.assertEqual(_call_logger[0][0], ("Error deleting 3: Invalid Type",))
5103 self.assertEqual(
5104 _call_logger[1][0],
5105 (f"Error deleting volume{volume_id}: Invalid attribute",),
5106 )
5107
5108 @patch.object(vimconnector, "_get_item_name_id")
5109 @patch.object(vimconnector, "_delete_volumes_by_id_wth_cinder")
5110 @patch.object(vimconnector, "_delete_floating_ip_by_id")
5111 def test_delete_created_items_no_fip_wth_port(
5112 self,
5113 mock_delete_floating_ip_by_id,
5114 mock_delete_volumes_by_id_wth_cinder,
5115 mock_get_item_name_id,
5116 ):
5117 """Created items has port, does not have floating ip."""
5118 created_items = {
5119 f"volume:{volume_id}": True,
5120 f"port:{port_id}": True,
5121 }
5122 mock_get_item_name_id.side_effect = [
5123 ("volume", f"{volume_id}"),
5124 ("port", f"{port_id}"),
5125 ]
5126 mock_delete_volumes_by_id_wth_cinder.return_value = False
5127 volumes_to_hold = []
5128 keep_waiting = False
5129 result = self.vimconn._delete_created_items(
5130 created_items, volumes_to_hold, keep_waiting
5131 )
5132 self.assertEqual(result, False)
5133 self.assertEqual(mock_get_item_name_id.call_count, 2)
5134 mock_delete_volumes_by_id_wth_cinder.assert_called_once_with(
5135 f"volume:{volume_id}", f"{volume_id}", [], created_items
5136 )
5137 mock_delete_floating_ip_by_id.assert_not_called()
5138 self.vimconn.logger.error.assert_not_called()
5139
5140 @patch.object(vimconnector, "_get_item_name_id")
5141 @patch.object(vimconnector, "_delete_volumes_by_id_wth_cinder")
5142 @patch.object(vimconnector, "_delete_floating_ip_by_id")
5143 def test_delete_created_items_no_volume(
5144 self,
5145 mock_delete_floating_ip_by_id,
5146 mock_delete_volumes_by_id_wth_cinder,
5147 mock_get_item_name_id,
5148 ):
5149 """Created items does not have volume."""
5150 created_items = {
5151 f"floating_ip:{floating_network_vim_id}": True,
5152 f"port:{port_id}": None,
5153 }
5154 mock_get_item_name_id.side_effect = [
5155 ("floating_ip", f"{floating_network_vim_id}")
5156 ]
5157 volumes_to_hold = []
5158 keep_waiting = False
5159 result = self.vimconn._delete_created_items(
5160 created_items, volumes_to_hold, keep_waiting
5161 )
5162 self.assertEqual(result, False)
5163 self.assertEqual(mock_get_item_name_id.call_count, 1)
5164 mock_delete_volumes_by_id_wth_cinder.assert_not_called()
5165 mock_delete_floating_ip_by_id.assert_called_once_with(
5166 f"floating_ip:{floating_network_vim_id}",
5167 f"{floating_network_vim_id}",
5168 created_items,
5169 )
5170 self.vimconn.logger.error.assert_not_called()
5171
5172 @patch.object(vimconnector, "_get_item_name_id")
5173 @patch.object(vimconnector, "_delete_volumes_by_id_wth_cinder")
5174 @patch.object(vimconnector, "_delete_floating_ip_by_id")
5175 def test_delete_created_items_already_deleted(
5176 self,
5177 mock_delete_floating_ip_by_id,
5178 mock_delete_volumes_by_id_wth_cinder,
5179 mock_get_item_name_id,
5180 ):
5181 """All created items are alerady deleted."""
5182 created_items = {
5183 f"floating_ip:{floating_network_vim_id}": None,
5184 f"volume:{volume_id}": None,
5185 f"port:{port_id}": None,
5186 }
5187 volumes_to_hold = []
5188 keep_waiting = False
5189 result = self.vimconn._delete_created_items(
5190 created_items, volumes_to_hold, keep_waiting
5191 )
5192 self.assertEqual(result, False)
5193 mock_get_item_name_id.assert_not_called()
5194 mock_delete_volumes_by_id_wth_cinder.assert_not_called()
5195 mock_delete_floating_ip_by_id.assert_not_called()
5196 self.vimconn.logger.error.assert_not_called()
5197
5198 @patch("time.sleep")
5199 @patch.object(vimconnector, "_format_exception")
5200 @patch.object(vimconnector, "_reload_connection")
5201 @patch.object(vimconnector, "_delete_vm_ports_attached_to_network")
5202 @patch.object(vimconnector, "_delete_created_items")
5203 def test_delete_vminstance_successfully(
5204 self,
5205 mock_delete_created_items,
5206 mock_delete_vm_ports_attached_to_network,
5207 mock_reload_connection,
5208 mock_format_exception,
5209 mock_sleep,
5210 ):
5211 vm_id = f"{virtual_mac_id}"
5212 created_items = deepcopy(created_items_all_true)
5213 volumes_to_hold = [f"{volume_id}", f"{volume_id2}"]
5214 mock_delete_created_items.return_value = False
5215 self.vimconn.delete_vminstance(vm_id, created_items, volumes_to_hold)
5216 mock_reload_connection.assert_called_once()
5217 mock_delete_vm_ports_attached_to_network.assert_called_once_with(created_items)
5218 self.vimconn.nova.servers.delete.assert_called_once_with(vm_id)
5219 mock_delete_created_items.assert_called_once_with(
5220 created_items, volumes_to_hold, False
5221 )
5222 mock_sleep.assert_not_called()
5223 mock_format_exception.assert_not_called()
5224
5225 @patch("time.sleep")
5226 @patch.object(vimconnector, "_format_exception")
5227 @patch.object(vimconnector, "_reload_connection")
5228 @patch.object(vimconnector, "_delete_vm_ports_attached_to_network")
5229 @patch.object(vimconnector, "_delete_created_items")
5230 def test_delete_vminstance_delete_created_items_raises(
5231 self,
5232 mock_delete_created_items,
5233 mock_delete_vm_ports_attached_to_network,
5234 mock_reload_connection,
5235 mock_format_exception,
5236 mock_sleep,
5237 ):
5238 """Delete creted items raises exception."""
5239 vm_id = f"{virtual_mac_id}"
5240 created_items = deepcopy(created_items_all_true)
5241 mock_sleep = MagicMock()
5242 volumes_to_hold = []
5243 err = ConnectionError("ClientException occured.")
5244 mock_delete_created_items.side_effect = err
5245 with self.assertRaises(ConnectionError) as err:
5246 self.vimconn.delete_vminstance(vm_id, created_items, volumes_to_hold)
5247 self.assertEqual(str(err), "ClientException occured.")
5248 mock_reload_connection.assert_called_once()
5249 mock_delete_vm_ports_attached_to_network.assert_called_once_with(created_items)
5250 self.vimconn.nova.servers.delete.assert_called_once_with(vm_id)
5251 mock_delete_created_items.assert_called_once()
5252 mock_sleep.assert_not_called()
5253
5254 @patch("time.sleep")
5255 @patch.object(vimconnector, "_format_exception")
5256 @patch.object(vimconnector, "_reload_connection")
5257 @patch.object(vimconnector, "_delete_vm_ports_attached_to_network")
5258 @patch.object(vimconnector, "_delete_created_items")
5259 def test_delete_vminstance_delete_vm_ports_raises(
5260 self,
5261 mock_delete_created_items,
5262 mock_delete_vm_ports_attached_to_network,
5263 mock_reload_connection,
5264 mock_format_exception,
5265 mock_sleep,
5266 ):
5267 """Delete vm ports raises exception."""
5268 vm_id = f"{virtual_mac_id}"
5269 created_items = deepcopy(created_items_all_true)
5270 volumes_to_hold = [f"{volume_id}", f"{volume_id2}"]
5271 err = ConnectionError("ClientException occured.")
5272 mock_delete_vm_ports_attached_to_network.side_effect = err
5273 mock_delete_created_items.side_effect = err
5274 with self.assertRaises(ConnectionError) as err:
5275 self.vimconn.delete_vminstance(vm_id, created_items, volumes_to_hold)
5276 self.assertEqual(str(err), "ClientException occured.")
5277 mock_reload_connection.assert_called_once()
5278 mock_delete_vm_ports_attached_to_network.assert_called_once_with(created_items)
5279 self.vimconn.nova.servers.delete.assert_not_called()
5280 mock_delete_created_items.assert_not_called()
5281 mock_sleep.assert_not_called()
5282
5283 @patch("time.sleep")
5284 @patch.object(vimconnector, "_format_exception")
5285 @patch.object(vimconnector, "_reload_connection")
5286 @patch.object(vimconnector, "_delete_vm_ports_attached_to_network")
5287 @patch.object(vimconnector, "_delete_created_items")
5288 def test_delete_vminstance_nova_server_delete_raises(
5289 self,
5290 mock_delete_created_items,
5291 mock_delete_vm_ports_attached_to_network,
5292 mock_reload_connection,
5293 mock_format_exception,
5294 mock_sleep,
5295 ):
5296 """Nova server delete raises exception."""
5297 vm_id = f"{virtual_mac_id}"
5298 created_items = deepcopy(created_items_all_true)
5299 volumes_to_hold = [f"{volume_id}", f"{volume_id2}"]
5300 err = VimConnConnectionException("ClientException occured.")
5301 self.vimconn.nova.servers.delete.side_effect = err
5302 mock_delete_created_items.side_effect = err
5303 with self.assertRaises(VimConnConnectionException) as err:
5304 self.vimconn.delete_vminstance(vm_id, created_items, volumes_to_hold)
5305 self.assertEqual(str(err), "ClientException occured.")
5306 mock_reload_connection.assert_called_once()
5307 mock_delete_vm_ports_attached_to_network.assert_called_once_with(created_items)
5308 self.vimconn.nova.servers.delete.assert_called_once_with(vm_id)
5309 mock_delete_created_items.assert_not_called()
5310 mock_sleep.assert_not_called()
5311
5312 @patch("time.sleep")
5313 @patch.object(vimconnector, "_format_exception")
5314 @patch.object(vimconnector, "_reload_connection")
5315 @patch.object(vimconnector, "_delete_vm_ports_attached_to_network")
5316 @patch.object(vimconnector, "_delete_created_items")
5317 def test_delete_vminstance_reload_connection_raises(
5318 self,
5319 mock_delete_created_items,
5320 mock_delete_vm_ports_attached_to_network,
5321 mock_reload_connection,
5322 mock_format_exception,
5323 mock_sleep,
5324 ):
5325 """Reload connection raises exception."""
5326 vm_id = f"{virtual_mac_id}"
5327 created_items = deepcopy(created_items_all_true)
5328 mock_sleep = MagicMock()
5329 volumes_to_hold = [f"{volume_id}", f"{volume_id2}"]
5330 err = ConnectionError("ClientException occured.")
5331 mock_delete_created_items.return_value = False
5332 mock_reload_connection.side_effect = err
5333 with self.assertRaises(ConnectionError) as err:
5334 self.vimconn.delete_vminstance(vm_id, created_items, volumes_to_hold)
5335 self.assertEqual(str(err), "ClientException occured.")
5336 mock_reload_connection.assert_called_once()
5337 mock_delete_vm_ports_attached_to_network.assert_not_called()
5338 self.vimconn.nova.servers.delete.assert_not_called()
5339 mock_delete_created_items.assert_not_called()
5340 mock_sleep.assert_not_called()
5341
5342 @patch("time.sleep")
5343 @patch.object(vimconnector, "_format_exception")
5344 @patch.object(vimconnector, "_reload_connection")
5345 @patch.object(vimconnector, "_delete_vm_ports_attached_to_network")
5346 @patch.object(vimconnector, "_delete_created_items")
5347 def test_delete_vminstance_created_item_vol_to_hold_are_none(
5348 self,
5349 mock_delete_created_items,
5350 mock_delete_vm_ports_attached_to_network,
5351 mock_reload_connection,
5352 mock_format_exception,
5353 mock_sleep,
5354 ):
5355 """created_items and volumes_to_hold are None."""
5356 vm_id = f"{virtual_mac_id}"
5357 created_items = None
5358 volumes_to_hold = None
5359 mock_delete_created_items.return_value = False
5360 self.vimconn.delete_vminstance(vm_id, created_items, volumes_to_hold)
5361 mock_reload_connection.assert_called_once()
5362 mock_delete_vm_ports_attached_to_network.assert_not_called()
5363 self.vimconn.nova.servers.delete.assert_called_once_with(vm_id)
5364 mock_delete_created_items.assert_called_once_with({}, [], False)
5365 mock_sleep.assert_not_called()
5366 mock_format_exception.assert_not_called()
5367
5368 @patch("time.sleep")
5369 @patch.object(vimconnector, "_format_exception")
5370 @patch.object(vimconnector, "_reload_connection")
5371 @patch.object(vimconnector, "_delete_vm_ports_attached_to_network")
5372 @patch.object(vimconnector, "_delete_created_items")
5373 def test_delete_vminstance_vm_id_is_none(
5374 self,
5375 mock_delete_created_items,
5376 mock_delete_vm_ports_attached_to_network,
5377 mock_reload_connection,
5378 mock_format_exception,
5379 mock_sleep,
5380 ):
5381 """vm_id is None."""
5382 vm_id = None
5383 created_items = deepcopy(created_items_all_true)
5384 volumes_to_hold = [f"{volume_id}", f"{volume_id2}"]
5385 mock_delete_created_items.side_effect = [True, True, False]
5386 self.vimconn.delete_vminstance(vm_id, created_items, volumes_to_hold)
5387 mock_reload_connection.assert_called_once()
5388 mock_delete_vm_ports_attached_to_network.assert_called_once_with(created_items)
5389 self.vimconn.nova.servers.delete.assert_not_called()
5390 self.assertEqual(mock_delete_created_items.call_count, 3)
5391 self.assertEqual(mock_sleep.call_count, 2)
5392 mock_format_exception.assert_not_called()
5393
5394 @patch("time.sleep")
5395 @patch.object(vimconnector, "_format_exception")
5396 @patch.object(vimconnector, "_reload_connection")
5397 @patch.object(vimconnector, "_delete_vm_ports_attached_to_network")
5398 @patch.object(vimconnector, "_delete_created_items")
5399 def test_delete_vminstance_delete_created_items_return_true(
5400 self,
5401 mock_delete_created_items,
5402 mock_delete_vm_ports_attached_to_network,
5403 mock_reload_connection,
5404 mock_format_exception,
5405 mock_sleep,
5406 ):
5407 """Delete created items always return True."""
5408 vm_id = None
5409 created_items = deepcopy(created_items_all_true)
5410 volumes_to_hold = [f"{volume_id}", f"{volume_id2}"]
5411 mock_delete_created_items.side_effect = [True] * 1800
5412 self.vimconn.delete_vminstance(vm_id, created_items, volumes_to_hold)
5413 mock_reload_connection.assert_called_once()
5414 mock_delete_vm_ports_attached_to_network.assert_called_once_with(created_items)
5415 self.vimconn.nova.servers.delete.assert_not_called()
5416 self.assertEqual(mock_delete_created_items.call_count, 1800)
5417 self.assertEqual(mock_sleep.call_count, 1800)
5418 mock_format_exception.assert_not_called()
5419
5420
5421 if __name__ == "__main__":
5422 unittest.main()