219724c8a48d7a56bb9d557cb5a983a4df7185c2
[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: esousa@whitestack.com or alfonso.tiernosepulveda@telefonica.com
16 ##
17
18
19 import asynctest # pip3 install asynctest --user
20 import asyncio
21 import yaml
22 # import logging
23 from os import getenv
24 from osm_lcm.ns import NsLcm
25 from osm_common.dbmongo import DbMongo
26 from osm_common.msgkafka import MsgKafka
27 from osm_common.fslocal import FsLocal
28 from osm_lcm.lcm_utils import TaskRegistry
29 from n2vc.vnf import N2VC
30 from uuid import uuid4
31
32 from osm_lcm.tests import test_db_descriptors as descriptors
33
34 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
35
36 """ Perform unittests using asynctest of osm_lcm.ns module
37 It allows, if some testing ENV are supplied, testing without mocking some external libraries for debugging:
38 OSMLCMTEST_NS_PUBKEY: public ssh-key returned by N2VC to inject to VMs
39 OSMLCMTEST_NS_NAME: change name of NS
40 OSMLCMTEST_PACKAGES_PATH: path where the vnf-packages are stored (de-compressed), each one on a 'vnfd_id' folder
41 OSMLCMTEST_NS_IPADDRESS: IP address where emulated VMs are reached. Comma separate list
42 OSMLCMTEST_RO_VIMID: VIM id of RO target vim IP. Obtain it with openmano datcenter-list on RO container
43 OSMLCMTEST_VCA_NOMOCK: Do no mock the VCA, N2VC library, for debugging it
44 OSMLCMTEST_RO_NOMOCK: Do no mock the ROClient library, for debugging it
45 OSMLCMTEST_DB_NOMOCK: Do no mock the database library, for debugging it
46 OSMLCMTEST_FS_NOMOCK: Do no mock the File Storage library, for debugging it
47 OSMLCMTEST_LOGGING_NOMOCK: Do no mock the logging
48 OSMLCM_VCA_XXX: configuration of N2VC
49 OSMLCM_RO_XXX: configuration of RO
50 """
51
52
53 vca_config = { # TODO replace with os.get_env to get other configurations
54 "host": getenv("OSMLCM_VCA_HOST", "vca"),
55 "port": getenv("OSMLCM_VCA_PORT", 17070),
56 "user": getenv("OSMLCM_VCA_USER", "admin"),
57 "secret": getenv("OSMLCM_VCA_SECRET", "vca"),
58 "pubkey": getenv("OSMLCM_VCA_PUBKEY", None),
59 'cacert': getenv("OSMLCM_VCA_CACERT", None)
60 }
61
62 ro_config = {
63 "endpoint_url": "http://{}:{}/openmano".format(getenv("OSMLCM_RO_HOST", "ro"), getenv("OSMLCM_RO_PORT", "9090")),
64 "tenant": getenv("OSMLCM_RO_TENANT", "osm"),
65 "logger_name": "lcm.ROclient",
66 "loglevel": "DEBUG",
67 }
68
69
70 class TestMyNS(asynctest.TestCase):
71
72 def _db_get_one(self, table, q_filter=None, fail_on_empty=True, fail_on_more=True):
73 if table not in self.db_content:
74 self.assertTrue(False, "db.get_one called with table={}".format(table))
75 for db_item in self.db_content[table]:
76 if db_item["_id"] == q_filter["_id"]:
77 return db_item
78 else:
79 self.assertTrue(False, "db.get_one, table={}, not found _id={}".format(table, q_filter["_id"]))
80
81 def _db_get_list(self, table, q_filter=None):
82 if table not in self.db_content:
83 self.assertTrue(False, "db.get_list called with table={} not found".format(table))
84 return self.db_content[table]
85
86 def _db_set_one(self, table, q_filter, update_dict, fail_on_empty=True, unset=None, pull=None, push=None):
87 db_item = self._db_get_one(table, q_filter, fail_on_empty=fail_on_empty)
88 for k, v in update_dict.items():
89 db_nested = db_item
90 k_list = k.split(".")
91 for k_nested in k_list[0:-1]:
92 if isinstance(db_nested, list):
93 db_nested = db_nested[int(k_nested)]
94 else:
95 if k_nested not in db_nested:
96 db_nested[k_nested] = {}
97 db_nested = db_nested[k_nested]
98 k_nested = k_list[-1]
99 if isinstance(db_nested, list):
100 if int(k_nested) < len(db_nested):
101 db_nested[int(k_nested)] = v
102 else:
103 db_nested.insert(int(k_nested), v)
104 else:
105 db_nested[k_nested] = v
106
107 async def _n2vc_DeployCharms(self, model_name, application_name, vnfd, charm_path, params={}, machine_spec={},
108 callback=None, *callback_args):
109 if callback:
110 for status, message in (("maintenance", "installing sofwware"), ("active", "Ready!")):
111 # call callback after some time
112 asyncio.sleep(5, loop=self.loop)
113 callback(model_name, application_name, status, message, *callback_args)
114
115 @staticmethod
116 def _n2vc_FormatApplicationName(*args):
117 num_calls = 0
118 while True:
119 yield "app_name-{}".format(num_calls)
120 num_calls += 1
121
122 def _n2vc_CreateExecutionEnvironment(self, namespace, reuse_ee_id, db_dict):
123 k_list = namespace.split(".")
124 ee_id = k_list[1] + "."
125 if len(k_list) >= 2:
126 for k in k_list[2:4]:
127 ee_id += k[:8]
128 else:
129 ee_id += "_NS_"
130 return ee_id, {}
131
132 def _ro_show(self, *args, **kwargs):
133 ro_ns_desc = yaml.load(descriptors.db_ro_ns_text, Loader=yaml.Loader)
134
135 # if ip address provided, replace descriptor
136 ip_addresses = getenv("OSMLCMTEST_NS_IPADDRESS", "")
137 if ip_addresses:
138 ip_addresses_list = ip_addresses.split(",")
139 for vnf in ro_ns_desc["vnfs"]:
140 if not ip_addresses_list:
141 break
142 vnf["ip_address"] = ip_addresses_list[0]
143 for vm in vnf["vms"]:
144 if not ip_addresses_list:
145 break
146 vm["ip_address"] = ip_addresses_list.pop(0)
147
148 while True:
149 yield ro_ns_desc
150 for net in ro_ns_desc["nets"]:
151 if net["status"] != "ACTIVE":
152 net["status"] = "ACTIVE"
153 break
154 else:
155 for vnf in ro_ns_desc["vnfs"]:
156 for vm in vnf["vms"]:
157 if vm["status"] != "ACTIVE":
158 vm["status"] = "ACTIVE"
159 break
160
161 def _ro_create(self, *args, **kwargs):
162 while True:
163 yield {"uuid": str(uuid4())}
164
165 def _return_uuid(self, *args, **kwargs):
166 return str(uuid4())
167
168 async def setUp(self):
169 # Mock DB
170 if not getenv("OSMLCMTEST_DB_NOMOCK"):
171 self.db = asynctest.Mock(DbMongo())
172 self.db.get_one.side_effect = self._db_get_one
173 self.db.get_list.side_effect = self._db_get_list
174 self.db.set_one.side_effect = self._db_set_one
175 self.db_content = {
176 "nsrs": yaml.load(descriptors.db_nsrs_text, Loader=yaml.Loader),
177 "nslcmops": yaml.load(descriptors.db_nslcmops_text, Loader=yaml.Loader),
178 "vnfrs": yaml.load(descriptors.db_vnfrs_text, Loader=yaml.Loader),
179 "vnfds": yaml.load(descriptors.db_vnfds_text, Loader=yaml.Loader),
180 "vim_accounts": yaml.load(descriptors.db_vim_accounts_text, Loader=yaml.Loader),
181 }
182 self.db_vim_accounts = yaml.load(descriptors.db_vim_accounts_text, Loader=yaml.Loader)
183
184 # Mock kafka
185 self.msg = asynctest.Mock(MsgKafka())
186
187 # Mock filesystem
188 if not getenv("OSMLCMTEST_FS_NOMOCK"):
189 self.fs = asynctest.Mock(FsLocal())
190 self.fs.get_params.return_value = {"path": getenv("OSMLCMTEST_PACKAGES_PATH", "./test/temp/packages")}
191 self.fs.file_open = asynctest.mock_open()
192 # self.fs.file_open.return_value.__enter__.return_value = asynctest.MagicMock() # called on a python "with"
193 # self.fs.file_open.return_value.__enter__.return_value.read.return_value = "" # empty file
194
195 # Mock TaskRegistry
196 self.lcm_tasks = asynctest.Mock(TaskRegistry())
197 self.lcm_tasks.lock_HA.return_value = True
198 self.lcm_tasks.waitfor_related_HA.return_value = None
199 self.lcm_tasks.lookfor_related.return_value = ("", [])
200
201 # Create NsLCM class
202 self.my_ns = NsLcm(self.db, self.msg, self.fs, self.lcm_tasks, ro_config, vca_config, self.loop)
203
204 # Mock logging
205 if not getenv("OSMLCMTEST_LOGGING_NOMOCK"):
206 self.my_ns.logger = asynctest.Mock(self.my_ns.logger)
207
208 # Mock VCA - N2VC
209 if not getenv("OSMLCMTEST_VCA_NOMOCK"):
210 pub_key = getenv("OSMLCMTEST_NS_PUBKEY", "ssh-rsa test-pub-key t@osm.com")
211 self.my_ns.n2vc = asynctest.Mock(N2VC())
212 self.my_ns.n2vc.GetPublicKey.return_value = getenv("OSMLCM_VCA_PUBKEY", "public_key")
213 # allow several versions of n2vc
214 self.my_ns.n2vc.FormatApplicationName = asynctest.Mock(side_effect=self._n2vc_FormatApplicationName())
215 self.my_ns.n2vc.DeployCharms = asynctest.CoroutineMock(side_effect=self._n2vc_DeployCharms)
216 self.my_ns.n2vc.create_execution_environment = asynctest.CoroutineMock(
217 side_effect=self._n2vc_CreateExecutionEnvironment)
218 self.my_ns.n2vc.install_configuration_sw = asynctest.CoroutineMock(return_value=pub_key)
219 self.my_ns.n2vc.get_ee_ssh_public__key = asynctest.CoroutineMock(return_value=pub_key)
220 self.my_ns.n2vc.exec_primitive = asynctest.CoroutineMock(side_effect=self._return_uuid)
221 self.my_ns.n2vc.GetPrimitiveStatus = asynctest.CoroutineMock(return_value="completed")
222 self.my_ns.n2vc.GetPrimitiveOutput = asynctest.CoroutineMock(return_value={"result": "ok",
223 "pubkey": pub_key})
224 self.my_ns.n2vc.get_public_key = asynctest.CoroutineMock(
225 return_value=getenv("OSMLCM_VCA_PUBKEY", "public_key"))
226
227 # Mock RO
228 if not getenv("OSMLCMTEST_RO_NOMOCK"):
229 # self.my_ns.RO = asynctest.Mock(ROclient.ROClient(self.loop, **ro_config))
230 # TODO first time should be empty list, following should return a dict
231 self.my_ns.RO.get_list = asynctest.CoroutineMock(self.my_ns.RO.get_list, return_value=[])
232 self.my_ns.RO.create = asynctest.CoroutineMock(self.my_ns.RO.create, side_effect=self._ro_create())
233 self.my_ns.RO.show = asynctest.CoroutineMock(self.my_ns.RO.show, side_effect=self._ro_show())
234 self.my_ns.RO.create_action = asynctest.CoroutineMock(self.my_ns.RO.create_action,
235 return_value={"vm-id": {"vim_result": 200,
236 "description": "done"}})
237
238 @asynctest.fail_on(active_handles=True) # all async tasks must be completed
239 async def test_instantiate(self):
240 nsr_id = self.db_content["nsrs"][0]["_id"]
241 nslcmop_id = self.db_content["nslcmops"][0]["_id"]
242 print("Test instantiate started")
243
244 # delete deployed information of database
245 if not getenv("OSMLCMTEST_DB_NOMOCK"):
246 if self.db_content["nsrs"][0]["_admin"].get("deployed"):
247 del self.db_content["nsrs"][0]["_admin"]["deployed"]
248 for db_vnfr in self.db_content["vnfrs"]:
249 db_vnfr.pop("ip_address", None)
250 for db_vdur in db_vnfr["vdur"]:
251 db_vdur.pop("ip_address", None)
252 db_vdur.pop("mac_address", None)
253 if getenv("OSMLCMTEST_RO_VIMID"):
254 self.db_content["vim_accounts"][0]["_admin"]["deployed"]["RO"] = getenv("OSMLCMTEST_RO_VIMID")
255 if getenv("OSMLCMTEST_RO_VIMID"):
256 self.db_content["nsrs"][0]["_admin"]["deployed"]["RO"] = getenv("OSMLCMTEST_RO_VIMID")
257
258 await self.my_ns.instantiate(nsr_id, nslcmop_id)
259
260 print("instantiate_result: {}".format(self._db_get_one("nslcmops", {"_id": nslcmop_id}).get("detailed-status")))
261
262 self.msg.aiowrite.assert_called_once_with("ns", "instantiated",
263 {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
264 "operationState": "COMPLETED"},
265 loop=self.loop)
266 self.lcm_tasks.lock_HA.assert_called_once_with('ns', 'nslcmops', nslcmop_id)
267 if not getenv("OSMLCMTEST_LOGGING_NOMOCK"):
268 self.assertTrue(self.my_ns.logger.debug.called, "Debug method not called")
269 self.my_ns.logger.error.assert_not_called()
270 self.my_ns.logger.exception().assert_not_called()
271
272 if not getenv("OSMLCMTEST_DB_NOMOCK"):
273 self.assertTrue(self.db.set_one.called, "db.set_one not called")
274
275 # TODO add more checks of called methods
276 # TODO add a terminate
277
278 def test_ns_params_2_RO(self):
279 vim = self._db_get_list("vim_accounts")[0]
280 vim_id = vim["_id"]
281 ro_vim_id = vim["_admin"]["deployed"]["RO"]
282 ns_params = {"vimAccountId": vim_id}
283 mgmt_interface = {"cp": "cp"}
284 vdu = [{"id": "vdu_id", "interface": [{"external-connection-point-ref": "cp"}]}]
285 vnfd_dict = {
286 "1": {"vdu": vdu, "mgmt-interface": mgmt_interface},
287 "2": {"vdu": vdu, "mgmt-interface": mgmt_interface, "vnf-configuration": None},
288 "3": {"vdu": vdu, "mgmt-interface": mgmt_interface, "vnf-configuration": {"config-access": None}},
289 "4": {"vdu": vdu, "mgmt-interface": mgmt_interface,
290 "vnf-configuration": {"config-access": {"ssh-access": None}}},
291 "5": {"vdu": vdu, "mgmt-interface": mgmt_interface,
292 "vnf-configuration": {"config-access": {"ssh-access": {"required": True, "default_user": "U"}}}},
293 }
294 nsd = {"constituent-vnfd": []}
295 for k in vnfd_dict.keys():
296 nsd["constituent-vnfd"].append({"vnfd-id-ref": k, "member-vnf-index": k})
297
298 n2vc_key_list = ["key"]
299 ro_ns_params = self.my_ns.ns_params_2_RO(ns_params, nsd, vnfd_dict, n2vc_key_list)
300 ro_params_expected = {'wim_account': None, "datacenter": ro_vim_id,
301 "vnfs": {"5": {"vdus": {"vdu_id": {"mgmt_keys": n2vc_key_list}}}}}
302 self.assertEqual(ro_ns_params, ro_params_expected)
303
304 # Test scale() and related methods
305 @asynctest.fail_on(active_handles=True) # all async tasks must be completed
306 async def test_scale(self):
307 # print("Test scale started")
308
309 # TODO: Add more higher-lever tests here, for example:
310 # scale-out/scale-in operations with success/error result
311
312 # Test scale() with missing 'scaleVnfData', should return operationState = 'FAILED'
313 nsr_id = self.db_content["nsrs"][0]["_id"]
314 nslcmop_id = self.db_content["nslcmops"][0]["_id"]
315 await self.my_ns.scale(nsr_id, nslcmop_id)
316 expected_value = 'FAILED'
317 return_value = self._db_get_one("nslcmops", {"_id": nslcmop_id}).get("operationState")
318 self.assertEqual(return_value, expected_value)
319 # print("scale_result: {}".format(self._db_get_one("nslcmops", {"_id": nslcmop_id}).get("detailed-status")))
320
321 # Test _reintent_or_skip_suboperation()
322 # Expected result:
323 # - if a suboperation's 'operationState' is marked as 'COMPLETED', SUBOPERATION_STATUS_SKIP is expected
324 # - if marked as anything but 'COMPLETED', the suboperation index is expected
325 def test_scale_reintent_or_skip_suboperation(self):
326 # Load an alternative 'nslcmops' YAML for this test
327 self.db_content['nslcmops'] = yaml.load(descriptors.db_nslcmops_scale_text, Loader=yaml.Loader)
328 db_nslcmop = self.db_content['nslcmops'][0]
329 op_index = 2
330 # Test when 'operationState' is 'COMPLETED'
331 db_nslcmop['_admin']['operations'][op_index]['operationState'] = 'COMPLETED'
332 return_value = self.my_ns._reintent_or_skip_suboperation(db_nslcmop, op_index)
333 expected_value = self.my_ns.SUBOPERATION_STATUS_SKIP
334 self.assertEqual(return_value, expected_value)
335 # Test when 'operationState' is not 'COMPLETED'
336 db_nslcmop['_admin']['operations'][op_index]['operationState'] = None
337 return_value = self.my_ns._reintent_or_skip_suboperation(db_nslcmop, op_index)
338 expected_value = op_index
339 self.assertEqual(return_value, expected_value)
340
341 # Test _find_suboperation()
342 # Expected result: index of the found sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if not found
343 def test_scale_find_suboperation(self):
344 # Load an alternative 'nslcmops' YAML for this test
345 self.db_content['nslcmops'] = yaml.load(descriptors.db_nslcmops_scale_text, Loader=yaml.Loader)
346 db_nslcmop = self.db_content['nslcmops'][0]
347 # Find this sub-operation
348 op_index = 2
349 vnf_index = db_nslcmop['_admin']['operations'][op_index]['member_vnf_index']
350 primitive = db_nslcmop['_admin']['operations'][op_index]['primitive']
351 primitive_params = db_nslcmop['_admin']['operations'][op_index]['primitive_params']
352 match = {
353 'member_vnf_index': vnf_index,
354 'primitive': primitive,
355 'primitive_params': primitive_params,
356 }
357 found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
358 self.assertEqual(found_op_index, op_index)
359 # Test with not-matching params
360 match = {
361 'member_vnf_index': vnf_index,
362 'primitive': '',
363 'primitive_params': primitive_params,
364 }
365 found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
366 self.assertEqual(found_op_index, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
367 # Test with None
368 match = None
369 found_op_index = self.my_ns._find_suboperation(db_nslcmop, match)
370 self.assertEqual(found_op_index, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
371
372 # Test _update_suboperation_status()
373 def test_scale_update_suboperation_status(self):
374 db_nslcmop = self.db_content['nslcmops'][0]
375 op_index = 0
376 # Force the initial values to be distinct from the updated ones
377 db_nslcmop['_admin']['operations'][op_index]['operationState'] = 'PROCESSING'
378 db_nslcmop['_admin']['operations'][op_index]['detailed-status'] = 'In progress'
379 # Test to change 'operationState' and 'detailed-status'
380 operationState = 'COMPLETED'
381 detailed_status = 'Done'
382 self.my_ns._update_suboperation_status(
383 db_nslcmop, op_index, operationState, detailed_status)
384 operationState_new = db_nslcmop['_admin']['operations'][op_index]['operationState']
385 detailed_status_new = db_nslcmop['_admin']['operations'][op_index]['detailed-status']
386 # print("DEBUG: operationState_new={}, detailed_status_new={}".format(operationState_new, detailed_status_new))
387 self.assertEqual(operationState, operationState_new)
388 self.assertEqual(detailed_status, detailed_status_new)
389
390 # Test _add_suboperation()
391 def test_scale_add_suboperation(self):
392 db_nslcmop = self.db_content['nslcmops'][0]
393 vnf_index = '1'
394 num_ops_before = len(db_nslcmop.get('_admin', {}).get('operations', [])) - 1
395 vdu_id = None
396 vdu_count_index = None
397 vdu_name = None
398 primitive = 'touch'
399 mapped_primitive_params = {'parameter':
400 [{'data-type': 'STRING',
401 'name': 'filename',
402 'default-value': '<touch_filename2>'}],
403 'name': 'touch'}
404 operationState = 'PROCESSING'
405 detailed_status = 'In progress'
406 operationType = 'PRE-SCALE'
407 # Add a 'pre-scale' suboperation
408 op_index_after = self.my_ns._add_suboperation(db_nslcmop, vnf_index, vdu_id, vdu_count_index,
409 vdu_name, primitive, mapped_primitive_params,
410 operationState, detailed_status, operationType)
411 self.assertEqual(op_index_after, num_ops_before + 1)
412
413 # Delete all suboperations and add the same operation again
414 del db_nslcmop['_admin']['operations']
415 op_index_zero = self.my_ns._add_suboperation(db_nslcmop, vnf_index, vdu_id, vdu_count_index,
416 vdu_name, primitive, mapped_primitive_params,
417 operationState, detailed_status, operationType)
418 self.assertEqual(op_index_zero, 0)
419
420 # Add a 'RO' suboperation
421 RO_nsr_id = '1234567890'
422 RO_scaling_info = [{'type': 'create', 'count': 1, 'member-vnf-index': '1', 'osm_vdu_id': 'dataVM'}]
423 op_index = self.my_ns._add_suboperation(db_nslcmop, vnf_index, vdu_id, vdu_count_index,
424 vdu_name, primitive, mapped_primitive_params,
425 operationState, detailed_status, operationType,
426 RO_nsr_id, RO_scaling_info)
427 db_RO_nsr_id = db_nslcmop['_admin']['operations'][op_index]['RO_nsr_id']
428 self.assertEqual(op_index, 1)
429 self.assertEqual(RO_nsr_id, db_RO_nsr_id)
430
431 # Try to add an invalid suboperation, should return SUBOPERATION_STATUS_NOT_FOUND
432 op_index_invalid = self.my_ns._add_suboperation(None, None, None, None, None,
433 None, None, None,
434 None, None, None)
435 self.assertEqual(op_index_invalid, self.my_ns.SUBOPERATION_STATUS_NOT_FOUND)
436
437 # Test _check_or_add_scale_suboperation() and _check_or_add_scale_suboperation_RO()
438 # check the possible return values:
439 # - SUBOPERATION_STATUS_NEW: This is a new sub-operation
440 # - op_index (non-negative number): This is an existing sub-operation, operationState != 'COMPLETED'
441 # - SUBOPERATION_STATUS_SKIP: This is an existing sub-operation, operationState == 'COMPLETED'
442 def test_scale_check_or_add_scale_suboperation(self):
443 db_nslcmop = self.db_content['nslcmops'][0]
444 operationType = 'PRE-SCALE'
445 vnf_index = '1'
446 primitive = 'touch'
447 primitive_params = {'parameter':
448 [{'data-type': 'STRING',
449 'name': 'filename',
450 'default-value': '<touch_filename2>'}],
451 'name': 'touch'}
452
453 # Delete all sub-operations to be sure this is a new sub-operation
454 del db_nslcmop['_admin']['operations']
455
456 # Add a new sub-operation
457 # For new sub-operations, operationState is set to 'PROCESSING' by default
458 op_index_new = self.my_ns._check_or_add_scale_suboperation(
459 db_nslcmop, vnf_index, primitive, primitive_params, operationType)
460 self.assertEqual(op_index_new, self.my_ns.SUBOPERATION_STATUS_NEW)
461
462 # Use the same parameters again to match the already added sub-operation
463 # which has status 'PROCESSING' (!= 'COMPLETED') by default
464 # The expected return value is a non-negative number
465 op_index_existing = self.my_ns._check_or_add_scale_suboperation(
466 db_nslcmop, vnf_index, primitive, primitive_params, operationType)
467 self.assertTrue(op_index_existing >= 0)
468
469 # Change operationState 'manually' for this sub-operation
470 db_nslcmop['_admin']['operations'][op_index_existing]['operationState'] = 'COMPLETED'
471 # Then use the same parameters again to match the already added sub-operation,
472 # which now has status 'COMPLETED'
473 # The expected return value is SUBOPERATION_STATUS_SKIP
474 op_index_skip = self.my_ns._check_or_add_scale_suboperation(
475 db_nslcmop, vnf_index, primitive, primitive_params, operationType)
476 self.assertEqual(op_index_skip, self.my_ns.SUBOPERATION_STATUS_SKIP)
477
478 # RO sub-operation test:
479 # Repeat tests for the very similar _check_or_add_scale_suboperation_RO(),
480 RO_nsr_id = '1234567890'
481 RO_scaling_info = [{'type': 'create', 'count': 1, 'member-vnf-index': '1', 'osm_vdu_id': 'dataVM'}]
482 op_index_new_RO = self.my_ns._check_or_add_scale_suboperation(
483 db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
484 self.assertEqual(op_index_new_RO, self.my_ns.SUBOPERATION_STATUS_NEW)
485
486 # Use the same parameters again to match the already added RO sub-operation
487 op_index_existing_RO = self.my_ns._check_or_add_scale_suboperation(
488 db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
489 self.assertTrue(op_index_existing_RO >= 0)
490
491 # Change operationState 'manually' for this RO sub-operation
492 db_nslcmop['_admin']['operations'][op_index_existing_RO]['operationState'] = 'COMPLETED'
493 # Then use the same parameters again to match the already added sub-operation,
494 # which now has status 'COMPLETED'
495 # The expected return value is SUBOPERATION_STATUS_SKIP
496 op_index_skip_RO = self.my_ns._check_or_add_scale_suboperation(
497 db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
498 self.assertEqual(op_index_skip_RO, self.my_ns.SUBOPERATION_STATUS_SKIP)
499
500
501 if __name__ == '__main__':
502 asynctest.main()