Bug 1234: OSM reports successful deployment when a charm relation fails
[osm/LCM.git] / osm_lcm / tests / test_ns.py
1 #
2 # Licensed under the Apache License, Version 2.0 (the "License"); you may
3 # not use this file except in compliance with the License. You may obtain
4 # a copy of the License at
5 #
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11 # License for the specific language governing permissions and limitations
12 # under the License.
13 #
14 # For those usages not covered by the Apache License, Version 2.0 please
15 # contact: alfonso.tiernosepulveda@telefonica.com
16 ##
17
18
19 import asynctest # pip3 install asynctest --user
20 import asyncio
21 from copy import deepcopy
22 import yaml
23 import copy
24 from n2vc.exceptions import N2VCException
25 from os import getenv
26 from osm_lcm import ns
27 from osm_common.msgkafka import MsgKafka
28
29 from osm_lcm.data_utils.lcm_config import LcmCfg
30 from osm_lcm.lcm_utils import TaskRegistry
31 from osm_lcm.ng_ro import NgRoClient
32 from osm_lcm.data_utils.database.database import Database
33 from osm_lcm.data_utils.filesystem.filesystem import Filesystem
34 from osm_lcm.data_utils.vca import Relation, EERelation
35 from osm_lcm.data_utils.vnfd import find_software_version
36 from osm_lcm.lcm_utils import check_juju_bundle_existence, get_charm_artifact_path
37 from osm_lcm.lcm_utils import LcmException
38 from uuid import uuid4
39 from unittest.mock import Mock, patch
40
41 from osm_lcm.tests import test_db_descriptors as descriptors
42
43 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
44
45 """ Perform unittests using asynctest of osm_lcm.ns module
46 It allows, if some testing ENV are supplied, testing without mocking some external libraries for debugging:
47 OSMLCMTEST_NS_PUBKEY: public ssh-key returned by N2VC to inject to VMs
48 OSMLCMTEST_NS_NAME: change name of NS
49 OSMLCMTEST_PACKAGES_PATH: path where the vnf-packages are stored (de-compressed), each one on a 'vnfd_id' folder
50 OSMLCMTEST_NS_IPADDRESS: IP address where emulated VMs are reached. Comma separate list
51 OSMLCMTEST_RO_VIMID: VIM id of RO target vim IP. Obtain it with openmano datcenter-list on RO container
52 OSMLCMTEST_VCA_NOMOCK: Do no mock the VCA, N2VC library, for debugging it
53 OSMLCMTEST_RO_NOMOCK: Do no mock the ROClient library, for debugging it
54 OSMLCMTEST_DB_NOMOCK: Do no mock the database library, for debugging it
55 OSMLCMTEST_FS_NOMOCK: Do no mock the File Storage library, for debugging it
56 OSMLCMTEST_LOGGING_NOMOCK: Do no mock the logging
57 OSMLCM_VCA_XXX: configuration of N2VC
58 OSMLCM_RO_XXX: configuration of RO
59 """
60
61 lcm_config_dict = {
62 "global": {"loglevel": "DEBUG"},
63 "timeout": {},
64 "VCA": { # TODO replace with os.get_env to get other configurations
65 "host": getenv("OSMLCM_VCA_HOST", "vca"),
66 "port": getenv("OSMLCM_VCA_PORT", 17070),
67 "user": getenv("OSMLCM_VCA_USER", "admin"),
68 "secret": getenv("OSMLCM_VCA_SECRET", "vca"),
69 "public_key": getenv("OSMLCM_VCA_PUBKEY", None),
70 "ca_cert": getenv("OSMLCM_VCA_CACERT", None),
71 "apiproxy": getenv("OSMLCM_VCA_APIPROXY", "192.168.1.1"),
72 },
73 "RO": {
74 "uri": "http://{}:{}/openmano".format(
75 getenv("OSMLCM_RO_HOST", "ro"), getenv("OSMLCM_RO_PORT", "9090")
76 ),
77 "tenant": getenv("OSMLCM_RO_TENANT", "osm"),
78 "logger_name": "lcm.ROclient",
79 "loglevel": "DEBUG",
80 "ng": True,
81 },
82 }
83
84 lcm_config = LcmCfg()
85 lcm_config.set_from_dict(lcm_config_dict)
86 lcm_config.transform()
87
88 nsr_id = descriptors.test_ids["TEST-A"]["ns"]
89 nslcmop_id = descriptors.test_ids["TEST-A"]["update"]
90 vnfr_id = "6421c7c9-d865-4fb4-9a13-d4275d243e01"
91 vnfd_id = "7637bcf8-cf14-42dc-ad70-c66fcf1e6e77"
92 update_fs = Mock(autospec=True)
93 update_fs.path.__add__ = Mock()
94 update_fs.path.side_effect = ["/", "/", "/", "/"]
95 update_fs.sync.side_effect = [None, None]
96
97
98 def callable(a):
99 return a
100
101
102 class TestBaseNS(asynctest.TestCase):
103 async def _n2vc_DeployCharms(
104 self,
105 model_name,
106 application_name,
107 vnfd,
108 charm_path,
109 params={},
110 machine_spec={},
111 callback=None,
112 *callback_args,
113 ):
114 if callback:
115 for status, message in (
116 ("maintenance", "installing sofwware"),
117 ("active", "Ready!"),
118 ):
119 # call callback after some time
120 asyncio.sleep(5, loop=self.loop)
121 callback(model_name, application_name, status, message, *callback_args)
122
123 @staticmethod
124 def _n2vc_FormatApplicationName(*args):
125 num_calls = 0
126 while True:
127 yield "app_name-{}".format(num_calls)
128 num_calls += 1
129
130 def _n2vc_CreateExecutionEnvironment(
131 self, namespace, reuse_ee_id, db_dict, *args, **kwargs
132 ):
133 k_list = namespace.split(".")
134 ee_id = k_list[1] + "."
135 if len(k_list) >= 2:
136 for k in k_list[2:4]:
137 ee_id += k[:8]
138 else:
139 ee_id += "_NS_"
140 return ee_id, {}
141
142 def _ro_status(self, *args, **kwargs):
143 print("Args > {}".format(args))
144 print("kwargs > {}".format(kwargs))
145 if args:
146 if "update" in args:
147 ro_ns_desc = yaml.safe_load(descriptors.ro_update_action_text)
148 while True:
149 yield ro_ns_desc
150 if kwargs.get("delete"):
151 ro_ns_desc = yaml.safe_load(descriptors.ro_delete_action_text)
152 while True:
153 yield ro_ns_desc
154
155 ro_ns_desc = yaml.safe_load(descriptors.ro_ns_text)
156
157 # if ip address provided, replace descriptor
158 ip_addresses = getenv("OSMLCMTEST_NS_IPADDRESS", "")
159 if ip_addresses:
160 ip_addresses_list = ip_addresses.split(",")
161 for vnf in ro_ns_desc["vnfs"]:
162 if not ip_addresses_list:
163 break
164 vnf["ip_address"] = ip_addresses_list[0]
165 for vm in vnf["vms"]:
166 if not ip_addresses_list:
167 break
168 vm["ip_address"] = ip_addresses_list.pop(0)
169
170 while True:
171 yield ro_ns_desc
172 for net in ro_ns_desc["nets"]:
173 if net["status"] != "ACTIVE":
174 net["status"] = "ACTIVE"
175 break
176 else:
177 for vnf in ro_ns_desc["vnfs"]:
178 for vm in vnf["vms"]:
179 if vm["status"] != "ACTIVE":
180 vm["status"] = "ACTIVE"
181 break
182
183 def _ro_deploy(self, *args, **kwargs):
184 return {"action_id": args[1]["action_id"], "nsr_id": args[0], "status": "ok"}
185
186 def _return_uuid(self, *args, **kwargs):
187 return str(uuid4())
188
189 async def setUp(self):
190 self.mock_db()
191 self.mock_kafka()
192 self.mock_filesystem()
193 self.mock_task_registry()
194 self.mock_vca_k8s()
195 self.create_nslcm_class()
196 self.mock_logging()
197 self.mock_vca_n2vc()
198 self.mock_ro()
199
200 def mock_db(self):
201 if not getenv("OSMLCMTEST_DB_NOMOCK"):
202 # Cleanup singleton Database instance
203 Database.instance = None
204
205 self.db = Database({"database": {"driver": "memory"}}).instance.db
206 self.db.create_list("vnfds", yaml.safe_load(descriptors.db_vnfds_text))
207 self.db.create_list(
208 "vnfds_revisions", yaml.safe_load(descriptors.db_vnfds_revisions_text)
209 )
210 self.db.create_list("nsds", yaml.safe_load(descriptors.db_nsds_text))
211 self.db.create_list("nsrs", yaml.safe_load(descriptors.db_nsrs_text))
212 self.db.create_list(
213 "vim_accounts", yaml.safe_load(descriptors.db_vim_accounts_text)
214 )
215 self.db.create_list(
216 "k8sclusters", yaml.safe_load(descriptors.db_k8sclusters_text)
217 )
218 self.db.create_list(
219 "nslcmops", yaml.safe_load(descriptors.db_nslcmops_text)
220 )
221 self.db.create_list("vnfrs", yaml.safe_load(descriptors.db_vnfrs_text))
222 self.db_vim_accounts = yaml.safe_load(descriptors.db_vim_accounts_text)
223
224 def mock_kafka(self):
225 self.msg = asynctest.Mock(MsgKafka())
226
227 def mock_filesystem(self):
228 if not getenv("OSMLCMTEST_FS_NOMOCK"):
229 self.fs = asynctest.Mock(
230 Filesystem({"storage": {"driver": "local", "path": "/"}}).instance.fs
231 )
232 self.fs.get_params.return_value = {
233 "path": getenv("OSMLCMTEST_PACKAGES_PATH", "./test/temp/packages")
234 }
235 self.fs.file_open = asynctest.mock_open()
236 # self.fs.file_open.return_value.__enter__.return_value = asynctest.MagicMock() # called on a python "with"
237 # self.fs.file_open.return_value.__enter__.return_value.read.return_value = "" # empty file
238
239 def mock_task_registry(self):
240 self.lcm_tasks = asynctest.Mock(TaskRegistry())
241 self.lcm_tasks.lock_HA.return_value = True
242 self.lcm_tasks.waitfor_related_HA.return_value = None
243 self.lcm_tasks.lookfor_related.return_value = ("", [])
244
245 def mock_vca_k8s(self):
246 if not getenv("OSMLCMTEST_VCA_K8s_NOMOCK"):
247 ns.K8sJujuConnector = asynctest.MagicMock(ns.K8sJujuConnector)
248 ns.K8sHelmConnector = asynctest.MagicMock(ns.K8sHelmConnector)
249 ns.K8sHelm3Connector = asynctest.MagicMock(ns.K8sHelm3Connector)
250
251 if not getenv("OSMLCMTEST_VCA_NOMOCK"):
252 ns.N2VCJujuConnector = asynctest.MagicMock(ns.N2VCJujuConnector)
253 ns.LCMHelmConn = asynctest.MagicMock(ns.LCMHelmConn)
254
255 def create_nslcm_class(self):
256 self.my_ns = ns.NsLcm(self.msg, self.lcm_tasks, lcm_config, self.loop)
257 self.my_ns.fs = self.fs
258 self.my_ns.db = self.db
259 self.my_ns._wait_dependent_n2vc = asynctest.CoroutineMock()
260
261 def mock_logging(self):
262 if not getenv("OSMLCMTEST_LOGGING_NOMOCK"):
263 self.my_ns.logger = asynctest.Mock(self.my_ns.logger)
264
265 def mock_vca_n2vc(self):
266 if not getenv("OSMLCMTEST_VCA_NOMOCK"):
267 pub_key = getenv("OSMLCMTEST_NS_PUBKEY", "ssh-rsa test-pub-key t@osm.com")
268 # self.my_ns.n2vc = asynctest.Mock(N2VC())
269 self.my_ns.n2vc.GetPublicKey.return_value = getenv(
270 "OSMLCM_VCA_PUBKEY", "public_key"
271 )
272 # allow several versions of n2vc
273 self.my_ns.n2vc.FormatApplicationName = asynctest.Mock(
274 side_effect=self._n2vc_FormatApplicationName()
275 )
276 self.my_ns.n2vc.DeployCharms = asynctest.CoroutineMock(
277 side_effect=self._n2vc_DeployCharms
278 )
279 self.my_ns.n2vc.create_execution_environment = asynctest.CoroutineMock(
280 side_effect=self._n2vc_CreateExecutionEnvironment
281 )
282 self.my_ns.n2vc.install_configuration_sw = asynctest.CoroutineMock(
283 return_value=pub_key
284 )
285 self.my_ns.n2vc.get_ee_ssh_public__key = asynctest.CoroutineMock(
286 return_value=pub_key
287 )
288 self.my_ns.n2vc.exec_primitive = asynctest.CoroutineMock(
289 side_effect=self._return_uuid
290 )
291 self.my_ns.n2vc.exec_primitive = asynctest.CoroutineMock(
292 side_effect=self._return_uuid
293 )
294 self.my_ns.n2vc.GetPrimitiveStatus = asynctest.CoroutineMock(
295 return_value="completed"
296 )
297 self.my_ns.n2vc.GetPrimitiveOutput = asynctest.CoroutineMock(
298 return_value={"result": "ok", "pubkey": pub_key}
299 )
300 self.my_ns.n2vc.delete_execution_environment = asynctest.CoroutineMock(
301 return_value=None
302 )
303 self.my_ns.n2vc.get_public_key = asynctest.CoroutineMock(
304 return_value=getenv("OSMLCM_VCA_PUBKEY", "public_key")
305 )
306 self.my_ns.n2vc.delete_namespace = asynctest.CoroutineMock(
307 return_value=None
308 )
309 self.my_ns.n2vc.register_execution_environment = asynctest.CoroutineMock(
310 return_value="model-name.application-name.k8s"
311 )
312
313 def mock_ro(self):
314 if not getenv("OSMLCMTEST_RO_NOMOCK"):
315 self.my_ns.RO = asynctest.Mock(
316 NgRoClient(self.loop, **lcm_config.RO.to_dict())
317 )
318 # TODO first time should be empty list, following should return a dict
319 # self.my_ns.RO.get_list = asynctest.CoroutineMock(self.my_ns.RO.get_list, return_value=[])
320 self.my_ns.RO.deploy = asynctest.CoroutineMock(
321 self.my_ns.RO.deploy, side_effect=self._ro_deploy
322 )
323 # self.my_ns.RO.status = asynctest.CoroutineMock(self.my_ns.RO.status, side_effect=self._ro_status)
324 # self.my_ns.RO.create_action = asynctest.CoroutineMock(self.my_ns.RO.create_action,
325 # return_value={"vm-id": {"vim_result": 200,
326 # "description": "done"}})
327 self.my_ns.RO.delete = asynctest.CoroutineMock(self.my_ns.RO.delete)
328
329 # @asynctest.fail_on(active_handles=True) # all async tasks must be completed
330 # async def test_instantiate(self):
331 # nsr_id = descriptors.test_ids["TEST-A"]["ns"]
332 # nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
333 # # print("Test instantiate started")
334
335 # # delete deployed information of database
336 # if not getenv("OSMLCMTEST_DB_NOMOCK"):
337 # if self.db.get_list("nsrs")[0]["_admin"].get("deployed"):
338 # del self.db.get_list("nsrs")[0]["_admin"]["deployed"]
339 # for db_vnfr in self.db.get_list("vnfrs"):
340 # db_vnfr.pop("ip_address", None)
341 # for db_vdur in db_vnfr["vdur"]:
342 # db_vdur.pop("ip_address", None)
343 # db_vdur.pop("mac_address", None)
344 # if getenv("OSMLCMTEST_RO_VIMID"):
345 # self.db.get_list("vim_accounts")[0]["_admin"]["deployed"]["RO"] = getenv("OSMLCMTEST_RO_VIMID")
346 # if getenv("OSMLCMTEST_RO_VIMID"):
347 # self.db.get_list("nsrs")[0]["_admin"]["deployed"]["RO"] = getenv("OSMLCMTEST_RO_VIMID")
348
349 # await self.my_ns.instantiate(nsr_id, nslcmop_id)
350
351 # self.msg.aiowrite.assert_called_once_with("ns", "instantiated",
352 # {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
353 # "operationState": "COMPLETED"},
354 # loop=self.loop)
355 # self.lcm_tasks.lock_HA.assert_called_once_with('ns', 'nslcmops', nslcmop_id)
356 # if not getenv("OSMLCMTEST_LOGGING_NOMOCK"):
357 # self.assertTrue(self.my_ns.logger.debug.called, "Debug method not called")
358 # self.my_ns.logger.error.assert_not_called()
359 # self.my_ns.logger.exception().assert_not_called()
360
361 # if not getenv("OSMLCMTEST_DB_NOMOCK"):
362 # self.assertTrue(self.db.set_one.called, "db.set_one not called")
363 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
364 # db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
365 # self.assertEqual(db_nsr["_admin"].get("nsState"), "INSTANTIATED", "Not instantiated")
366 # for vnfr in db_vnfrs_list:
367 # self.assertEqual(vnfr["_admin"].get("nsState"), "INSTANTIATED", "Not instantiated")
368
369 # if not getenv("OSMLCMTEST_VCA_NOMOCK"):
370 # # check intial-primitives called
371 # self.assertTrue(self.my_ns.n2vc.exec_primitive.called,
372 # "Exec primitive not called for initial config primitive")
373 # for _call in self.my_ns.n2vc.exec_primitive.call_args_list:
374 # self.assertIn(_call[1]["primitive_name"], ("config", "touch"),
375 # "called exec primitive with a primitive different than config or touch")
376
377 # # TODO add more checks of called methods
378 # # TODO add a terminate
379
380 # async def test_instantiate_ee_list(self):
381 # # Using modern IM where configuration is in the new format of execution_environment_list
382 # ee_descriptor_id = "charm_simple"
383 # non_used_initial_primitive = {
384 # "name": "not_to_be_called",
385 # "seq": 3,
386 # "execution-environment-ref": "not_used_ee"
387 # }
388 # ee_list = [
389 # {
390 # "id": ee_descriptor_id,
391 # "juju": {"charm": "simple"},
392
393 # },
394 # ]
395
396 # self.db.set_one(
397 # "vnfds",
398 # q_filter={"_id": "7637bcf8-cf14-42dc-ad70-c66fcf1e6e77"},
399 # update_dict={"vnf-configuration.0.execution-environment-list": ee_list,
400 # "vnf-configuration.0.initial-config-primitive.0.execution-environment-ref": ee_descriptor_id,
401 # "vnf-configuration.0.initial-config-primitive.1.execution-environment-ref": ee_descriptor_id,
402 # "vnf-configuration.0.initial-config-primitive.2": non_used_initial_primitive,
403 # "vnf-configuration.0.config-primitive.0.execution-environment-ref": ee_descriptor_id,
404 # "vnf-configuration.0.config-primitive.0.execution-environment-primitive": "touch_charm",
405 # },
406 # unset={"vnf-configuration.juju": None})
407 # await self.test_instantiate()
408 # # this will check that the initial-congig-primitive 'not_to_be_called' is not called
409
410
411 class TestMyNS(TestBaseNS):
412 @asynctest.fail_on(active_handles=True)
413 async def test_start_stop_rebuild_pass(self):
414 nsr_id = descriptors.test_ids["TEST-OP-VNF"]["ns"]
415 nslcmop_id = descriptors.test_ids["TEST-OP-VNF"]["nslcmops"]
416 vnf_id = descriptors.test_ids["TEST-OP-VNF"]["vnfrs"]
417 additional_param = {"count-index": "0"}
418 operation_type = "start"
419 await self.my_ns.rebuild_start_stop(
420 nsr_id, nslcmop_id, vnf_id, additional_param, operation_type
421 )
422 expected_value = "COMPLETED"
423 return_value = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
424 "operationState"
425 )
426 self.assertEqual(return_value, expected_value)
427
428 @asynctest.fail_on(active_handles=True)
429 async def test_start_stop_rebuild_fail(self):
430 nsr_id = descriptors.test_ids["TEST-OP-VNF"]["ns"]
431 nslcmop_id = descriptors.test_ids["TEST-OP-VNF"]["nslcmops1"]
432 vnf_id = descriptors.test_ids["TEST-OP-VNF"]["vnfrs"]
433 additional_param = {"count-index": "0"}
434 operation_type = "stop"
435 await self.my_ns.rebuild_start_stop(
436 nsr_id, nslcmop_id, vnf_id, additional_param, operation_type
437 )
438 expected_value = "Error"
439 return_value = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
440 "operationState"
441 )
442 self.assertEqual(return_value, expected_value)
443
444 # Test scale() and related methods
445 @asynctest.fail_on(active_handles=True) # all async tasks must be completed
446 async def test_scale(self):
447 # print("Test scale started")
448
449 # TODO: Add more higher-lever tests here, for example:
450 # scale-out/scale-in operations with success/error result
451
452 # Test scale() with missing 'scaleVnfData', should return operationState = 'FAILED'
453 nsr_id = descriptors.test_ids["TEST-A"]["ns"]
454 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
455 await self.my_ns.scale(nsr_id, nslcmop_id)
456 expected_value = "FAILED"
457 return_value = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
458 "operationState"
459 )
460 self.assertEqual(return_value, expected_value)
461 # print("scale_result: {}".format(self.db.get_one("nslcmops", {"_id": nslcmop_id}).get("detailed-status")))
462
463 # Test scale() for native kdu
464 # this also includes testing _scale_kdu()
465 nsr_id = descriptors.test_ids["TEST-NATIVE-KDU"]["ns"]
466 nslcmop_id = descriptors.test_ids["TEST-NATIVE-KDU"]["instantiate"]
467
468 self.my_ns.k8sclusterjuju.scale = asynctest.mock.CoroutineMock()
469 self.my_ns.k8sclusterjuju.exec_primitive = asynctest.mock.CoroutineMock()
470 self.my_ns.k8sclusterjuju.get_scale_count = asynctest.mock.CoroutineMock(
471 return_value=1
472 )
473 await self.my_ns.scale(nsr_id, nslcmop_id)
474 expected_value = "COMPLETED"
475 return_value = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
476 "operationState"
477 )
478 self.assertEqual(return_value, expected_value)
479 self.my_ns.k8sclusterjuju.scale.assert_called_once()
480
481 # Test scale() for native kdu with 2 resource
482 nsr_id = descriptors.test_ids["TEST-NATIVE-KDU-2"]["ns"]
483 nslcmop_id = descriptors.test_ids["TEST-NATIVE-KDU-2"]["instantiate"]
484
485 self.my_ns.k8sclusterjuju.get_scale_count.return_value = 2
486 await self.my_ns.scale(nsr_id, nslcmop_id)
487 expected_value = "COMPLETED"
488 return_value = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
489 "operationState"
490 )
491 self.assertEqual(return_value, expected_value)
492 self.my_ns.k8sclusterjuju.scale.assert_called()
493
494 async def test_vca_status_refresh(self):
495 nsr_id = descriptors.test_ids["TEST-A"]["ns"]
496 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
497 await self.my_ns.vca_status_refresh(nsr_id, nslcmop_id)
498 expected_value = dict()
499 return_value = dict()
500 vnf_descriptors = self.db.get_list("vnfds")
501 for i, _ in enumerate(vnf_descriptors):
502 for j, value in enumerate(vnf_descriptors[i]["df"]):
503 if "lcm-operations-configuration" in vnf_descriptors[i]["df"][j]:
504 if (
505 "day1-2"
506 in value["lcm-operations-configuration"][
507 "operate-vnf-op-config"
508 ]
509 ):
510 for k, v in enumerate(
511 value["lcm-operations-configuration"][
512 "operate-vnf-op-config"
513 ]["day1-2"]
514 ):
515 if (
516 v.get("execution-environment-list")
517 and "juju" in v["execution-environment-list"][k]
518 ):
519 expected_value = self.db.get_list("nsrs")[i][
520 "vcaStatus"
521 ]
522 await self.my_ns._on_update_n2vc_db(
523 "nsrs", {"_id": nsr_id}, "_admin.deployed.VCA.0", {}
524 )
525 return_value = self.db.get_list("nsrs")[i]["vcaStatus"]
526 self.assertEqual(return_value, expected_value)
527
528 # Test _retry_or_skip_suboperation()
529 # Expected result:
530 # - if a suboperation's 'operationState' is marked as 'COMPLETED', SUBOPERATION_STATUS_SKIP is expected
531 # - if marked as anything but 'COMPLETED', the suboperation index is expected
532 def test_scale_retry_or_skip_suboperation(self):
533 # Load an alternative 'nslcmops' YAML for this test
534 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
535 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
536 op_index = 2
537 # Test when 'operationState' is 'COMPLETED'
538 db_nslcmop["_admin"]["operations"][op_index]["operationState"] = "COMPLETED"
539 return_value = self.my_ns._retry_or_skip_suboperation(db_nslcmop, op_index)
540 expected_value = self.my_ns.SUBOPERATION_STATUS_SKIP
541 self.assertEqual(return_value, expected_value)
542 # Test when 'operationState' is not 'COMPLETED'
543 db_nslcmop["_admin"]["operations"][op_index]["operationState"] = None
544 return_value = self.my_ns._retry_or_skip_suboperation(db_nslcmop, op_index)
545 expected_value = op_index
546 self.assertEqual(return_value, expected_value)
547
548 # Test _find_suboperation()
549 # Expected result: index of the found sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if not found
550 def test_scale_find_suboperation(self):
551 # Load an alternative 'nslcmops' YAML for this test
552 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
553 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
554 # Find this sub-operation
555 op_index = 2
556 vnf_index = db_nslcmop["_admin"]["operations"][op_index]["member_vnf_index"]
557 primitive = db_nslcmop["_admin"]["operations"][op_index]["primitive"]
558 primitive_params = db_nslcmop["_admin"]["operations"][op_index][
559 "primitive_params"
560 ]
561 match = {
562 "member_vnf_index": vnf_index,
563 "primitive": primitive,
564 "primitive_params": primitive_params,
565 }
566 found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
567 self.assertEqual(found_op_index, op_index)
568 # Test with not-matching params
569 match = {
570 "member_vnf_index": vnf_index,
571 "primitive": "",
572 "primitive_params": primitive_params,
573 }
574 found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
575 self.assertEqual(found_op_index, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
576 # Test with None
577 match = None
578 found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
579 self.assertEqual(found_op_index, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
580
581 # Test _update_suboperation_status()
582 def test_scale_update_suboperation_status(self):
583 self.db.set_one = asynctest.Mock()
584 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
585 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
586 op_index = 0
587 # Force the initial values to be distinct from the updated ones
588 q_filter = {"_id": db_nslcmop["_id"]}
589 # Test to change 'operationState' and 'detailed-status'
590 operationState = "COMPLETED"
591 detailed_status = "Done"
592 expected_update_dict = {
593 "_admin.operations.0.operationState": operationState,
594 "_admin.operations.0.detailed-status": detailed_status,
595 }
596 self.my_ns._update_suboperation_status(
597 db_nslcmop, op_index, operationState, detailed_status
598 )
599 self.db.set_one.assert_called_once_with(
600 "nslcmops",
601 q_filter=q_filter,
602 update_dict=expected_update_dict,
603 fail_on_empty=False,
604 )
605
606 def test_scale_add_suboperation(self):
607 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
608 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
609 vnf_index = "1"
610 num_ops_before = len(db_nslcmop.get("_admin", {}).get("operations", [])) - 1
611 vdu_id = None
612 vdu_count_index = None
613 vdu_name = None
614 primitive = "touch"
615 mapped_primitive_params = {
616 "parameter": [
617 {
618 "data-type": "STRING",
619 "name": "filename",
620 "default-value": "<touch_filename2>",
621 }
622 ],
623 "name": "touch",
624 }
625 operationState = "PROCESSING"
626 detailed_status = "In progress"
627 operationType = "PRE-SCALE"
628 # Add a 'pre-scale' suboperation
629 op_index_after = self.my_ns._add_suboperation(
630 db_nslcmop,
631 vnf_index,
632 vdu_id,
633 vdu_count_index,
634 vdu_name,
635 primitive,
636 mapped_primitive_params,
637 operationState,
638 detailed_status,
639 operationType,
640 )
641 self.assertEqual(op_index_after, num_ops_before + 1)
642
643 # Delete all suboperations and add the same operation again
644 del db_nslcmop["_admin"]["operations"]
645 op_index_zero = self.my_ns._add_suboperation(
646 db_nslcmop,
647 vnf_index,
648 vdu_id,
649 vdu_count_index,
650 vdu_name,
651 primitive,
652 mapped_primitive_params,
653 operationState,
654 detailed_status,
655 operationType,
656 )
657 self.assertEqual(op_index_zero, 0)
658
659 # Add a 'RO' suboperation
660 RO_nsr_id = "1234567890"
661 RO_scaling_info = [
662 {
663 "type": "create",
664 "count": 1,
665 "member-vnf-index": "1",
666 "osm_vdu_id": "dataVM",
667 }
668 ]
669 op_index = self.my_ns._add_suboperation(
670 db_nslcmop,
671 vnf_index,
672 vdu_id,
673 vdu_count_index,
674 vdu_name,
675 primitive,
676 mapped_primitive_params,
677 operationState,
678 detailed_status,
679 operationType,
680 RO_nsr_id,
681 RO_scaling_info,
682 )
683 db_RO_nsr_id = db_nslcmop["_admin"]["operations"][op_index]["RO_nsr_id"]
684 self.assertEqual(op_index, 1)
685 self.assertEqual(RO_nsr_id, db_RO_nsr_id)
686
687 # Try to add an invalid suboperation, should return SUBOPERATION_STATUS_NOT_FOUND
688 op_index_invalid = self.my_ns._add_suboperation(
689 None, None, None, None, None, None, None, None, None, None, None
690 )
691 self.assertEqual(op_index_invalid, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
692
693 # Test _check_or_add_scale_suboperation() and _check_or_add_scale_suboperation_RO()
694 # check the possible return values:
695 # - SUBOPERATION_STATUS_NEW: This is a new sub-operation
696 # - op_index (non-negative number): This is an existing sub-operation, operationState != 'COMPLETED'
697 # - SUBOPERATION_STATUS_SKIP: This is an existing sub-operation, operationState == 'COMPLETED'
698 def test_scale_check_or_add_scale_suboperation(self):
699 nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
700 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
701 operationType = "PRE-SCALE"
702 vnf_index = "1"
703 primitive = "touch"
704 primitive_params = {
705 "parameter": [
706 {
707 "data-type": "STRING",
708 "name": "filename",
709 "default-value": "<touch_filename2>",
710 }
711 ],
712 "name": "touch",
713 }
714
715 # Delete all sub-operations to be sure this is a new sub-operation
716 del db_nslcmop["_admin"]["operations"]
717
718 # Add a new sub-operation
719 # For new sub-operations, operationState is set to 'PROCESSING' by default
720 op_index_new = self.my_ns._check_or_add_scale_suboperation(
721 db_nslcmop, vnf_index, primitive, primitive_params, operationType
722 )
723 self.assertEqual(op_index_new, self.my_ns.SUBOPERATION_STATUS_NEW)
724
725 # Use the same parameters again to match the already added sub-operation
726 # which has status 'PROCESSING' (!= 'COMPLETED') by default
727 # The expected return value is a non-negative number
728 op_index_existing = self.my_ns._check_or_add_scale_suboperation(
729 db_nslcmop, vnf_index, primitive, primitive_params, operationType
730 )
731 self.assertTrue(op_index_existing >= 0)
732
733 # Change operationState 'manually' for this sub-operation
734 db_nslcmop["_admin"]["operations"][op_index_existing][
735 "operationState"
736 ] = "COMPLETED"
737 # Then use the same parameters again to match the already added sub-operation,
738 # which now has status 'COMPLETED'
739 # The expected return value is SUBOPERATION_STATUS_SKIP
740 op_index_skip = self.my_ns._check_or_add_scale_suboperation(
741 db_nslcmop, vnf_index, primitive, primitive_params, operationType
742 )
743 self.assertEqual(op_index_skip, self.my_ns.SUBOPERATION_STATUS_SKIP)
744
745 # RO sub-operation test:
746 # Repeat tests for the very similar _check_or_add_scale_suboperation_RO(),
747 RO_nsr_id = "1234567890"
748 RO_scaling_info = [
749 {
750 "type": "create",
751 "count": 1,
752 "member-vnf-index": "1",
753 "osm_vdu_id": "dataVM",
754 }
755 ]
756 op_index_new_RO = self.my_ns._check_or_add_scale_suboperation(
757 db_nslcmop, vnf_index, None, None, "SCALE-RO", RO_nsr_id, RO_scaling_info
758 )
759 self.assertEqual(op_index_new_RO, self.my_ns.SUBOPERATION_STATUS_NEW)
760
761 # Use the same parameters again to match the already added RO sub-operation
762 op_index_existing_RO = self.my_ns._check_or_add_scale_suboperation(
763 db_nslcmop, vnf_index, None, None, "SCALE-RO", RO_nsr_id, RO_scaling_info
764 )
765 self.assertTrue(op_index_existing_RO >= 0)
766
767 # Change operationState 'manually' for this RO sub-operation
768 db_nslcmop["_admin"]["operations"][op_index_existing_RO][
769 "operationState"
770 ] = "COMPLETED"
771 # Then use the same parameters again to match the already added sub-operation,
772 # which now has status 'COMPLETED'
773 # The expected return value is SUBOPERATION_STATUS_SKIP
774 op_index_skip_RO = self.my_ns._check_or_add_scale_suboperation(
775 db_nslcmop, vnf_index, None, None, "SCALE-RO", RO_nsr_id, RO_scaling_info
776 )
777 self.assertEqual(op_index_skip_RO, self.my_ns.SUBOPERATION_STATUS_SKIP)
778
779 async def test_deploy_kdus(self):
780 nsr_id = descriptors.test_ids["TEST-KDU"]["ns"]
781 nslcmop_id = descriptors.test_ids["TEST-KDU"]["instantiate"]
782 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
783 db_vnfr = self.db.get_one(
784 "vnfrs", {"nsr-id-ref": nsr_id, "member-vnf-index-ref": "multikdu"}
785 )
786 db_vnfrs = {"multikdu": db_vnfr}
787 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
788 db_vnfds = [db_vnfd]
789 task_register = {}
790 logging_text = "KDU"
791 self.my_ns.k8sclusterhelm3.generate_kdu_instance_name = asynctest.mock.Mock()
792 self.my_ns.k8sclusterhelm3.generate_kdu_instance_name.return_value = "k8s_id"
793 self.my_ns.k8sclusterhelm3.install = asynctest.CoroutineMock()
794 self.my_ns.k8sclusterhelm3.synchronize_repos = asynctest.CoroutineMock(
795 return_value=("", "")
796 )
797 self.my_ns.k8sclusterhelm3.get_services = asynctest.CoroutineMock(
798 return_value=([])
799 )
800 await self.my_ns.deploy_kdus(
801 logging_text, nsr_id, nslcmop_id, db_vnfrs, db_vnfds, task_register
802 )
803 await asyncio.wait(list(task_register.keys()), timeout=100)
804 db_nsr = self.db.get_list("nsrs")[1]
805 self.assertIn(
806 "K8s",
807 db_nsr["_admin"]["deployed"],
808 "K8s entry not created at '_admin.deployed'",
809 )
810 self.assertIsInstance(
811 db_nsr["_admin"]["deployed"]["K8s"], list, "K8s entry is not of type list"
812 )
813 self.assertEqual(
814 len(db_nsr["_admin"]["deployed"]["K8s"]), 2, "K8s entry is not of type list"
815 )
816 k8s_instace_info = {
817 "kdu-instance": "k8s_id",
818 "k8scluster-uuid": "73d96432-d692-40d2-8440-e0c73aee209c",
819 "k8scluster-type": "helm-chart-v3",
820 "kdu-name": "ldap",
821 "member-vnf-index": "multikdu",
822 "namespace": None,
823 "kdu-deployment-name": None,
824 }
825
826 nsr_result = copy.deepcopy(db_nsr["_admin"]["deployed"]["K8s"][0])
827 nsr_kdu_model_result = nsr_result.pop("kdu-model")
828 expected_kdu_model = "stable/openldap:1.2.1"
829 self.assertEqual(nsr_result, k8s_instace_info)
830 self.assertTrue(
831 nsr_kdu_model_result in expected_kdu_model
832 or expected_kdu_model in nsr_kdu_model_result
833 )
834 nsr_result = copy.deepcopy(db_nsr["_admin"]["deployed"]["K8s"][1])
835 nsr_kdu_model_result = nsr_result.pop("kdu-model")
836 k8s_instace_info["kdu-name"] = "mongo"
837 expected_kdu_model = "stable/mongodb"
838 self.assertEqual(nsr_result, k8s_instace_info)
839 self.assertTrue(
840 nsr_kdu_model_result in expected_kdu_model
841 or expected_kdu_model in nsr_kdu_model_result
842 )
843
844 # Test remove_vnf() and related methods
845 @asynctest.fail_on(active_handles=True) # all async tasks must be completed
846 async def test_remove_vnf(self):
847 # Test REMOVE_VNF
848 nsr_id = descriptors.test_ids["TEST-UPDATE"]["ns"]
849 nslcmop_id = descriptors.test_ids["TEST-UPDATE"]["removeVnf"]
850 vnf_instance_id = descriptors.test_ids["TEST-UPDATE"]["vnf"]
851 mock_wait_ng_ro = asynctest.CoroutineMock()
852 with patch("osm_lcm.ns.NsLcm._wait_ng_ro", mock_wait_ng_ro):
853 await self.my_ns.update(nsr_id, nslcmop_id)
854 expected_value = "COMPLETED"
855 return_value = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
856 "operationState"
857 )
858 self.assertEqual(return_value, expected_value)
859 with self.assertRaises(Exception) as context:
860 self.db.get_one("vnfrs", {"_id": vnf_instance_id})
861 self.assertTrue(
862 "database exception Not found entry with filter"
863 in str(context.exception)
864 )
865
866 # test vertical scale executes sucessfully
867 # @patch("osm_lcm.ng_ro.status.response")
868 @asynctest.fail_on(active_handles=True)
869 async def test_vertical_scaling(self):
870 nsr_id = descriptors.test_ids["TEST-V-SCALE"]["ns"]
871 nslcmop_id = descriptors.test_ids["TEST-V-SCALE"]["instantiate"]
872
873 # calling the vertical scale fucntion
874 # self.my_ns.RO.status = asynctest.CoroutineMock(self.my_ns.RO.status, side_effect=self._ro_status("update"))
875 mock_wait_ng_ro = asynctest.CoroutineMock()
876 with patch("osm_lcm.ns.NsLcm._wait_ng_ro", mock_wait_ng_ro):
877 await self.my_ns.vertical_scale(nsr_id, nslcmop_id)
878 return_value = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
879 "operationState"
880 )
881 expected_value = "COMPLETED"
882 self.assertEqual(return_value, expected_value)
883
884 # test vertical scale executes fail
885 @asynctest.fail_on(active_handles=True)
886 async def test_vertical_scaling_fail(self):
887 # get th nsr nad nslcmops id from descriptors
888 nsr_id = descriptors.test_ids["TEST-V-SCALE"]["ns"]
889 nslcmop_id = descriptors.test_ids["TEST-V-SCALE"]["instantiate-1"]
890
891 # calling the vertical scale fucntion
892 await self.my_ns.vertical_scale(nsr_id, nslcmop_id)
893 return_value = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
894 "operationState"
895 )
896 expected_value = "FAILED"
897 self.assertEqual(return_value, expected_value)
898
899 # async def test_instantiate_pdu(self):
900 # nsr_id = descriptors.test_ids["TEST-A"]["ns"]
901 # nslcmop_id = descriptors.test_ids["TEST-A"]["instantiate"]
902 # # Modify vnfd/vnfr to change KDU for PDU. Adding keys that NBI will already set
903 # self.db.set_one("vnfrs", {"nsr-id-ref": nsr_id, "member-vnf-index-ref": "1"},
904 # update_dict={"ip-address": "10.205.1.46",
905 # "vdur.0.pdu-id": "53e1ec21-2464-451e-a8dc-6e311d45b2c8",
906 # "vdur.0.pdu-type": "PDU-TYPE-1",
907 # "vdur.0.ip-address": "10.205.1.46",
908 # },
909 # unset={"vdur.status": None})
910 # self.db.set_one("vnfrs", {"nsr-id-ref": nsr_id, "member-vnf-index-ref": "2"},
911 # update_dict={"ip-address": "10.205.1.47",
912 # "vdur.0.pdu-id": "53e1ec21-2464-451e-a8dc-6e311d45b2c8",
913 # "vdur.0.pdu-type": "PDU-TYPE-1",
914 # "vdur.0.ip-address": "10.205.1.47",
915 # },
916 # unset={"vdur.status": None})
917
918 # await self.my_ns.instantiate(nsr_id, nslcmop_id)
919 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
920 # self.assertEqual(db_nsr.get("nsState"), "READY", str(db_nsr.get("errorDescription ")))
921 # self.assertEqual(db_nsr.get("currentOperation"), "IDLE", "currentOperation different than 'IDLE'")
922 # self.assertEqual(db_nsr.get("currentOperationID"), None, "currentOperationID different than None")
923 # self.assertEqual(db_nsr.get("errorDescription "), None, "errorDescription different than None")
924 # self.assertEqual(db_nsr.get("errorDetail"), None, "errorDetail different than None")
925
926 # @asynctest.fail_on(active_handles=True) # all async tasks must be completed
927 # async def test_terminate_without_configuration(self):
928 # nsr_id = descriptors.test_ids["TEST-A"]["ns"]
929 # nslcmop_id = descriptors.test_ids["TEST-A"]["terminate"]
930 # # set instantiation task as completed
931 # self.db.set_list("nslcmops", {"nsInstanceId": nsr_id, "_id.ne": nslcmop_id},
932 # update_dict={"operationState": "COMPLETED"})
933 # self.db.set_one("nsrs", {"_id": nsr_id},
934 # update_dict={"_admin.deployed.VCA.0": None, "_admin.deployed.VCA.1": None})
935
936 # await self.my_ns.terminate(nsr_id, nslcmop_id)
937 # db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
938 # self.assertEqual(db_nslcmop.get("operationState"), 'COMPLETED', db_nslcmop.get("detailed-status"))
939 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
940 # self.assertEqual(db_nsr.get("nsState"), "NOT_INSTANTIATED", str(db_nsr.get("errorDescription ")))
941 # self.assertEqual(db_nsr["_admin"].get("nsState"), "NOT_INSTANTIATED", str(db_nsr.get("errorDescription ")))
942 # self.assertEqual(db_nsr.get("currentOperation"), "IDLE", "currentOperation different than 'IDLE'")
943 # self.assertEqual(db_nsr.get("currentOperationID"), None, "currentOperationID different than None")
944 # self.assertEqual(db_nsr.get("errorDescription "), None, "errorDescription different than None")
945 # self.assertEqual(db_nsr.get("errorDetail"), None, "errorDetail different than None")
946 # db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
947 # for vnfr in db_vnfrs_list:
948 # self.assertEqual(vnfr["_admin"].get("nsState"), "NOT_INSTANTIATED", "Not instantiated")
949
950 # @asynctest.fail_on(active_handles=True) # all async tasks must be completed
951 # async def test_terminate_primitive(self):
952 # nsr_id = descriptors.test_ids["TEST-A"]["ns"]
953 # nslcmop_id = descriptors.test_ids["TEST-A"]["terminate"]
954 # # set instantiation task as completed
955 # self.db.set_list("nslcmops", {"nsInstanceId": nsr_id, "_id.ne": nslcmop_id},
956 # update_dict={"operationState": "COMPLETED"})
957
958 # # modify vnfd descriptor to include terminate_primitive
959 # terminate_primitive = [{
960 # "name": "touch",
961 # "parameter": [{"name": "filename", "value": "terminate_filename"}],
962 # "seq": '1'
963 # }]
964 # db_vnfr = self.db.get_one("vnfrs", {"nsr-id-ref": nsr_id, "member-vnf-index-ref": "1"})
965 # self.db.set_one("vnfds", {"_id": db_vnfr["vnfd-id"]},
966 # {"vnf-configuration.0.terminate-config-primitive": terminate_primitive})
967
968 # await self.my_ns.terminate(nsr_id, nslcmop_id)
969 # db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
970 # self.assertEqual(db_nslcmop.get("operationState"), 'COMPLETED', db_nslcmop.get("detailed-status"))
971 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
972 # self.assertEqual(db_nsr.get("nsState"), "NOT_INSTANTIATED", str(db_nsr.get("errorDescription ")))
973 # self.assertEqual(db_nsr["_admin"].get("nsState"), "NOT_INSTANTIATED", str(db_nsr.get("errorDescription ")))
974 # self.assertEqual(db_nsr.get("currentOperation"), "IDLE", "currentOperation different than 'IDLE'")
975 # self.assertEqual(db_nsr.get("currentOperationID"), None, "currentOperationID different than None")
976 # self.assertEqual(db_nsr.get("errorDescription "), None, "errorDescription different than None")
977 # self.assertEqual(db_nsr.get("errorDetail"), None, "errorDetail different than None")
978
979 @patch("osm_lcm.lcm_utils.LcmBase.check_charm_hash_changed")
980 @patch(
981 "osm_lcm.ns.NsLcm._ns_charm_upgrade", new_callable=asynctest.Mock(autospec=True)
982 )
983 @patch("osm_lcm.data_utils.vnfd.find_software_version")
984 @patch("osm_lcm.lcm_utils.check_juju_bundle_existence")
985 async def test_update_change_vnfpkg_sw_version_not_changed(
986 self,
987 mock_juju_bundle,
988 mock_software_version,
989 mock_charm_upgrade,
990 mock_charm_hash,
991 ):
992 """Update type: CHANGE_VNFPKG, latest_vnfd revision changed,
993 Charm package changed, sw-version is not changed"""
994 self.db.set_one(
995 "vnfds",
996 q_filter={"_id": vnfd_id},
997 update_dict={"_admin.revision": 3, "kdu": []},
998 )
999
1000 self.db.set_one(
1001 "vnfds_revisions",
1002 q_filter={"_id": vnfd_id + ":1"},
1003 update_dict={"_admin.revision": 1, "kdu": []},
1004 )
1005
1006 self.db.set_one("vnfrs", q_filter={"_id": vnfr_id}, update_dict={"revision": 1})
1007
1008 mock_charm_hash.return_value = True
1009 mock_software_version.side_effect = ["1.0", "1.0"]
1010
1011 task = asyncio.Future()
1012 task.set_result(("COMPLETED", "some_output"))
1013 mock_charm_upgrade.return_value = task
1014
1015 instance = self.my_ns
1016 fs = deepcopy(update_fs)
1017 instance.fs = fs
1018
1019 expected_operation_state = "COMPLETED"
1020 expected_operation_error = ""
1021 expected_vnfr_revision = 3
1022 expected_ns_state = "INSTANTIATED"
1023 expected_ns_operational_state = "running"
1024
1025 await instance.update(nsr_id, nslcmop_id)
1026 return_operation_state = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
1027 "operationState"
1028 )
1029 return_operation_error = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
1030 "errorMessage"
1031 )
1032 return_ns_operational_state = self.db.get_one("nsrs", {"_id": nsr_id}).get(
1033 "operational-status"
1034 )
1035 return_vnfr_revision = self.db.get_one("vnfrs", {"_id": vnfr_id}).get(
1036 "revision"
1037 )
1038 return_ns_state = self.db.get_one("nsrs", {"_id": nsr_id}).get("nsState")
1039 mock_charm_hash.assert_called_with(
1040 f"{vnfd_id}:1/hackfest_3charmed_vnfd/charms/simple",
1041 f"{vnfd_id}:3/hackfest_3charmed_vnfd/charms/simple",
1042 )
1043 self.assertEqual(fs.sync.call_count, 2)
1044 self.assertEqual(return_ns_state, expected_ns_state)
1045 self.assertEqual(return_operation_state, expected_operation_state)
1046 self.assertEqual(return_operation_error, expected_operation_error)
1047 self.assertEqual(return_ns_operational_state, expected_ns_operational_state)
1048 self.assertEqual(return_vnfr_revision, expected_vnfr_revision)
1049
1050 @patch("osm_lcm.lcm_utils.LcmBase.check_charm_hash_changed")
1051 @patch(
1052 "osm_lcm.ns.NsLcm._ns_charm_upgrade", new_callable=asynctest.Mock(autospec=True)
1053 )
1054 @patch("osm_lcm.data_utils.vnfd.find_software_version")
1055 @patch("osm_lcm.lcm_utils.check_juju_bundle_existence")
1056 async def test_update_change_vnfpkg_vnfd_revision_not_changed(
1057 self,
1058 mock_juju_bundle,
1059 mock_software_version,
1060 mock_charm_upgrade,
1061 mock_charm_hash,
1062 ):
1063 """Update type: CHANGE_VNFPKG, latest_vnfd revision not changed"""
1064 self.db.set_one(
1065 "vnfds", q_filter={"_id": vnfd_id}, update_dict={"_admin.revision": 1}
1066 )
1067 self.db.set_one("vnfrs", q_filter={"_id": vnfr_id}, update_dict={"revision": 1})
1068
1069 mock_charm_hash.return_value = True
1070
1071 task = asyncio.Future()
1072 task.set_result(("COMPLETED", "some_output"))
1073 mock_charm_upgrade.return_value = task
1074
1075 instance = self.my_ns
1076
1077 expected_operation_state = "COMPLETED"
1078 expected_operation_error = ""
1079 expected_vnfr_revision = 1
1080 expected_ns_state = "INSTANTIATED"
1081 expected_ns_operational_state = "running"
1082
1083 await instance.update(nsr_id, nslcmop_id)
1084 return_operation_state = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
1085 "operationState"
1086 )
1087 return_operation_error = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
1088 "errorMessage"
1089 )
1090 return_ns_operational_state = self.db.get_one("nsrs", {"_id": nsr_id}).get(
1091 "operational-status"
1092 )
1093 return_ns_state = self.db.get_one("nsrs", {"_id": nsr_id}).get("nsState")
1094 return_vnfr_revision = self.db.get_one("vnfrs", {"_id": vnfr_id}).get(
1095 "revision"
1096 )
1097 mock_charm_hash.assert_not_called()
1098 mock_software_version.assert_not_called()
1099 mock_juju_bundle.assert_not_called()
1100 mock_charm_upgrade.assert_not_called()
1101 update_fs.sync.assert_not_called()
1102 self.assertEqual(return_ns_state, expected_ns_state)
1103 self.assertEqual(return_operation_state, expected_operation_state)
1104 self.assertEqual(return_operation_error, expected_operation_error)
1105 self.assertEqual(return_ns_operational_state, expected_ns_operational_state)
1106 self.assertEqual(return_vnfr_revision, expected_vnfr_revision)
1107
1108 @patch("osm_lcm.lcm_utils.LcmBase.check_charm_hash_changed")
1109 @patch(
1110 "osm_lcm.ns.NsLcm._ns_charm_upgrade", new_callable=asynctest.Mock(autospec=True)
1111 )
1112 @patch("osm_lcm.data_utils.vnfd.find_software_version")
1113 @patch("osm_lcm.lcm_utils.check_juju_bundle_existence")
1114 async def test_update_change_vnfpkg_charm_is_not_changed(
1115 self,
1116 mock_juju_bundle,
1117 mock_software_version,
1118 mock_charm_upgrade,
1119 mock_charm_hash,
1120 ):
1121 """Update type: CHANGE_VNFPKG, latest_vnfd revision changed
1122 Charm package is not changed, sw-version is not changed"""
1123 self.db.set_one(
1124 "vnfds",
1125 q_filter={"_id": vnfd_id},
1126 update_dict={"_admin.revision": 3, "kdu": []},
1127 )
1128 self.db.set_one(
1129 "vnfds_revisions",
1130 q_filter={"_id": vnfd_id + ":1"},
1131 update_dict={"_admin.revision": 1, "kdu": []},
1132 )
1133 self.db.set_one("vnfrs", q_filter={"_id": vnfr_id}, update_dict={"revision": 1})
1134
1135 mock_charm_hash.return_value = False
1136 mock_software_version.side_effect = ["1.0", "1.0"]
1137
1138 instance = self.my_ns
1139 fs = deepcopy(update_fs)
1140 instance.fs = fs
1141 expected_operation_state = "COMPLETED"
1142 expected_operation_error = ""
1143 expected_vnfr_revision = 3
1144 expected_ns_state = "INSTANTIATED"
1145 expected_ns_operational_state = "running"
1146
1147 await instance.update(nsr_id, nslcmop_id)
1148 return_operation_state = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
1149 "operationState"
1150 )
1151 return_operation_error = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
1152 "errorMessage"
1153 )
1154 return_ns_operational_state = self.db.get_one("nsrs", {"_id": nsr_id}).get(
1155 "operational-status"
1156 )
1157 return_vnfr_revision = self.db.get_one("vnfrs", {"_id": vnfr_id}).get(
1158 "revision"
1159 )
1160 return_ns_state = self.db.get_one("nsrs", {"_id": nsr_id}).get("nsState")
1161 mock_charm_hash.assert_called_with(
1162 f"{vnfd_id}:1/hackfest_3charmed_vnfd/charms/simple",
1163 f"{vnfd_id}:3/hackfest_3charmed_vnfd/charms/simple",
1164 )
1165 self.assertEqual(fs.sync.call_count, 2)
1166 self.assertEqual(mock_charm_hash.call_count, 1)
1167 mock_juju_bundle.assert_not_called()
1168 mock_charm_upgrade.assert_not_called()
1169 self.assertEqual(return_ns_state, expected_ns_state)
1170 self.assertEqual(return_operation_state, expected_operation_state)
1171 self.assertEqual(return_operation_error, expected_operation_error)
1172 self.assertEqual(return_ns_operational_state, expected_ns_operational_state)
1173 self.assertEqual(return_vnfr_revision, expected_vnfr_revision)
1174
1175 @patch("osm_lcm.lcm_utils.check_juju_bundle_existence")
1176 @patch("osm_lcm.lcm_utils.LcmBase.check_charm_hash_changed")
1177 @patch(
1178 "osm_lcm.ns.NsLcm._ns_charm_upgrade", new_callable=asynctest.Mock(autospec=True)
1179 )
1180 @patch("osm_lcm.lcm_utils.get_charm_artifact_path")
1181 async def test_update_change_vnfpkg_sw_version_changed(
1182 self, mock_charm_artifact, mock_charm_upgrade, mock_charm_hash, mock_juju_bundle
1183 ):
1184 """Update type: CHANGE_VNFPKG, latest_vnfd revision changed
1185 Charm package exists, sw-version changed."""
1186 self.db.set_one(
1187 "vnfds",
1188 q_filter={"_id": vnfd_id},
1189 update_dict={"_admin.revision": 3, "software-version": "3.0", "kdu": []},
1190 )
1191 self.db.set_one(
1192 "vnfds_revisions",
1193 q_filter={"_id": vnfd_id + ":1"},
1194 update_dict={"_admin.revision": 1, "kdu": []},
1195 )
1196 self.db.set_one("vnfrs", q_filter={"_id": vnfr_id}, update_dict={"revision": 1})
1197 mock_charm_hash.return_value = False
1198
1199 mock_charm_artifact.side_effect = [
1200 f"{vnfd_id}:1/hackfest_3charmed_vnfd/charms/simple",
1201 f"{vnfd_id}:3/hackfest_3charmed_vnfd/charms/simple",
1202 ]
1203
1204 instance = self.my_ns
1205 fs = deepcopy(update_fs)
1206 instance.fs = fs
1207 expected_operation_state = "FAILED"
1208 expected_operation_error = "FAILED Checking if existing VNF has charm: Software version change is not supported as VNF instance 6421c7c9-d865-4fb4-9a13-d4275d243e01 has charm."
1209 expected_vnfr_revision = 1
1210 expected_ns_state = "INSTANTIATED"
1211 expected_ns_operational_state = "running"
1212
1213 await instance.update(nsr_id, nslcmop_id)
1214 return_operation_state = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
1215 "operationState"
1216 )
1217 return_operation_error = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
1218 "errorMessage"
1219 )
1220 return_ns_operational_state = self.db.get_one("nsrs", {"_id": nsr_id}).get(
1221 "operational-status"
1222 )
1223 return_vnfr_revision = self.db.get_one("vnfrs", {"_id": vnfr_id}).get(
1224 "revision"
1225 )
1226 return_ns_state = self.db.get_one("nsrs", {"_id": nsr_id}).get("nsState")
1227 self.assertEqual(fs.sync.call_count, 2)
1228 mock_charm_hash.assert_not_called()
1229 mock_juju_bundle.assert_not_called()
1230 mock_charm_upgrade.assert_not_called()
1231 self.assertEqual(return_ns_state, expected_ns_state)
1232 self.assertEqual(return_operation_state, expected_operation_state)
1233 self.assertEqual(return_operation_error, expected_operation_error)
1234 self.assertEqual(return_ns_operational_state, expected_ns_operational_state)
1235 self.assertEqual(return_vnfr_revision, expected_vnfr_revision)
1236
1237 @patch("osm_lcm.lcm_utils.check_juju_bundle_existence")
1238 @patch("osm_lcm.lcm_utils.LcmBase.check_charm_hash_changed")
1239 @patch(
1240 "osm_lcm.ns.NsLcm._ns_charm_upgrade", new_callable=asynctest.Mock(autospec=True)
1241 )
1242 @patch("osm_lcm.data_utils.vnfd.find_software_version")
1243 async def test_update_change_vnfpkg_juju_bundle_exists(
1244 self,
1245 mock_software_version,
1246 mock_charm_upgrade,
1247 mock_charm_hash,
1248 mock_juju_bundle,
1249 ):
1250 """Update type: CHANGE_VNFPKG, latest_vnfd revision changed
1251 Charm package exists, sw-version not changed, juju-bundle exists"""
1252 # Upgrade is not allowed with juju bundles, this will cause TypeError
1253 self.db.set_one(
1254 "vnfds",
1255 q_filter={"_id": vnfd_id},
1256 update_dict={
1257 "_admin.revision": 5,
1258 "software-version": "1.0",
1259 "kdu": [{"kdu_name": "native-kdu", "juju-bundle": "stable/native-kdu"}],
1260 },
1261 )
1262 self.db.set_one(
1263 "vnfds_revisions",
1264 q_filter={"_id": vnfd_id + ":1"},
1265 update_dict={
1266 "_admin.revision": 1,
1267 "software-version": "1.0",
1268 "kdu": [{"kdu_name": "native-kdu", "juju-bundle": "stable/native-kdu"}],
1269 },
1270 )
1271 self.db.set_one(
1272 "nsrs",
1273 q_filter={"_id": nsr_id},
1274 update_dict={"_admin.deployed.VCA.0.kdu_name": "native-kdu"},
1275 )
1276 self.db.set_one("vnfrs", q_filter={"_id": vnfr_id}, update_dict={"revision": 1})
1277
1278 mock_charm_hash.side_effect = [True]
1279 mock_software_version.side_effect = ["1.0", "1.0"]
1280 mock_juju_bundle.return_value = True
1281 instance = self.my_ns
1282 fs = deepcopy(update_fs)
1283 instance.fs = fs
1284
1285 expected_vnfr_revision = 1
1286 expected_ns_state = "INSTANTIATED"
1287 expected_ns_operational_state = "running"
1288
1289 await instance.update(nsr_id, nslcmop_id)
1290 return_ns_operational_state = self.db.get_one("nsrs", {"_id": nsr_id}).get(
1291 "operational-status"
1292 )
1293 return_vnfr_revision = self.db.get_one("vnfrs", {"_id": vnfr_id}).get(
1294 "revision"
1295 )
1296 return_ns_state = self.db.get_one("nsrs", {"_id": nsr_id}).get("nsState")
1297 self.assertEqual(fs.sync.call_count, 2)
1298 mock_charm_upgrade.assert_not_called()
1299 mock_charm_hash.assert_not_called()
1300 self.assertEqual(return_ns_state, expected_ns_state)
1301 self.assertEqual(return_ns_operational_state, expected_ns_operational_state)
1302 self.assertEqual(return_vnfr_revision, expected_vnfr_revision)
1303
1304 @patch("osm_lcm.lcm_utils.LcmBase.check_charm_hash_changed")
1305 @patch(
1306 "osm_lcm.ns.NsLcm._ns_charm_upgrade", new_callable=asynctest.Mock(autospec=True)
1307 )
1308 async def test_update_change_vnfpkg_charm_upgrade_failed(
1309 self, mock_charm_upgrade, mock_charm_hash
1310 ):
1311 """ "Update type: CHANGE_VNFPKG, latest_vnfd revision changed"
1312 Charm package exists, sw-version not changed, charm-upgrade failed"""
1313 self.db.set_one(
1314 "vnfds",
1315 q_filter={"_id": vnfd_id},
1316 update_dict={"_admin.revision": 3, "software-version": "1.0", "kdu": []},
1317 )
1318 self.db.set_one(
1319 "vnfds_revisions",
1320 q_filter={"_id": vnfd_id + ":1"},
1321 update_dict={"_admin.revision": 1, "software-version": "1.0", "kdu": []},
1322 )
1323 self.db.set_one("vnfrs", q_filter={"_id": vnfr_id}, update_dict={"revision": 1})
1324
1325 mock_charm_hash.return_value = True
1326
1327 task = asyncio.Future()
1328 task.set_result(("FAILED", "some_error"))
1329 mock_charm_upgrade.return_value = task
1330
1331 instance = self.my_ns
1332 fs = deepcopy(update_fs)
1333 instance.fs = fs
1334 expected_operation_state = "FAILED"
1335 expected_operation_error = "some_error"
1336 expected_vnfr_revision = 1
1337 expected_ns_state = "INSTANTIATED"
1338 expected_ns_operational_state = "running"
1339
1340 await instance.update(nsr_id, nslcmop_id)
1341 return_operation_state = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
1342 "operationState"
1343 )
1344 return_operation_error = self.db.get_one("nslcmops", {"_id": nslcmop_id}).get(
1345 "errorMessage"
1346 )
1347 return_ns_operational_state = self.db.get_one("nsrs", {"_id": nsr_id}).get(
1348 "operational-status"
1349 )
1350 return_vnfr_revision = self.db.get_one("vnfrs", {"_id": vnfr_id}).get(
1351 "revision"
1352 )
1353 return_ns_state = self.db.get_one("nsrs", {"_id": nsr_id}).get("nsState")
1354 self.assertEqual(fs.sync.call_count, 2)
1355 self.assertEqual(mock_charm_hash.call_count, 1)
1356 self.assertEqual(mock_charm_upgrade.call_count, 1)
1357 self.assertEqual(return_ns_state, expected_ns_state)
1358 self.assertEqual(return_operation_state, expected_operation_state)
1359 self.assertEqual(return_operation_error, expected_operation_error)
1360 self.assertEqual(return_ns_operational_state, expected_ns_operational_state)
1361 self.assertEqual(return_vnfr_revision, expected_vnfr_revision)
1362
1363 def test_ns_update_find_sw_version_vnfd_not_includes(self):
1364 """Find software version, VNFD does not have software version"""
1365
1366 db_vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
1367 expected_result = "1.0"
1368 result = find_software_version(db_vnfd)
1369 self.assertEqual(result, expected_result, "Default sw version should be 1.0")
1370
1371 def test_ns_update_find_sw_version_vnfd_includes(self):
1372 """Find software version, VNFD includes software version"""
1373
1374 db_vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
1375 db_vnfd["software-version"] = "3.1"
1376 expected_result = "3.1"
1377 result = find_software_version(db_vnfd)
1378 self.assertEqual(result, expected_result, "VNFD software version is wrong")
1379
1380 @patch("os.path.exists")
1381 @patch("osm_lcm.lcm_utils.LcmBase.compare_charmdir_hash")
1382 @patch("osm_lcm.lcm_utils.LcmBase.compare_charm_hash")
1383 def test_ns_update_check_charm_hash_not_changed(
1384 self, mock_compare_charm_hash, mock_compare_charmdir_hash, mock_path_exists
1385 ):
1386 """Check charm hash, Hash did not change"""
1387
1388 current_path, target_path = "/tmp/charm1", "/tmp/charm1"
1389
1390 fs = Mock()
1391 fs.path.__add__ = Mock()
1392 fs.path.side_effect = [current_path, target_path]
1393 fs.path.__add__.side_effect = [current_path, target_path]
1394
1395 mock_path_exists.side_effect = [True, True]
1396
1397 mock_compare_charmdir_hash.return_value = callable(False)
1398 mock_compare_charm_hash.return_value = callable(False)
1399
1400 instance = self.my_ns
1401 instance.fs = fs
1402 expected_result = False
1403
1404 result = instance.check_charm_hash_changed(current_path, target_path)
1405 self.assertEqual(result, expected_result, "Wrong charm hash control value")
1406 self.assertEqual(mock_path_exists.call_count, 2)
1407 self.assertEqual(mock_compare_charmdir_hash.call_count, 1)
1408 self.assertEqual(mock_compare_charm_hash.call_count, 0)
1409
1410 @patch("os.path.exists")
1411 @patch("osm_lcm.lcm_utils.LcmBase.compare_charmdir_hash")
1412 @patch("osm_lcm.lcm_utils.LcmBase.compare_charm_hash")
1413 def test_ns_update_check_charm_hash_changed(
1414 self, mock_compare_charm_hash, mock_compare_charmdir_hash, mock_path_exists
1415 ):
1416 """Check charm hash, Hash has changed"""
1417
1418 current_path, target_path = "/tmp/charm1", "/tmp/charm2"
1419
1420 fs = Mock()
1421 fs.path.__add__ = Mock()
1422 fs.path.side_effect = [current_path, target_path, current_path, target_path]
1423 fs.path.__add__.side_effect = [
1424 current_path,
1425 target_path,
1426 current_path,
1427 target_path,
1428 ]
1429
1430 mock_path_exists.side_effect = [True, True]
1431 mock_compare_charmdir_hash.return_value = callable(True)
1432 mock_compare_charm_hash.return_value = callable(True)
1433
1434 instance = self.my_ns
1435 instance.fs = fs
1436 expected_result = True
1437
1438 result = instance.check_charm_hash_changed(current_path, target_path)
1439 self.assertEqual(result, expected_result, "Wrong charm hash control value")
1440 self.assertEqual(mock_path_exists.call_count, 2)
1441 self.assertEqual(mock_compare_charmdir_hash.call_count, 1)
1442 self.assertEqual(mock_compare_charm_hash.call_count, 0)
1443
1444 @patch("os.path.exists")
1445 @patch("osm_lcm.lcm_utils.LcmBase.compare_charmdir_hash")
1446 @patch("osm_lcm.lcm_utils.LcmBase.compare_charm_hash")
1447 def test_ns_update_check_no_charm_path(
1448 self, mock_compare_charm_hash, mock_compare_charmdir_hash, mock_path_exists
1449 ):
1450 """Check charm hash, Charm path does not exist"""
1451
1452 current_path, target_path = "/tmp/charm1", "/tmp/charm2"
1453
1454 fs = Mock()
1455 fs.path.__add__ = Mock()
1456 fs.path.side_effect = [current_path, target_path, current_path, target_path]
1457 fs.path.__add__.side_effect = [
1458 current_path,
1459 target_path,
1460 current_path,
1461 target_path,
1462 ]
1463
1464 mock_path_exists.side_effect = [True, False]
1465
1466 mock_compare_charmdir_hash.return_value = callable(False)
1467 mock_compare_charm_hash.return_value = callable(False)
1468 instance = self.my_ns
1469 instance.fs = fs
1470
1471 with self.assertRaises(LcmException):
1472 instance.check_charm_hash_changed(current_path, target_path)
1473 self.assertEqual(mock_path_exists.call_count, 2)
1474 self.assertEqual(mock_compare_charmdir_hash.call_count, 0)
1475 self.assertEqual(mock_compare_charm_hash.call_count, 0)
1476
1477 def test_ns_update_check_juju_bundle_existence_bundle_exists(self):
1478 """Check juju bundle existence"""
1479 test_vnfd2 = self.db.get_one(
1480 "vnfds", {"_id": "d96b1cdf-5ad6-49f7-bf65-907ada989293"}
1481 )
1482 expected_result = "stable/native-kdu"
1483 result = check_juju_bundle_existence(test_vnfd2)
1484 self.assertEqual(result, expected_result, "Wrong juju bundle name")
1485
1486 def test_ns_update_check_juju_bundle_existence_bundle_does_not_exist(self):
1487 """Check juju bundle existence"""
1488 test_vnfd1 = self.db.get_one("vnfds", {"_id": vnfd_id})
1489 expected_result = None
1490 result = check_juju_bundle_existence(test_vnfd1)
1491 self.assertEqual(result, expected_result, "Wrong juju bundle name")
1492
1493 def test_ns_update_check_juju_bundle_existence_empty_vnfd(self):
1494 """Check juju bundle existence"""
1495 test_vnfd1 = {}
1496 expected_result = None
1497 result = check_juju_bundle_existence(test_vnfd1)
1498 self.assertEqual(result, expected_result, "Wrong juju bundle name")
1499
1500 def test_ns_update_check_juju_bundle_existence_invalid_vnfd(self):
1501 """Check juju bundle existence"""
1502 test_vnfd1 = [{"_id": vnfd_id}]
1503 with self.assertRaises(AttributeError):
1504 check_juju_bundle_existence(test_vnfd1)
1505
1506 def test_ns_update_check_juju_charm_artifacts_base_folder_wth_pkgdir(self):
1507 """Check charm artifacts"""
1508 base_folder = {"folder": vnfd_id, "pkg-dir": "hackfest_3charmed_vnfd"}
1509 charm_name = "simple"
1510 charm_type = "lxc_proxy_charm"
1511 revision = 3
1512 expected_result = f"{vnfd_id}:3/hackfest_3charmed_vnfd/charms/simple"
1513 result = get_charm_artifact_path(base_folder, charm_name, charm_type, revision)
1514 self.assertEqual(result, expected_result, "Wrong charm artifact path")
1515
1516 def test_ns_update_check_juju_charm_artifacts_base_folder_wthout_pkgdir(self):
1517 """Check charm artifacts, SOL004 packages"""
1518 base_folder = {"folder": vnfd_id}
1519 charm_name = "basic"
1520 charm_type, revision = "", ""
1521 expected_result = f"{vnfd_id}/Scripts/helm-charts/basic"
1522 result = get_charm_artifact_path(base_folder, charm_name, charm_type, revision)
1523 self.assertEqual(result, expected_result, "Wrong charm artifact path")
1524
1525
1526 class TestInstantiateN2VC(TestBaseNS):
1527 async def setUp(self):
1528 await super().setUp()
1529 self.db_nsr = yaml.safe_load(descriptors.db_nsrs_text)[0]
1530 self.db_vnfr = yaml.safe_load(descriptors.db_vnfrs_text)[0]
1531 self.vca_index = 1
1532 self.my_ns._write_configuration_status = Mock()
1533
1534 async def call_instantiate_N2VC(self):
1535 logging_text = "N2VC Instantiation"
1536 config_descriptor = {"config-access": {"ssh-access": {"default-user": "admin"}}}
1537 base_folder = {"pkg-dir": "", "folder": "~"}
1538 stage = ["Stage", "Message"]
1539
1540 await self.my_ns.instantiate_N2VC(
1541 logging_text=logging_text,
1542 vca_index=self.vca_index,
1543 nsi_id="nsi_id",
1544 db_nsr=self.db_nsr,
1545 db_vnfr=self.db_vnfr,
1546 vdu_id=None,
1547 kdu_name=None,
1548 vdu_index=None,
1549 kdu_index=None,
1550 config_descriptor=config_descriptor,
1551 deploy_params={},
1552 base_folder=base_folder,
1553 nslcmop_id="nslcmop_id",
1554 stage=stage,
1555 vca_type="native_charm",
1556 vca_name="vca_name",
1557 ee_config_descriptor={},
1558 )
1559
1560 def check_config_status(self, expected_status):
1561 self.my_ns._write_configuration_status.assert_called_with(
1562 nsr_id=self.db_nsr["_id"], vca_index=self.vca_index, status=expected_status
1563 )
1564
1565 async def call_ns_add_relation(self):
1566 ee_relation = EERelation(
1567 {
1568 "nsr-id": self.db_nsr["_id"],
1569 "vdu-profile-id": None,
1570 "kdu-resource-profile-id": None,
1571 "vnf-profile-id": "hackfest_vnf1",
1572 "execution-environment-ref": "f48163a6-c807-47bc-9682-f72caef5af85.alf-c-ab",
1573 "endpoint": "127.0.0.1",
1574 }
1575 )
1576
1577 relation = Relation("relation-name", ee_relation, ee_relation)
1578 cached_vnfrs = {"hackfest_vnf1": self.db_vnfr}
1579
1580 return await self.my_ns._add_relation(
1581 relation=relation,
1582 vca_type="native_charm",
1583 db_nsr=self.db_nsr,
1584 cached_vnfds={},
1585 cached_vnfrs=cached_vnfrs,
1586 )
1587
1588 async def test_add_relation_ok(self):
1589 await self.call_instantiate_N2VC()
1590 self.check_config_status(expected_status="READY")
1591
1592 async def test_add_relation_returns_false_raises_exception(self):
1593 self.my_ns._add_vca_relations = asynctest.CoroutineMock(return_value=False)
1594
1595 with self.assertRaises(LcmException) as exception:
1596 await self.call_instantiate_N2VC()
1597
1598 exception_msg = "Relations could not be added to VCA."
1599 self.assertTrue(exception_msg in str(exception.exception))
1600 self.check_config_status(expected_status="BROKEN")
1601
1602 async def test_add_relation_raises_lcm_exception(self):
1603 exception_msg = "Relations FAILED"
1604 self.my_ns._add_vca_relations = asynctest.CoroutineMock(
1605 side_effect=LcmException(exception_msg)
1606 )
1607
1608 with self.assertRaises(LcmException) as exception:
1609 await self.call_instantiate_N2VC()
1610
1611 self.assertTrue(exception_msg in str(exception.exception))
1612 self.check_config_status(expected_status="BROKEN")
1613
1614 async def test_n2vc_add_relation_fails_raises_exception(self):
1615 exception_msg = "N2VC failed to add relations"
1616 self.my_ns.n2vc.add_relation = asynctest.CoroutineMock(
1617 side_effect=N2VCException(exception_msg)
1618 )
1619 with self.assertRaises(LcmException) as exception:
1620 await self.call_ns_add_relation()
1621 self.assertTrue(exception_msg in str(exception.exception))
1622
1623 async def test_n2vc_add_relation_ok_returns_true(self):
1624 self.my_ns.n2vc.add_relation = asynctest.CoroutineMock(return_value=None)
1625 self.assertTrue(await self.call_ns_add_relation())
1626
1627
1628 if __name__ == "__main__":
1629 asynctest.main()