Don't write information to resmanagement
[vfc/nfvo/lcm.git] / lcm / ns_vnfs / tests / tests.py
1 # Copyright 2016-2017 ZTE Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 import json
15 import uuid
16 import time
17 import mock
18
19 from django.test import TestCase, Client
20 from rest_framework import status
21
22 from lcm.pub.database.models import VLInstModel, NfInstModel, JobModel, NSInstModel, VmInstModel, \
23     OOFDataModel, VNFCInstModel, PortInstModel, CPInstModel, SubscriptionModel
24 from lcm.pub.exceptions import NSLCMException
25 from lcm.pub.utils import restcall
26 from lcm.jobs.enum import JOB_MODEL_STATUS, JOB_TYPE, JOB_ACTION, JOB_PROGRESS
27 from lcm.pub.utils.jobutil import JobUtil
28 from lcm.pub.utils.timeutil import now_time
29 from lcm.pub.utils.values import ignore_case_get
30 from lcm.ns_vnfs.biz.grant_vnf import GrantVnf
31 from lcm.ns_vnfs.biz.heal_vnfs import NFHealService
32 from lcm.ns_vnfs.biz.scale_vnfs import NFManualScaleService
33 from lcm.ns_vnfs.biz.subscribe import SubscriptionDeletion
34 from lcm.ns_vnfs.biz.terminate_nfs import TerminateVnfs
35 from lcm.ns_vnfs.enum import VNF_STATUS, LIFE_CYCLE_OPERATION, RESOURCE_CHANGE_TYPE, VNFC_CHANGE_TYPE, \
36     INST_TYPE, NETWORK_RESOURCE_TYPE
37 from lcm.ns_vnfs.biz.place_vnfs import PlaceVnfs
38 from lcm.pub.msapi import resmgr
39 from lcm.ns_vnfs.tests.test_data import vnfm_info, vim_info, vnf_place_request
40 from lcm.ns_vnfs.tests.test_data import nf_package_info, nsd_model_dict, subscription_response_data
41 from lcm.ns_vnfs.biz.create_vnfs import CreateVnfs
42 from lcm.ns_vnfs.biz import create_vnfs
43 from lcm.ns_vnfs.biz.grant_vnfs import GrantVnfs
44 from lcm.ns_vnfs.biz.update_vnfs import NFOperateService
45 from lcm.ns_vnfs.biz.verify_vnfs import VerifyVnfs
46 from lcm.ns.enum import OWNER_TYPE
47 from lcm.ns_vnfs.biz.handle_notification import HandleVnfLcmOocNotification, HandleVnfIdentifierCreationNotification, \
48     HandleVnfIdentifierDeletionNotification
49 from lcm.ns_vnfs.biz.notify_lcm import NotifyLcm
50
51
52 class TestGetVnfViews(TestCase):
53     def setUp(self):
54         self.client = Client()
55         self.nf_inst_id = str(uuid.uuid4())
56         NfInstModel(nfinstid=self.nf_inst_id, nf_name="vnf1", vnfm_inst_id="1", vnf_id="vnf_id1",
57                     status=VNF_STATUS.ACTIVE, create_time=now_time(), lastuptime=now_time()).save()
58
59     def tearDown(self):
60         NfInstModel.objects.all().delete()
61
62     def test_get_vnf(self):
63         response = self.client.get("/api/nslcm/v1/ns/vnfs/%s" % self.nf_inst_id)
64         self.assertEqual(status.HTTP_200_OK, response.status_code)
65         context = json.loads(response.content)
66         self.assertEqual(self.nf_inst_id, context["vnfInstId"])
67
68
69 class TestTerminateVnfViews(TestCase):
70     def setUp(self):
71         self.client = Client()
72         self.data = {
73             "terminationType": "forceful",
74             "gracefulTerminationTimeout": "600"
75         }
76         self.ns_inst_id = str(uuid.uuid4())
77         self.nf_inst_id = "1"
78         self.vim_id = str(uuid.uuid4())
79         self.job_id = str(uuid.uuid4())
80         self.nf_uuid = "111"
81         self.vnfd_model = {"metadata": {"vnfdId": "1"}}
82         NSInstModel.objects.all().delete()
83         NfInstModel.objects.all().delete()
84         VmInstModel.objects.all().delete()
85         NSInstModel(id=self.ns_inst_id, name="ns_name").save()
86         NfInstModel.objects.create(nfinstid=self.nf_inst_id,
87                                    vnfm_inst_id="1",
88                                    status="active",
89                                    mnfinstid=self.nf_uuid,
90                                    vnfd_model=self.vnfd_model
91                                    )
92         VmInstModel.objects.create(vmid="1",
93                                    vimid='{"cloud_owner": "VCPE", "cloud_regionid": "RegionOne"}',
94                                    instid=self.nf_inst_id
95                                    )
96         SubscriptionModel(vnf_instance_filter=self.nf_inst_id, callback_uri="", links="").save()
97
98     def tearDown(self):
99         NSInstModel.objects.all().delete()
100         NfInstModel.objects.all().delete()
101         VmInstModel.objects.all().delete()
102         SubscriptionModel.objects.all().delete()
103
104     @mock.patch.object(TerminateVnfs, "run")
105     def test_terminate_vnf_url(self, mock_run):
106         req_data = {
107             "terminationType": "forceful",
108             "gracefulTerminationTimeout": "600"}
109
110         response = self.client.post("/api/nslcm/v1/ns/terminatevnf/%s" % self.nf_inst_id, data=req_data)
111         self.assertEqual(status.HTTP_202_ACCEPTED, response.status_code)
112
113     @mock.patch.object(time, "sleep")
114     @mock.patch.object(restcall, "call_req")
115     def test_terminate_vnf(self, mock_call_req, mock_sleep):
116         job_id = JobUtil.create_job(JOB_TYPE.VNF, JOB_ACTION.TERMINATE, self.nf_inst_id)
117         job_info = {
118             "jobId": job_id,
119             "responsedescriptor": {"status": JOB_MODEL_STATUS.FINISHED}
120         }
121         mock_vals = {
122             "/external-system/esr-vnfm-list/esr-vnfm/1?depth=all":
123                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
124             "/api/ztevnfmdriver/v1/1/vnfs/111/terminate":
125                 [0, json.JSONEncoder().encode({"jobId": job_id}), "200"],
126             "/api/ztevnfmdriver/v1/1/jobs/" + job_id + "?responseId=0":
127                 [0, json.JSONEncoder().encode(job_info), "200"],
128             "/api/resmgr/v1/vnf/1":
129                 [0, json.JSONEncoder().encode({"jobId": job_id}), "200"],
130             "api/gvnfmdriver/v1/1/subscriptions/":
131                 [0, json.JSONEncoder().encode({}), "200"]
132         }
133
134         def side_effect(*args):
135             return mock_vals[args[4]]
136         mock_call_req.side_effect = side_effect
137         TerminateVnfs(self.data, self.nf_inst_id, job_id).run()
138         nfinst = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
139         if nfinst:
140             self.assertEqual(1, 0)
141         else:
142             self.assertEqual(1, 1)
143         self.assertEqual(JobModel.objects.get(jobid=job_id).progress, 100)
144
145     @mock.patch.object(time, "sleep")
146     @mock.patch.object(restcall, "call_req")
147     @mock.patch.object(SubscriptionDeletion, "send_subscription_deletion_request")
148     def test_terminate_vnf_when_no_vnf_uuid(self, mock_send_subscription_deletion_request, mock_call_req, mock_sleep):
149         nf_inst_id = "test_terminate_vnf_when_no_vnf_uuid"
150         NSInstModel(id=nf_inst_id, name="ns_name_2").save()
151         NfInstModel.objects.create(nfinstid=nf_inst_id,
152                                    vnfm_inst_id="2",
153                                    status="active",
154                                    vnfd_model=self.vnfd_model
155                                    )
156         VmInstModel.objects.create(vmid="2",
157                                    vimid='{"cloud_owner": "VCPE", "cloud_regionid": "RegionOne"}',
158                                    instid=nf_inst_id
159                                    )
160         job_id = JobUtil.create_job(JOB_TYPE.VNF, JOB_ACTION.TERMINATE, nf_inst_id)
161         job_info = {
162             "jobId": job_id,
163             "responsedescriptor": {"status": JOB_MODEL_STATUS.FINISHED}
164         }
165         mock_vals = {
166             "/external-system/esr-vnfm-list/esr-vnfm/2?depth=all":
167                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
168             "/api/ztevnfmdriver/v1/2/vnfs/None/terminate":
169                 [0, json.JSONEncoder().encode({"jobId": job_id}), "200"],
170             "/api/ztevnfmdriver/v1/2/jobs/" + job_id + "?responseId=0":
171                 [0, json.JSONEncoder().encode(job_info), "200"],
172             "/api/resmgr/v1/vnf/%s" % nf_inst_id:
173                 [0, json.JSONEncoder().encode({"jobId": job_id}), "200"]
174         }
175
176         def side_effect(*args):
177             return mock_vals[args[4]]
178
179         mock_call_req.side_effect = side_effect
180         TerminateVnfs(self.data, nf_inst_id, job_id).run()
181         nfinst = NfInstModel.objects.filter(nfinstid=nf_inst_id)
182         if nfinst:
183             self.assertEqual(1, 0)
184         else:
185             self.assertEqual(1, 1)
186         self.assertEqual(JobModel.objects.get(jobid=job_id).progress, 100)
187
188     @mock.patch.object(time, "sleep")
189     @mock.patch.object(restcall, "call_req")
190     @mock.patch.object(SubscriptionDeletion, "send_subscription_deletion_request")
191     def test_terminate_vnf_when_nf_not_exists(self, mock_send_subscription_deletion_request, mock_call_req, mock_sleep):
192         job_id = JobUtil.create_job(JOB_TYPE.VNF, JOB_ACTION.TERMINATE, self.nf_inst_id)
193         TerminateVnfs(self.data, "nf_not_exists", job_id).run()
194         nfinst = NfInstModel.objects.filter(nfinstid="nf_not_exists")
195         if nfinst:
196             self.assertEqual(1, 0)
197         else:
198             self.assertEqual(1, 1)
199         self.assertEqual(JobModel.objects.get(jobid=job_id).progress, 255)
200
201     def test_terminate_vnf_when_vnf_is_dealing(self):
202         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.TERMINATING)
203         job_id = JobUtil.create_job(JOB_TYPE.VNF, JOB_ACTION.TERMINATE, self.nf_inst_id)
204         TerminateVnfs(self.data, self.nf_inst_id, job_id).run()
205         self.assertEqual(NfInstModel.objects.get(nfinstid=self.nf_inst_id).status, VNF_STATUS.FAILED)
206         self.assertEqual(JobModel.objects.get(jobid=job_id).progress, 255)
207
208     @mock.patch.object(time, "sleep")
209     @mock.patch.object(restcall, "call_req")
210     @mock.patch.object(SubscriptionDeletion, "send_subscription_deletion_request")
211     def test_terminate_vnf_when_job_error(self, mock_send_subscription_deletion_request, mock_call_req, mock_sleep):
212         job_id = JobUtil.create_job(JOB_TYPE.VNF, JOB_ACTION.TERMINATE, self.nf_inst_id)
213         job_info = {
214             "jobId": job_id,
215             "responsedescriptor": {"status": JOB_MODEL_STATUS.ERROR}
216         }
217         mock_vals = {
218             "/external-system/esr-vnfm-list/esr-vnfm/1?depth=all":
219                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
220             "/api/ztevnfmdriver/v1/1/vnfs/111/terminate":
221                 [0, json.JSONEncoder().encode({"jobId": job_id}), "200"],
222             "/api/ztevnfmdriver/v1/1/jobs/" + job_id + "?responseId=0":
223                 [0, json.JSONEncoder().encode(job_info), "200"]
224         }
225
226         def side_effect(*args):
227             return mock_vals[args[4]]
228
229         mock_call_req.side_effect = side_effect
230         TerminateVnfs(self.data, self.nf_inst_id, job_id).run()
231         self.assertEqual(NfInstModel.objects.get(nfinstid=self.nf_inst_id).status, VNF_STATUS.FAILED)
232         self.assertEqual(JobModel.objects.get(jobid=job_id).progress, 255)
233
234
235 class TestScaleVnfViews(TestCase):
236     def setUp(self):
237         self.client = Client()
238         self.nf_inst_id = str(uuid.uuid4())
239         self.url = "/api/nslcm/v1/ns/ns_vnfs/%s/scaling" % self.nf_inst_id
240         self.data = {
241             "scaleVnfData":
242                 {
243                     "type": "SCALE_OUT",
244                     "aspectId": "demo_aspect1",
245                     "numberOfSteps": 1,
246                     "additionalParam": {}
247                 }
248         }
249         NfInstModel.objects.create(nfinstid=self.nf_inst_id, vnfm_inst_id="vnfm_inst_id_001",
250                                    mnfinstid="m_nf_inst_id_001")
251
252     def tearDown(self):
253         NfInstModel.objects.all().delete()
254
255     # def test_scale_vnf_view(self):
256     #     response = self.client.post(self.url, self.data)
257     #     self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
258
259     @mock.patch.object(time, "sleep")
260     @mock.patch.object(restcall, "call_req")
261     def test_scale_vnf_success(self, mock_call_req, mock_sleep):
262         scale_service = NFManualScaleService(self.nf_inst_id, self.data)
263         job_info = {
264             "jobId": scale_service.job_id,
265             "responsedescriptor": {"status": JOB_MODEL_STATUS.FINISHED}
266         }
267         mock_vals = {
268             "/external-system/esr-vnfm-list/esr-vnfm/vnfm_inst_id_001?depth=all":
269                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
270             "/api/ztevnfmdriver/v1/vnfm_inst_id_001/vnfs/m_nf_inst_id_001/scale":
271                 [0, json.JSONEncoder().encode({"jobId": scale_service.job_id}), "200"],
272             "/api/ztevnfmdriver/v1/vnfm_inst_id_001/jobs/" + scale_service.job_id + "?responseId=0":
273                 [0, json.JSONEncoder().encode(job_info), "200"]
274         }
275
276         def side_effect(*args):
277             return mock_vals[args[4]]
278         mock_call_req.side_effect = side_effect
279         scale_service.run()
280         nsIns = NfInstModel.objects.get(nfinstid=self.nf_inst_id)
281         self.assertEqual(nsIns.status, VNF_STATUS.ACTIVE)
282
283         jobs = JobModel.objects.get(jobid=scale_service.job_id)
284         self.assertEqual(JOB_PROGRESS.FINISHED, jobs.progress)
285
286     @mock.patch.object(time, "sleep")
287     @mock.patch.object(restcall, "call_req")
288     def test_scale_vnf_when_job_fail(self, mock_call_req, mock_sleep):
289         scale_service = NFManualScaleService(self.nf_inst_id, self.data)
290         job_info = {
291             "jobId": scale_service.job_id,
292             "responsedescriptor": {"status": JOB_MODEL_STATUS.ERROR}
293         }
294         mock_vals = {
295             "/external-system/esr-vnfm-list/esr-vnfm/vnfm_inst_id_001?depth=all":
296                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
297             "/api/ztevnfmdriver/v1/vnfm_inst_id_001/vnfs/m_nf_inst_id_001/scale":
298                 [0, json.JSONEncoder().encode({"jobId": scale_service.job_id}), "200"],
299             "/api/ztevnfmdriver/v1/vnfm_inst_id_001/jobs/" + scale_service.job_id + "?responseId=0":
300                 [0, json.JSONEncoder().encode(job_info), "200"]
301         }
302
303         def side_effect(*args):
304             return mock_vals[args[4]]
305
306         mock_call_req.side_effect = side_effect
307         scale_service.run()
308         nsIns = NfInstModel.objects.get(nfinstid=self.nf_inst_id)
309         self.assertEqual(nsIns.status, VNF_STATUS.ACTIVE)
310         jobs = JobModel.objects.get(jobid=scale_service.job_id)
311         self.assertEqual(JOB_PROGRESS.ERROR, jobs.progress)
312
313     def test_scale_vnf_when_exception(self):
314         req_data = {
315             "scaleVnfData": [
316                 {
317                     "type": "SCALE_OUT",
318                     "aspectId": "demo_aspect1",
319                     "numberOfSteps": 1,
320                 },
321                 {
322                     "type": "SCALE_OUT",
323                     "aspectId": "demo_aspect2",
324                     "numberOfSteps": 1,
325                 }
326             ]
327         }
328         scale_service = NFManualScaleService(self.nf_inst_id, req_data)
329         scale_service.run()
330         nsIns = NfInstModel.objects.get(nfinstid=self.nf_inst_id)
331         self.assertEqual(nsIns.status, VNF_STATUS.ACTIVE)
332
333         jobs = JobModel.objects.get(jobid=scale_service.job_id)
334         self.assertEqual(JOB_PROGRESS.ERROR, jobs.progress)
335
336     def test_scale_vnf_when_nf_instance_does_not_exist(self):
337         req_data = {
338             "scaleVnfData":
339                 {
340                     "type": "SCALE_OUT",
341                     "aspectId": "demo_aspect1",
342                     "numberOfSteps": 1,
343                 }
344         }
345         scale_service = NFManualScaleService("nf_instance_does_not_exist", req_data)
346         scale_service.run()
347
348         jobs = JobModel.objects.get(jobid=scale_service.job_id)
349         self.assertEqual(JOB_PROGRESS.ERROR, jobs.progress)
350
351     def test_scale_vnf_when_scale_vnf_data_does_not_exist(self):
352         req_data = {
353             "scaleVnfData": {}
354         }
355         scale_service = NFManualScaleService(self.nf_inst_id, req_data)
356         scale_service.run()
357         nsIns = NfInstModel.objects.get(nfinstid=self.nf_inst_id)
358         self.assertEqual(nsIns.status, VNF_STATUS.ACTIVE)
359
360         jobs = JobModel.objects.get(jobid=scale_service.job_id)
361         self.assertEqual(JOB_PROGRESS.ERROR, jobs.progress)
362
363
364 class TestHealVnfViews(TestCase):
365     def setUp(self):
366         self.client = Client()
367         self.ns_inst_id = str(uuid.uuid4())
368         self.nf_inst_id = str(uuid.uuid4())
369         self.nf_uuid = "111"
370         self.data = {
371             "action": "vmReset",
372             "affectedvm": {
373                 "vmid": "1",
374                 "vduid": "1",
375                 "vmname": "name",
376             },
377             "additionalParams": {
378                 "actionvminfo": {
379                     "vmid": "vm_id_001",
380                 }
381             }
382         }
383         NSInstModel(id=self.ns_inst_id, name="ns_name").save()
384         NfInstModel.objects.create(nfinstid=self.nf_inst_id, status=VNF_STATUS.NULL, vnfm_inst_id="vnfm_inst_id_001",
385                                    mnfinstid="m_nf_inst_id_001")
386         NfInstModel.objects.create(nfinstid="non_vud_id", status=VNF_STATUS.NULL, vnfm_inst_id="vnfm_inst_id_001",
387                                    mnfinstid="m_nf_inst_id_001")
388         VNFCInstModel.objects.create(nfinstid=self.nf_inst_id, vmid="vm_id_001", vduid="vdu_id_001")
389         VmInstModel.objects.create(resouceid="vm_id_001", vmname="vm_name_001")
390
391     def tearDown(self):
392         NSInstModel.objects.all().delete()
393         NfInstModel.objects.all().delete()
394
395     @mock.patch.object(time, "sleep")
396     @mock.patch.object(restcall, "call_req")
397     def test_heal_vnf_success(self, mock_call_req, mock_sleep):
398         heal_service = NFHealService(self.nf_inst_id, self.data)
399         mock_vals = {
400             "/test/bins/1?timeout=15000":
401                 [0, json.JSONEncoder().encode(['{"powering-off": "", "instance_id": "vm_id_001", '
402                                                '"display_name": ""}']), "200"],
403             "/external-system/esr-vnfm-list/esr-vnfm/vnfm_inst_id_001?depth=all":
404                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
405             "/api/ztevnfmdriver/v1/vnfm_inst_id_001/vnfs/m_nf_inst_id_001/heal":
406                 [0, json.JSONEncoder().encode({"jobId": heal_service.job_id}), "200"],
407             "/api/ztevnfmdriver/v1/vnfm_inst_id_001/jobs/" + heal_service.job_id + "?responseId=0":
408                 [0, json.JSONEncoder().encode({
409                     "jobId": heal_service.job_id,
410                     "responsedescriptor": {
411                         "status": JOB_MODEL_STATUS.FINISHED,
412                         "responsehistorylist": [{
413                             "progress": "0",
414                             "status": JOB_MODEL_STATUS.PROCESSING,
415                             "responseid": "2",
416                             "statusdescription": "creating",
417                             "errorcode": "0"
418                         }]
419                     }
420                 }), "200"]
421         }
422
423         def side_effect(*args):
424             return mock_vals[args[4]]
425
426         mock_call_req.side_effect = side_effect
427         heal_service.run()
428         self.assertEqual(NfInstModel.objects.get(nfinstid=self.nf_inst_id).status, VNF_STATUS.ACTIVE)
429         jobs = JobModel.objects.get(jobid=heal_service.job_id)
430         self.assertEqual(JOB_PROGRESS.FINISHED, jobs.progress)
431
432     def test_heal_vnf_when_non_existing_vnf(self, ):
433         heal_service = NFHealService("on_existing_vnf", self.data)
434         heal_service.run()
435         self.assertEqual(NfInstModel.objects.get(nfinstid=self.nf_inst_id).status, VNF_STATUS.NULL)
436         jobs = JobModel.objects.get(jobid=heal_service.job_id)
437         self.assertEqual(JOB_PROGRESS.ERROR, jobs.progress)
438
439     def test_heal_vnf_when_additional_params_non_exist(self):
440         data = {"action": "vmReset"}
441         heal_service = NFHealService(self.nf_inst_id, data)
442         heal_service.run()
443         self.assertEqual(NfInstModel.objects.get(nfinstid=self.nf_inst_id).status, VNF_STATUS.NULL)
444         jobs = JobModel.objects.get(jobid=heal_service.job_id)
445         self.assertEqual(JOB_PROGRESS.ERROR, jobs.progress)
446
447     def test_heal_vnf_when_non_vud_id(self, ):
448         heal_service = NFHealService("non_vud_id", self.data)
449         heal_service.run()
450         self.assertEqual(NfInstModel.objects.get(nfinstid="non_vud_id").status, VNF_STATUS.NULL)
451         jobs = JobModel.objects.get(jobid=heal_service.job_id)
452         self.assertEqual(JOB_PROGRESS.ERROR, jobs.progress)
453
454     @mock.patch.object(restcall, "call_req")
455     def test_heal_vnf_when_no_vnfm_job_id(self, mock_call_req):
456         heal_service = NFHealService(self.nf_inst_id, self.data)
457         mock_vals = {
458             "/test/bins/1?timeout=15000":
459                 [0, json.JSONEncoder().encode(['{"powering-off": "", "instance_id": "vm_id_001", '
460                                                '"display_name": ""}']), "200"],
461             "/external-system/esr-vnfm-list/esr-vnfm/vnfm_inst_id_001?depth=all":
462                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
463             "/api/ztevnfmdriver/v1/vnfm_inst_id_001/vnfs/m_nf_inst_id_001/heal":
464                 [0, json.JSONEncoder().encode({}), "200"]
465         }
466
467         def side_effect(*args):
468             return mock_vals[args[4]]
469
470         mock_call_req.side_effect = side_effect
471         heal_service.run()
472         self.assertEqual(NfInstModel.objects.get(nfinstid=self.nf_inst_id).status, VNF_STATUS.ACTIVE)
473         jobs = JobModel.objects.get(jobid=heal_service.job_id)
474         self.assertEqual(JOB_PROGRESS.FINISHED, jobs.progress)
475
476     @mock.patch.object(time, "sleep")
477     @mock.patch.object(restcall, "call_req")
478     def test_heal_vnf_when_job_bot_finish(self, mock_call_req, mock_sleep):
479         heal_service = NFHealService(self.nf_inst_id, self.data)
480         mock_vals = {
481             "/test/bins/1?timeout=15000":
482                 [0, json.JSONEncoder().encode(['{"powering-off": "", "instance_id": "vm_id_001", '
483                                                '"display_name": ""}']), "200"],
484             "/external-system/esr-vnfm-list/esr-vnfm/vnfm_inst_id_001?depth=all":
485                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
486             "/api/ztevnfmdriver/v1/vnfm_inst_id_001/vnfs/m_nf_inst_id_001/heal":
487                 [0, json.JSONEncoder().encode({"jobId": heal_service.job_id}), "200"],
488             "/api/ztevnfmdriver/v1/vnfm_inst_id_001/jobs/" + heal_service.job_id + "?responseId=0":
489                 [0, json.JSONEncoder().encode({
490                     "jobId": heal_service.job_id,
491                     "responsedescriptor": {
492                         "status": JOB_MODEL_STATUS.ERROR,
493                         "responsehistorylist": [{
494                             "progress": "0",
495                             "status": JOB_MODEL_STATUS.PROCESSING,
496                             "responseid": "2",
497                             "statusdescription": "creating",
498                             "errorcode": "0"
499                         }]
500                     }
501                 }), "200"]
502         }
503
504         def side_effect(*args):
505             return mock_vals[args[4]]
506
507         mock_call_req.side_effect = side_effect
508         heal_service.run()
509         self.assertEqual(NfInstModel.objects.get(nfinstid=self.nf_inst_id).status, VNF_STATUS.HEALING)
510         jobs = JobModel.objects.get(jobid=heal_service.job_id)
511         self.assertEqual(JOB_PROGRESS.ERROR, jobs.progress)
512
513
514 class TestGetVnfmInfoViews(TestCase):
515     def setUp(self):
516         self.client = Client()
517         self.vnfm_id = str(uuid.uuid4())
518
519     def tearDown(self):
520         pass
521
522     @mock.patch.object(restcall, "call_req")
523     def test_get_vnfm_info(self, mock_call_req):
524         vnfm_info_aai = {
525             "vnfm-id": "example-vnfm-id-val-62576",
526             "vim-id": "example-vim-id-val-35114",
527             "certificate-url": "example-certificate-url-val-90242",
528             "esr-system-info-list": {
529                 "esr-system-info": [
530                     {
531                         "esr-system-info-id": "example-esr-system-info-id-val-78484",
532                         "system-name": "example-system-name-val-23790",
533                         "type": "example-type-val-52596",
534                         "vendor": "example-vendor-val-47399",
535                         "version": "example-version-val-42051",
536                         "service-url": "example-service-url-val-10731",
537                         "user-name": "example-user-name-val-65946",
538                         "password": "example-password-val-22505",
539                         "system-type": "example-system-type-val-27221",
540                         "protocal": "example-protocal-val-54632",
541                         "ssl-cacert": "example-ssl-cacert-val-45965",
542                         "ssl-insecure": True,
543                         "ip-address": "example-ip-address-val-19212",
544                         "port": "example-port-val-57641",
545                         "cloud-domain": "example-cloud-domain-val-26296",
546                         "default-tenant": "example-default-tenant-val-87724"
547                     }
548                 ]
549             }
550         }
551         r1 = [0, json.JSONEncoder().encode(vnfm_info_aai), "200"]
552         mock_call_req.side_effect = [r1]
553         esr_system_info = ignore_case_get(ignore_case_get(vnfm_info_aai, "esr-system-info-list"), "esr-system-info")
554         expect_data = {
555             "vnfmId": vnfm_info_aai["vnfm-id"],
556             "name": vnfm_info_aai["vnfm-id"],
557             "type": ignore_case_get(esr_system_info[0], "type"),
558             "vimId": vnfm_info_aai["vim-id"],
559             "vendor": ignore_case_get(esr_system_info[0], "vendor"),
560             "version": ignore_case_get(esr_system_info[0], "version"),
561             "description": "vnfm",
562             "certificateUrl": vnfm_info_aai["certificate-url"],
563             "url": ignore_case_get(esr_system_info[0], "service-url"),
564             "userName": ignore_case_get(esr_system_info[0], "user-name"),
565             "password": ignore_case_get(esr_system_info[0], "password"),
566             "createTime": ""
567         }
568
569         response = self.client.get("/api/nslcm/v1/vnfms/%s" % self.vnfm_id)
570         self.assertEqual(status.HTTP_200_OK, response.status_code, response.content)
571         context = json.loads(response.content)
572         self.assertEqual(expect_data, context)
573
574
575 class TestGetVimInfoViews(TestCase):
576     def setUp(self):
577         self.client = Client()
578         self.vim_id = {"cloud_owner": "VCPE", "cloud_regionid": "RegionOne"}
579
580     def tearDown(self):
581         pass
582
583     @mock.patch.object(restcall, "call_req")
584     def test_get_vim_info(self, mock_call_req):
585         r1 = [0, json.JSONEncoder().encode(vim_info), "200"]
586         mock_call_req.side_effect = [r1]
587         esr_system_info = ignore_case_get(ignore_case_get(vim_info, "esr-system-info-list"), "esr-system-info")
588         expect_data = {
589             "vimId": self.vim_id,
590             "name": self.vim_id,
591             "url": ignore_case_get(esr_system_info[0], "service-url"),
592             "userName": ignore_case_get(esr_system_info[0], "user-name"),
593             "password": ignore_case_get(esr_system_info[0], "password"),
594             # "tenant": ignore_case_get(tenants[0], "tenant-id"),
595             "tenant": ignore_case_get(esr_system_info[0], "default-tenant"),
596             "vendor": ignore_case_get(esr_system_info[0], "vendor"),
597             "version": ignore_case_get(esr_system_info[0], "version"),
598             "description": "vim",
599             "domain": "",
600             "type": ignore_case_get(esr_system_info[0], "type"),
601             "createTime": ""
602         }
603
604         # response = self.client.get("/api/nslcm/v1/vims/%s" % self.vim_id)
605         response = self.client.get("/api/nslcm/v1/vims/%s/%s" % (self.vim_id["cloud_owner"], self.vim_id["cloud_regionid"]))
606         self.assertEqual(status.HTTP_200_OK, response.status_code)
607         context = json.loads(response.content)
608         self.assertEqual(expect_data["url"], context["url"])
609
610
611 class TestPlaceVnfViews(TestCase):
612     def setUp(self):
613         self.vnf_inst_id = "1234"
614         self.vnf_id = "vG"
615         self.client = Client()
616         self.url = "/api/nslcm/v1/ns/placevnf"
617         self.data = vnf_place_request
618         OOFDataModel.objects.all().delete()
619         OOFDataModel.objects.create(
620             request_id="1234",
621             transaction_id="1234",
622             request_status="init",
623             request_module_name=self.vnf_id,
624             service_resource_id=self.vnf_inst_id,
625             vim_id="",
626             cloud_owner="",
627             cloud_region_id="",
628             vdu_info="",
629         )
630
631     def tearDown(self):
632         OOFDataModel.objects.all().delete()
633
634     @mock.patch.object(restcall, "call_req")
635     def test_place_vnf(self, mock_call_req):
636         vdu_info_json = [{
637             "vduName": "vG_0",
638             "flavorName": "HPA.flavor.1",
639             "flavorId": "12345",
640             "directive": []
641         }]
642         # response = self.client.post(self.url, data=self.data)
643         PlaceVnfs(vnf_place_request).extract()
644         db_info = OOFDataModel.objects.filter(request_id=vnf_place_request.get("requestId"), transaction_id=vnf_place_request.get("transactionId"))
645         self.assertEqual(db_info[0].request_status, "completed")
646         self.assertEqual(db_info[0].vim_id, "CloudOwner1_DLLSTX1A")
647         self.assertEqual(db_info[0].cloud_owner, "CloudOwner1")
648         self.assertEqual(db_info[0].cloud_region_id, "DLLSTX1A")
649         self.assertEqual(db_info[0].vdu_info, json.dumps(vdu_info_json))
650
651     def test_place_vnf_with_invalid_response(self):
652         resp = {
653             "requestId": "1234",
654             "transactionId": "1234",
655             "statusMessage": "xx",
656             "requestStatus": "pending",
657             "solutions": {
658                 "placementSolutions": [
659                     [
660                         {
661                             "resourceModuleName": self.vnf_id,
662                             "serviceResourceId": self.vnf_inst_id,
663                             "solution": {
664                                 "identifierType": "serviceInstanceId",
665                                 "identifiers": [
666                                     "xx"
667                                 ],
668                                 "cloudOwner": "CloudOwner1 "
669                             },
670                             "assignmentInfo": []
671                         }
672                     ]
673                 ],
674                 "licenseSolutions": [
675                     {
676                         "resourceModuleName": "string",
677                         "serviceResourceId": "string",
678                         "entitlementPoolUUID": [
679                             "string"
680                         ],
681                         "licenseKeyGroupUUID": [
682                             "string"
683                         ],
684                         "entitlementPoolInvariantUUID": [
685                             "string"
686                         ],
687                         "licenseKeyGroupInvariantUUID": [
688                             "string"
689                         ]
690                     }
691                 ]
692             }
693         }
694         PlaceVnfs(resp).extract()
695         db_info = OOFDataModel.objects.filter(request_id=resp.get("requestId"), transaction_id=resp.get("transactionId"))
696         self.assertEqual(db_info[0].request_status, "pending")
697         self.assertEqual(db_info[0].vim_id, "none")
698         self.assertEqual(db_info[0].cloud_owner, "none")
699         self.assertEqual(db_info[0].cloud_region_id, "none")
700         self.assertEqual(db_info[0].vdu_info, "none")
701
702     def test_place_vnf_with_no_assignment_info(self):
703         resp = {
704             "requestId": "1234",
705             "transactionId": "1234",
706             "statusMessage": "xx",
707             "requestStatus": "completed",
708             "solutions": {
709                 "placementSolutions": [
710                     [
711                         {
712                             "resourceModuleName": self.vnf_id,
713                             "serviceResourceId": self.vnf_inst_id,
714                             "solution": {
715                                 "identifierType": "serviceInstanceId",
716                                 "identifiers": [
717                                     "xx"
718                                 ],
719                                 "cloudOwner": "CloudOwner1 "
720                             }
721                         }
722                     ]
723                 ],
724                 "licenseSolutions": [
725                     {
726                         "resourceModuleName": "string",
727                         "serviceResourceId": "string",
728                         "entitlementPoolUUID": [
729                             "string"
730                         ],
731                         "licenseKeyGroupUUID": [
732                             "string"
733                         ],
734                         "entitlementPoolInvariantUUID": [
735                             "string"
736                         ],
737                         "licenseKeyGroupInvariantUUID": [
738                             "string"
739                         ]
740                     }
741                 ]
742             }
743         }
744         PlaceVnfs(resp).extract()
745         db_info = OOFDataModel.objects.filter(request_id=resp.get("requestId"), transaction_id=resp.get("transactionId"))
746         self.assertEqual(db_info[0].request_status, "completed")
747         self.assertEqual(db_info[0].vim_id, "none")
748         self.assertEqual(db_info[0].cloud_owner, "none")
749         self.assertEqual(db_info[0].cloud_region_id, "none")
750         self.assertEqual(db_info[0].vdu_info, "none")
751
752     def test_place_vnf_no_directives(self):
753         resp = {
754             "requestId": "1234",
755             "transactionId": "1234",
756             "statusMessage": "xx",
757             "requestStatus": "completed",
758             "solutions": {
759                 "placementSolutions": [
760                     [
761                         {
762                             "resourceModuleName": self.vnf_id,
763                             "serviceResourceId": self.vnf_inst_id,
764                             "solution": {
765                                 "identifierType": "serviceInstanceId",
766                                 "identifiers": [
767                                     "xx"
768                                 ],
769                                 "cloudOwner": "CloudOwner1 "
770                             },
771                             "assignmentInfo": [
772                                 {"key": "locationId",
773                                  "value": "DLLSTX1A"
774                                  }
775                             ]
776                         }
777                     ]
778                 ],
779                 "licenseSoutions": [
780                     {
781                         "resourceModuleName": "string",
782                         "serviceResourceId": "string",
783                         "entitlementPoolUUID": [
784                             "string"
785                         ],
786                         "licenseKeyGroupUUID": [
787                             "string"
788                         ],
789                         "entitlementPoolInvariantUUID": [
790                             "string"
791                         ],
792                         "licenseKeyGroupInvariantUUID": [
793                             "string"
794                         ]
795                     }
796                 ]
797             }
798         }
799         PlaceVnfs(resp).extract()
800         db_info = OOFDataModel.objects.filter(request_id=resp.get("requestId"), transaction_id=resp.get("transactionId"))
801         self.assertEqual(db_info[0].request_status, "completed")
802         self.assertEqual(db_info[0].vim_id, "none")
803         self.assertEqual(db_info[0].cloud_owner, "none")
804         self.assertEqual(db_info[0].cloud_region_id, "none")
805         self.assertEqual(db_info[0].vdu_info, "none")
806
807     def test_place_vnf_with_no_solution(self):
808         resp = {
809             "requestId": "1234",
810             "transactionId": "1234",
811             "statusMessage": "xx",
812             "requestStatus": "completed",
813             "solutions": {
814                 "placementSolutions": [],
815                 "licenseSoutions": []
816             }
817         }
818         PlaceVnfs(resp).extract()
819         db_info = OOFDataModel.objects.filter(request_id=resp.get("requestId"), transaction_id=resp.get("transactionId"))
820         self.assertEqual(db_info[0].request_status, "completed")
821         self.assertEqual(db_info[0].vim_id, "none")
822         self.assertEqual(db_info[0].cloud_owner, "none")
823         self.assertEqual(db_info[0].cloud_region_id, "none")
824         self.assertEqual(db_info[0].vdu_info, "none")
825
826
827 class TestGrantVnfsViews(TestCase):
828     def setUp(self):
829         self.vnf_inst_id = str(uuid.uuid4())
830         self.data = {
831             "vnfInstanceId": self.vnf_inst_id,
832             "lifecycleOperation": LIFE_CYCLE_OPERATION.INSTANTIATE,
833             "addResource": [{"type": RESOURCE_CHANGE_TYPE.VDU, "vdu": "vdu_grant_vnf_add_resources"}],
834             "additionalParam": {
835                 "vnfmid": "vnfm_inst_id_001",
836                 "vimid": '{"cloud_owner": "VCPE", "cloud_regionid": "RegionOne"}'
837             }
838         }
839         self.client = Client()
840         self.url = "/api/nslcm/v1/ns/grantvnf"
841         NfInstModel(mnfinstid=self.vnf_inst_id, nfinstid="vnf_inst_id_001", package_id="package_id_001",
842                     vnfm_inst_id="vnfm_inst_id_001").save()
843
844     def tearDown(self):
845         OOFDataModel.objects.all().delete()
846         NfInstModel.objects.all().delete()
847
848     # @mock.patch.object(restcall, "call_req")
849     # def test_nf_grant_view(self, mock_call_req):
850     #     mock_vals = {
851     #         "/api/catalog/v1/vnfpackages/package_id_001":
852     #             [0, json.JSONEncoder().encode(nf_package_info), "200"],
853     #         "/api/resmgr/v1/resource/grant":
854     #             [1, json.JSONEncoder().encode({}), "200"],
855     #         "/cloud-infrastructure/cloud-regions/cloud-region/VCPE/RegionOne?depth=all":
856     #             [0, json.JSONEncoder().encode(vim_info), "201"],
857     #     }
858     #
859     #     def side_effect(*args):
860     #         return mock_vals[args[4]]
861     #
862     #     mock_call_req.side_effect = side_effect
863     #     data = {
864     #         "vnfInstanceId": self.vnf_inst_id,
865     #         "lifecycleOperation": LIFE_CYCLE_OPERATION.INSTANTIATE
866     #     }
867     #     response = self.client.post(self.url, data=data)
868     #     self.assertEqual(response.status_code, status.HTTP_201_CREATED)
869
870     @mock.patch.object(restcall, "call_req")
871     def test_nf_grant_view_when_add_resource(self, mock_call_req):
872         mock_vals = {
873             "/api/catalog/v1/vnfpackages/package_id_001":
874                 [0, json.JSONEncoder().encode(nf_package_info), "200"],
875             "/api/resmgr/v1/resource/grant":
876                 [1, json.JSONEncoder().encode({}), "200"],
877             "/cloud-infrastructure/cloud-regions/cloud-region/VCPE/RegionOne?depth=all":
878                 [0, json.JSONEncoder().encode(vim_info), "201"],
879         }
880
881         def side_effect(*args):
882             return mock_vals[args[4]]
883         mock_call_req.side_effect = side_effect
884         resp = GrantVnfs(json.dumps(self.data), "").send_grant_vnf_to_resMgr()
885         return_success = {"vim": {"accessInfo": {"tenant": "admin"},
886                                   "vimId": "example-cloud-owner-val-97336_example-cloud-region-id-val-35532"}}
887         self.assertEqual(resp, return_success)
888
889     @mock.patch.object(restcall, "call_req")
890     def test_nf_grant_view_when_remove_resource(self, mock_call_req):
891         mock_vals = {
892             "/api/catalog/v1/vnfpackages/package_id_001":
893                 [0, json.JSONEncoder().encode(nf_package_info), "200"],
894             "/api/resmgr/v1/resource/grant":
895                 [1, json.JSONEncoder().encode({}), "200"],
896             "/cloud-infrastructure/cloud-regions/cloud-region/VCPE/RegionOne?depth=all":
897                 [0, json.JSONEncoder().encode(vim_info), "201"],
898         }
899
900         def side_effect(*args):
901             return mock_vals[args[4]]
902
903         mock_call_req.side_effect = side_effect
904         self.data.pop("addResource")
905         self.data["removeResource"] = [{"vdu": "vdu_grant_vnf_remove_resources"}]
906         resp = GrantVnfs(json.dumps(self.data), "").send_grant_vnf_to_resMgr()
907         return_success = {"vim": {"accessInfo": {"tenant": "admin"},
908                                   "vimId": "example-cloud-owner-val-97336_example-cloud-region-id-val-35532"}}
909         self.assertEqual(resp, return_success)
910
911
912 class TestGrantVnfViews(TestCase):
913     def setUp(self):
914         self.vnf_inst_id = str(uuid.uuid4())
915         self.data = {
916             "vnfInstanceId": self.vnf_inst_id,
917             "vnfLcmOpOccId": "vnf_lcm_op_occ_id",
918             "addResources": [{"vdu": "vdu_grant_vnf_add_resources"}],
919             "operation": "INSTANTIATE"
920         }
921         self.client = Client()
922         vdu_info_dict = [{"vduName": "vg", "flavorName": "flavor_1", "flavorId": "flavor_id_001", "directive": []}]
923         OOFDataModel(request_id="request_id_001", transaction_id="transaction_id_001", request_status="done",
924                      request_module_name="vg", service_resource_id=self.vnf_inst_id, vim_id="cloudOwner_casa",
925                      cloud_owner="cloudOwner", cloud_region_id="casa", vdu_info=json.dumps(vdu_info_dict)).save()
926         NfInstModel(mnfinstid=self.vnf_inst_id, nfinstid="vnf_inst_id_001", package_id="package_id_001",
927                     vnfm_inst_id="vnfm_id_001").save()
928
929     def tearDown(self):
930         OOFDataModel.objects.all().delete()
931         NfInstModel.objects.all().delete()
932
933     @mock.patch.object(resmgr, "grant_vnf")
934     def test_vnf_grant_view(self, mock_grant):
935         resmgr_grant_resp = {
936             "vim": {
937                 "vimId": "cloudOwner_casa",
938                 "accessInfo": {
939                     "tenant": "tenantA"
940                 }
941             }
942         }
943         mock_grant.return_value = resmgr_grant_resp
944         self.data.pop("addResources")
945         response = self.client.post("/api/nslcm/v2/grants", data=self.data)
946         self.assertEqual(response.status_code, status.HTTP_201_CREATED)
947         self.assertEqual(response.data["vimAssets"]["computeResourceFlavours"][0]["vimConnectionId"], "cloudOwner_casa")
948         self.assertEqual(response.data["vimAssets"]["computeResourceFlavours"][0]["resourceProviderId"], "vg")
949         self.assertEqual(response.data["vimAssets"]["computeResourceFlavours"][0]["vimFlavourId"], "flavor_id_001")
950
951     @mock.patch.object(restcall, "call_req")
952     @mock.patch.object(resmgr, "grant_vnf")
953     def test_exec_grant_when_add_resources_success(self, mock_grant, mock_call_req):
954         mock_vals = {
955             "/api/catalog/v1/vnfpackages/package_id_001":
956                 [0, json.JSONEncoder().encode(nf_package_info), "200"],
957         }
958
959         def side_effect(*args):
960             return mock_vals[args[4]]
961
962         mock_call_req.side_effect = side_effect
963         resmgr_grant_resp = {
964             "vim": {
965                 "vimId": "cloudOwner_casa",
966                 "accessInfo": {
967                     "tenant": "tenantA"
968                 }
969             }
970         }
971         mock_grant.return_value = resmgr_grant_resp
972         resp = GrantVnf(json.dumps(self.data)).exec_grant()
973         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["vimConnectionId"], "cloudOwner_casa")
974         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["resourceProviderId"], "vg")
975         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["vimFlavourId"], "flavor_id_001")
976
977     def test_exec_grant_when_add_resources_but_no_vnfinst(self):
978         self.data["vnfInstanceId"] = "no_vnfinst"
979         resp = None
980         try:
981             resp = GrantVnf(json.dumps(self.data)).exec_grant()
982         except NSLCMException as e:
983             self.assertEqual(type(e), NSLCMException)
984         finally:
985             self.assertEqual(resp, None)
986
987     @mock.patch.object(time, "sleep")
988     @mock.patch.object(restcall, "call_req")
989     @mock.patch.object(resmgr, "grant_vnf")
990     def test_exec_grant_when_add_resources_but_no_off(self, mock_grant, mock_call_req, mock_sleep):
991         NfInstModel(mnfinstid="add_resources_but_no_off", nfinstid="vnf_inst_id_002",
992                     package_id="package_id_002").save()
993         mock_sleep.return_value = None
994         mock_vals = {
995             "/api/catalog/v1/vnfpackages/package_id_002":
996                 [0, json.JSONEncoder().encode(nf_package_info), "200"],
997         }
998
999         def side_effect(*args):
1000             return mock_vals[args[4]]
1001
1002         mock_call_req.side_effect = side_effect
1003         resmgr_grant_resp = {
1004             "vim": {
1005                 "vimId": "cloudOwner_casa",
1006                 "accessInfo": {
1007                     "tenant": "tenantA"
1008                 }
1009             }
1010         }
1011         mock_grant.return_value = resmgr_grant_resp
1012         self.data["vnfInstanceId"] = "add_resources_but_no_off"
1013         resp = GrantVnf(json.dumps(self.data)).exec_grant()
1014         self.assertEqual(resp["vnfInstanceId"], "add_resources_but_no_off")
1015         self.assertEqual(resp["vnfLcmOpOccId"], "vnf_lcm_op_occ_id")
1016         vimConnections = []
1017         self.assertEqual(resp["vimConnections"], vimConnections)
1018
1019     @mock.patch.object(resmgr, "grant_vnf")
1020     def test_exec_grant_when_resource_template_in_add_resources(self, mock_grant):
1021         resmgr_grant_resp = {
1022             "vim": {
1023                 "vimId": "cloudOwner_casa",
1024                 "accessInfo": {
1025                     "tenant": "tenantA"
1026                 }
1027             }
1028         }
1029         mock_grant.return_value = resmgr_grant_resp
1030         self.data["addResources"] = [{"vdu": "vdu_grant_vnf_add_resources"}, "resourceTemplate"]
1031         resp = GrantVnf(json.dumps(self.data)).exec_grant()
1032         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["vimConnectionId"], "cloudOwner_casa")
1033         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["resourceProviderId"], "vg")
1034         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["vimFlavourId"], "flavor_id_001")
1035
1036     @mock.patch.object(restcall, "call_req")
1037     @mock.patch.object(resmgr, "grant_vnf")
1038     def test_exec_grant_when_remove_resources_success(self, mock_grant, mock_call_req):
1039         mock_vals = {
1040             "/api/catalog/v1/vnfpackages/package_id_001":
1041                 [0, json.JSONEncoder().encode(nf_package_info), "200"],
1042         }
1043
1044         def side_effect(*args):
1045             return mock_vals[args[4]]
1046
1047         mock_call_req.side_effect = side_effect
1048         resmgr_grant_resp = {
1049             "vim": {
1050                 "vimId": "cloudOwner_casa",
1051                 "accessInfo": {
1052                     "tenant": "tenantA"
1053                 }
1054             }
1055         }
1056         mock_grant.return_value = resmgr_grant_resp
1057         self.data.pop("addResources")
1058         self.data["removeResources"] = [{"vdu": "vdu_grant_vnf_remove_resources"}]
1059         self.data["additionalparams"] = {"vnfmid": "vnfm_id_001"}
1060         resp = GrantVnf(json.dumps(self.data)).exec_grant()
1061         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["vimConnectionId"], "cloudOwner_casa")
1062         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["resourceProviderId"], "vg")
1063         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["vimFlavourId"], "flavor_id_001")
1064
1065     def test_exec_grant_when_remove_resources_no_vnfinst(self):
1066         self.data.pop("addResources")
1067         self.data["removeResources"] = [{"vdu": "vdu_grant_vnf_remove_resources"}]
1068         self.data["additionalparams"] = {"vnfmid": "vnfm_id_002"}
1069         resp = None
1070         try:
1071             resp = GrantVnf(json.dumps(self.data)).exec_grant()
1072         except NSLCMException as e:
1073             self.assertEqual(type(e), NSLCMException)
1074         finally:
1075             self.assertEqual(resp, None)
1076
1077     @mock.patch.object(time, "sleep")
1078     @mock.patch.object(restcall, "call_req")
1079     @mock.patch.object(resmgr, "grant_vnf")
1080     def test_exec_grant_when_remove_resources_but_no_off(self, mock_grant, mock_call_req, mock_sleep):
1081         NfInstModel(mnfinstid="remove_resources_but_no_off", nfinstid="vnf_inst_id_002", package_id="package_id_002",
1082                     vnfm_inst_id="vnfm_id_002").save()
1083         mock_sleep.return_value = None
1084         mock_vals = {
1085             "/api/catalog/v1/vnfpackages/package_id_002":
1086                 [0, json.JSONEncoder().encode(nf_package_info), "200"],
1087         }
1088
1089         def side_effect(*args):
1090             return mock_vals[args[4]]
1091
1092         mock_call_req.side_effect = side_effect
1093         resmgr_grant_resp = {
1094             "vim": {
1095                 "vimId": "cloudOwner_casa",
1096                 "accessInfo": {
1097                     "tenant": "tenantA"
1098                 }
1099             }
1100         }
1101         mock_grant.return_value = resmgr_grant_resp
1102         self.data["vnfInstanceId"] = "remove_resources_but_no_off"
1103         self.data.pop("addResources")
1104         self.data["removeResources"] = [{"vdu": "vdu_grant_vnf_remove_resources"}]
1105         self.data["additionalparams"] = {"vnfmid": "vnfm_id_002"}
1106         resp = GrantVnf(json.dumps(self.data)).exec_grant()
1107         self.assertEqual(resp["vnfInstanceId"], "remove_resources_but_no_off")
1108         self.assertEqual(resp["vnfLcmOpOccId"], "vnf_lcm_op_occ_id")
1109         vimConnections = []
1110         self.assertEqual(resp["vimConnections"], vimConnections)
1111
1112     @mock.patch.object(resmgr, "grant_vnf")
1113     def test_exec_grant_when_resource_template_in_remove_resources(self, mock_grant):
1114         resmgr_grant_resp = {
1115             "vim": {
1116                 "vimId": "cloudOwner_casa",
1117                 "accessInfo": {
1118                     "tenant": "tenantA"
1119                 }
1120             }
1121         }
1122         mock_grant.return_value = resmgr_grant_resp
1123         self.data.pop("addResources")
1124         self.data["removeResources"] = [{"vdu": "vdu_grant_vnf_remove_resources"}, "resourceTemplate"]
1125         resp = GrantVnf(json.dumps(self.data)).exec_grant()
1126         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["vimConnectionId"], "cloudOwner_casa")
1127         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["resourceProviderId"], "vg")
1128         self.assertEqual(resp["vimAssets"]["computeResourceFlavours"][0]["vimFlavourId"], "flavor_id_001")
1129
1130
1131 class TestCreateVnfViews(TestCase):
1132     def setUp(self):
1133         self.ns_inst_id = str(uuid.uuid4())
1134         self.job_id = str(uuid.uuid4())
1135         self.data = {
1136             "vnfIndex": "1",
1137             "nsInstanceId": self.ns_inst_id,
1138             # "additionalParamForNs": {"inputs": json.dumps({})},
1139             "additionalParamForVnf": [
1140                 {
1141                     "vnfprofileid": "VBras",
1142                     "additionalparam": {
1143                         "inputs": json.dumps({
1144                             "vnf_param1": "11",
1145                             "vnf_param2": "22"
1146                         }),
1147                         "vnfminstanceid": "1",
1148                         # "vimId": "zte_test",
1149                         "vimId": '{"cloud_owner": "VCPE", "cloud_regionid": "RegionOne"}'
1150                     }
1151                 }
1152             ]
1153         }
1154         self.client = Client()
1155         NSInstModel(id=self.ns_inst_id, name="ns", nspackage_id="1", nsd_id="nsd_id", description="description",
1156                     status="instantiating", nsd_model=json.dumps(nsd_model_dict), create_time=now_time(),
1157                     lastuptime=now_time()).save()
1158         VLInstModel(vldid="ext_mnet_network", ownertype=OWNER_TYPE.NS, ownerid=self.ns_inst_id,
1159                     vimid="{}").save()
1160
1161     def tearDown(self):
1162         NfInstModel.objects.all().delete()
1163         JobModel.objects.all().delete()
1164
1165     @mock.patch.object(CreateVnfs, "run")
1166     def test_create_vnf_view(self, mock_run):
1167         response = self.client.post("/api/nslcm/v1/ns/vnfs", data=self.data)
1168         self.assertEqual(status.HTTP_202_ACCEPTED, response.status_code)
1169         context = json.loads(response.content)
1170         self.assertTrue(NfInstModel.objects.filter(nfinstid=context["vnfInstId"]).exists())
1171
1172     @mock.patch.object(time, "sleep")
1173     @mock.patch.object(restcall, "call_req")
1174     def test_create_vnf_thread_sucess(self, mock_call_req, mock_sleep):
1175         mock_sleep.return_value = None
1176         nf_inst_id, job_id = create_vnfs.prepare_create_params()
1177         mock_vals = {
1178             "/api/catalog/v1/vnfpackages/zte_vbras":
1179                 [0, json.JSONEncoder().encode(nf_package_info), "200"],
1180             "/external-system/esr-vnfm-list/esr-vnfm/1?depth=all":
1181                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
1182             "/api/ztevnfmdriver/v1/1/vnfs":
1183                 [0, json.JSONEncoder().encode({"jobId": self.job_id, "vnfInstanceId": 3}), "200"],
1184             "/api/oof/v1/placement":
1185                 [0, json.JSONEncoder().encode({}), "202"],
1186             "/api/resmgr/v1/vnf":
1187                 [0, json.JSONEncoder().encode({}), "200"],
1188             "/api/ztevnfmdriver/v1/1/jobs/" + self.job_id + "?responseId=0":
1189                 [0, json.JSONEncoder().encode({"jobid": self.job_id,
1190                                                "responsedescriptor": {"progress": "100",
1191                                                                       "status": JOB_MODEL_STATUS.FINISHED,
1192                                                                       "responseid": "3",
1193                                                                       "statusdescription": "creating",
1194                                                                       "errorcode": "0",
1195                                                                       "responsehistorylist": [
1196                                                                           {"progress": "0",
1197                                                                            "status": JOB_MODEL_STATUS.PROCESSING,
1198                                                                            "responseid": "2",
1199                                                                            "statusdescription": "creating",
1200                                                                            "errorcode": "0"}]}}), "200"],
1201             "api/gvnfmdriver/v1/1/subscriptions":
1202                 [0, json.JSONEncoder().encode(subscription_response_data), "200"],
1203             "/api/resmgr/v1/vnfinfo":
1204                 [0, json.JSONEncoder().encode(subscription_response_data), "200"],
1205
1206             # "/network/generic-vnfs/generic-vnf/%s" % nf_inst_id:
1207             #     [0, json.JSONEncoder().encode({}), "201"],
1208             # "/cloud-infrastructure/cloud-regions/cloud-region/zte/test?depth=all":
1209             #     [0, json.JSONEncoder().encode(vim_info), "201"],
1210             # "/cloud-infrastructure/cloud-regions/cloud-region/zte/test/tenants/tenant/admin/vservers/vserver/1":
1211             #     [0, json.JSONEncoder().encode({}), "201"],
1212
1213         }
1214
1215         def side_effect(*args):
1216             return mock_vals[args[4]]
1217         mock_call_req.side_effect = side_effect
1218         data = {
1219             "ns_instance_id": ignore_case_get(self.data, "nsInstanceId"),
1220             "additional_param_for_ns": ignore_case_get(self.data, "additionalParamForNs"),
1221             "additional_param_for_vnf": ignore_case_get(self.data, "additionalParamForVnf"),
1222             "vnf_index": ignore_case_get(self.data, "vnfIndex")
1223         }
1224         CreateVnfs(data, nf_inst_id, job_id).run()
1225         self.assertEqual(NfInstModel.objects.get(nfinstid=nf_inst_id).status, VNF_STATUS.ACTIVE)
1226         self.assertEqual(JobModel.objects.get(jobid=job_id).progress, JOB_PROGRESS.FINISHED)
1227
1228     def test_create_vnf_thread_when_the_name_of_vnf_instance_already_exists(self):
1229         NfInstModel(nf_name="").save()
1230         nf_inst_id, job_id = create_vnfs.prepare_create_params()
1231         data = {
1232             "ns_instance_id": ignore_case_get(self.data, "nsInstanceId"),
1233             "additional_param_for_ns": ignore_case_get(self.data, "additionalParamForNs"),
1234             "additional_param_for_vnf": ignore_case_get(self.data, "additionalParamForVnf"),
1235             "vnf_index": ignore_case_get(self.data, "vnfIndex")
1236         }
1237         CreateVnfs(data, nf_inst_id, job_id).run()
1238         self.assertEqual(NfInstModel.objects.get(nfinstid=nf_inst_id).status, VNF_STATUS.FAILED)
1239         self.assertEqual(JobModel.objects.get(jobid=job_id).progress, JOB_PROGRESS.ERROR)
1240
1241     @mock.patch.object(time, "sleep")
1242     @mock.patch.object(restcall, "call_req")
1243     def test_create_vnf_thread_when_data_has_vnfd_id(self, mock_call_req, mock_sleep):
1244         mock_sleep.return_value = None
1245         nf_inst_id, job_id = create_vnfs.prepare_create_params()
1246         mock_vals = {
1247             "/api/catalog/v1/vnfpackages/data_has_vnfd_id":
1248                 [0, json.JSONEncoder().encode(nf_package_info), "200"],
1249             "/external-system/esr-vnfm-list/esr-vnfm/1?depth=all":
1250                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
1251             "/api/ztevnfmdriver/v1/1/vnfs":
1252                 [0, json.JSONEncoder().encode({"jobId": self.job_id, "vnfInstanceId": 3}), "200"],
1253             "/api/oof/v1/placement":
1254                 [0, json.JSONEncoder().encode({}), "202"],
1255             "/api/resmgr/v1/vnf":
1256                 [0, json.JSONEncoder().encode({}), "200"],
1257             "/api/ztevnfmdriver/v1/1/jobs/" + self.job_id + "?responseId=0":
1258                 [0, json.JSONEncoder().encode({"jobid": self.job_id,
1259                                                "responsedescriptor": {"progress": "100",
1260                                                                       "status": JOB_MODEL_STATUS.FINISHED,
1261                                                                       "responseid": "3",
1262                                                                       "statusdescription": "creating",
1263                                                                       "errorcode": "0",
1264                                                                       "responsehistorylist": [
1265                                                                           {"progress": "0",
1266                                                                            "status": JOB_MODEL_STATUS.PROCESSING,
1267                                                                            "responseid": "2",
1268                                                                            "statusdescription": "creating",
1269                                                                            "errorcode": "0"}]}}), "200"],
1270             "api/gvnfmdriver/v1/1/subscriptions":
1271                 [0, json.JSONEncoder().encode({}), "200"],
1272             "/api/resmgr/v1/vnfinfo":
1273                 [0, json.JSONEncoder().encode(subscription_response_data), "200"]
1274         }
1275
1276         def side_effect(*args):
1277             return mock_vals[args[4]]
1278
1279         mock_call_req.side_effect = side_effect
1280         self.data["additionalParamForVnf"][0]["additionalparam"]["vnfdId"] = "data_has_vnfd_id"
1281         data = {
1282             "ns_instance_id": ignore_case_get(self.data, "nsInstanceId"),
1283             "additional_param_for_ns": ignore_case_get(self.data, "additionalParamForNs"),
1284             "additional_param_for_vnf": ignore_case_get(self.data, "additionalParamForVnf"),
1285             "vnf_index": ignore_case_get(self.data, "vnfIndex")
1286         }
1287         CreateVnfs(data, nf_inst_id, job_id).run()
1288         self.assertEqual(NfInstModel.objects.get(nfinstid=nf_inst_id).status, VNF_STATUS.ACTIVE)
1289         self.assertEqual(JobModel.objects.get(jobid=job_id).progress, JOB_PROGRESS.FINISHED)
1290
1291     @mock.patch.object(restcall, "call_req")
1292     @mock.patch.object(CreateVnfs, "build_homing_request")
1293     def test_send_homing_request(self, mock_build_req, mock_call_req):
1294         nf_inst_id, job_id = create_vnfs.prepare_create_params()
1295         OOFDataModel.objects.all().delete()
1296         resp = {
1297             "requestId": "1234",
1298             "transactionId": "1234",
1299             "requestStatus": "accepted"
1300         }
1301         mock_build_req.return_value = {
1302             "requestInfo": {
1303                 "transactionId": "1234",
1304                 "requestId": "1234",
1305                 "callbackUrl": "xx",
1306                 "sourceId": "vfc",
1307                 "requestType": "create",
1308                 "numSolutions": 1,
1309                 "optimizers": ["placement"],
1310                 "timeout": 600
1311             },
1312             "placementInfo": {
1313                 "placementDemands": [
1314                     {
1315                         "resourceModuleName": "vG",
1316                         "serviceResourceId": "1234",
1317                         "resourceModelInfo": {
1318                             "modelInvariantId": "1234",
1319                             "modelVersionId": "1234"
1320                         }
1321                     }
1322                 ]
1323             },
1324             "serviceInfo": {
1325                 "serviceInstanceId": "1234",
1326                 "serviceName": "1234",
1327                 "modelInfo": {
1328                     "modelInvariantId": "5678",
1329                     "modelVersionId": "7890"
1330                 }
1331             }
1332         }
1333         mock_call_req.return_value = [0, json.JSONEncoder().encode(resp), "202"]
1334         data = {
1335             "ns_instance_id": ignore_case_get(self.data, "nsInstanceId"),
1336             "additional_param_for_ns": ignore_case_get(self.data, "additionalParamForNs"),
1337             "additional_param_for_vnf": ignore_case_get(self.data, "additionalParamForVnf"),
1338             "vnf_index": ignore_case_get(self.data, "vnfIndex")
1339         }
1340         CreateVnfs(data, nf_inst_id, job_id).send_homing_request_to_OOF()
1341         ret = OOFDataModel.objects.filter(request_id="1234", transaction_id="1234")
1342         self.assertIsNotNone(ret)
1343
1344     @mock.patch.object(time, "sleep")
1345     @mock.patch.object(restcall, "call_req")
1346     def test_create_vnf_thread_sucess_when_failed_to_subscribe_from_vnfm(self, mock_call_req, mock_sleep):
1347         mock_sleep.return_value = None
1348         nf_inst_id, job_id = create_vnfs.prepare_create_params()
1349         mock_vals = {
1350             "/api/catalog/v1/vnfpackages/zte_vbras":
1351                 [0, json.JSONEncoder().encode(nf_package_info), "200"],
1352             "/external-system/esr-vnfm-list/esr-vnfm/1?depth=all":
1353                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
1354             "/api/ztevnfmdriver/v1/1/vnfs":
1355                 [0, json.JSONEncoder().encode({"jobId": self.job_id, "vnfInstanceId": 3}), "200"],
1356             "/api/oof/v1/placement":
1357                 [0, json.JSONEncoder().encode({}), "202"],
1358             "/api/resmgr/v1/vnf":
1359                 [0, json.JSONEncoder().encode({}), "200"],
1360             "/api/ztevnfmdriver/v1/1/jobs/" + self.job_id + "?responseId=0":
1361                 [0, json.JSONEncoder().encode({"jobid": self.job_id,
1362                                                "responsedescriptor": {"progress": "100",
1363                                                                       "status": JOB_MODEL_STATUS.FINISHED,
1364                                                                       "responseid": "3",
1365                                                                       "statusdescription": "creating",
1366                                                                       "errorcode": "0",
1367                                                                       "responsehistorylist": [
1368                                                                           {"progress": "0",
1369                                                                            "status": JOB_MODEL_STATUS.PROCESSING,
1370                                                                            "responseid": "2",
1371                                                                            "statusdescription": "creating",
1372                                                                            "errorcode": "0"}]}}), "200"],
1373             "api/gvnfmdriver/v1/1/subscriptions":
1374                 [1, json.JSONEncoder().encode(subscription_response_data), "200"],
1375             "/api/resmgr/v1/vnfinfo":
1376                 [0, json.JSONEncoder().encode(subscription_response_data), "200"],
1377         }
1378
1379         def side_effect(*args):
1380             return mock_vals[args[4]]
1381
1382         mock_call_req.side_effect = side_effect
1383         data = {
1384             "ns_instance_id": ignore_case_get(self.data, "nsInstanceId"),
1385             "additional_param_for_ns": ignore_case_get(self.data, "additionalParamForNs"),
1386             "additional_param_for_vnf": ignore_case_get(self.data, "additionalParamForVnf"),
1387             "vnf_index": ignore_case_get(self.data, "vnfIndex")
1388         }
1389         CreateVnfs(data, nf_inst_id, job_id).run()
1390         self.assertEqual(NfInstModel.objects.get(nfinstid=nf_inst_id).status, VNF_STATUS.ACTIVE)
1391         self.assertEqual(JobModel.objects.get(jobid=job_id).progress, JOB_PROGRESS.FINISHED)
1392
1393
1394 class TestUpdateVnfsViews(TestCase):
1395     def setUp(self):
1396         self.client = Client()
1397         self.data = {
1398             "terminationType": "forceful",
1399             "gracefulTerminationTimeout": "600",
1400             "additionalParams": ""
1401         }
1402         self.nf_inst_id = "test_update_vnf"
1403         self.m_nf_inst_id = "test_update_vnf_m_nf_inst_id"
1404         self.vnfm_inst_id = "test_update_vnf_vnfm_inst_id"
1405         self.vnfd_model = {"metadata": {"vnfdId": "1"}}
1406         NfInstModel.objects.all().delete()
1407         NfInstModel.objects.create(nfinstid=self.nf_inst_id,
1408                                    vnfm_inst_id=self.vnfm_inst_id,
1409                                    status=VNF_STATUS.NULL,
1410                                    mnfinstid=self.m_nf_inst_id,
1411                                    vnfd_model=self.vnfd_model
1412                                    )
1413
1414     def tearDown(self):
1415         NfInstModel.objects.all().delete()
1416
1417     @mock.patch.object(time, "sleep")
1418     @mock.patch.object(restcall, "call_req")
1419     def test_update_vnf_thread(self, mock_call_req, mock_sleep):
1420         vnf_update_service = NFOperateService(self.nf_inst_id, self.data)
1421         job_info = {
1422             "jobId": vnf_update_service.job_id,
1423             "responsedescriptor": {"status": JOB_MODEL_STATUS.FINISHED}
1424         }
1425         mock_vals = {
1426             "/external-system/esr-vnfm-list/esr-vnfm/test_update_vnf_vnfm_inst_id?depth=all":
1427                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
1428             "/api/ztevnfmdriver/v1/test_update_vnf_vnfm_inst_id/vnfs/test_update_vnf_m_nf_inst_id/operate":
1429                 [0, json.JSONEncoder().encode({"jobId": vnf_update_service.job_id}), "200"],
1430             "/api/ztevnfmdriver/v1/test_update_vnf_vnfm_inst_id/jobs/" + vnf_update_service.job_id + "?responseId=0":
1431                 [0, json.JSONEncoder().encode(job_info), "200"],
1432         }
1433
1434         def side_effect(*args):
1435             return mock_vals[args[4]]
1436         mock_call_req.side_effect = side_effect
1437         vnf_update_service.run()
1438         nfinst = NfInstModel.objects.get(nfinstid=self.nf_inst_id)
1439         self.assertEqual(nfinst.status, VNF_STATUS.ACTIVE)
1440         self.assertEqual(JobModel.objects.get(jobid=vnf_update_service.job_id).progress, JOB_PROGRESS.FINISHED)
1441
1442     def test_update_vnf_thread_when_no_nf(self):
1443         NfInstModel.objects.all().delete()
1444         vnf_update_service = NFOperateService(self.nf_inst_id, self.data)
1445         vnf_update_service.run()
1446         self.assertEqual(JobModel.objects.get(jobid=vnf_update_service.job_id).progress, JOB_PROGRESS.ERROR)
1447
1448     @mock.patch.object(time, "sleep")
1449     @mock.patch.object(restcall, "call_req")
1450     def test_update_vnf_thread_when_nf_update_failed(self, mock_call_req, mock_sleep):
1451         vnf_update_service = NFOperateService(self.nf_inst_id, self.data)
1452         job_info = {
1453             "jobId": vnf_update_service.job_id,
1454             "responsedescriptor": {"status": JOB_MODEL_STATUS.ERROR}
1455         }
1456         mock_vals = {
1457             "/external-system/esr-vnfm-list/esr-vnfm/test_update_vnf_vnfm_inst_id?depth=all":
1458                 [0, json.JSONEncoder().encode(vnfm_info), "200"],
1459             "/api/ztevnfmdriver/v1/test_update_vnf_vnfm_inst_id/vnfs/test_update_vnf_m_nf_inst_id/operate":
1460                 [0, json.JSONEncoder().encode({"jobId": vnf_update_service.job_id}), "200"],
1461             "/api/ztevnfmdriver/v1/test_update_vnf_vnfm_inst_id/jobs/" + vnf_update_service.job_id + "?responseId=0":
1462                 [0, json.JSONEncoder().encode(job_info), "200"],
1463         }
1464
1465         def side_effect(*args):
1466             return mock_vals[args[4]]
1467
1468         mock_call_req.side_effect = side_effect
1469         vnf_update_service.run()
1470         nfinst = NfInstModel.objects.get(nfinstid=self.nf_inst_id)
1471         self.assertEqual(nfinst.status, VNF_STATUS.UPDATING)
1472         self.assertEqual(JobModel.objects.get(jobid=vnf_update_service.job_id).progress, JOB_PROGRESS.ERROR)
1473
1474
1475 class TestVerifyVnfsViews(TestCase):
1476     def setUp(self):
1477         self.client = Client()
1478         self.url = "/api/nslcm/v1/vnfonboarding"
1479         self.package_id = "test_verify_vnfs_package_id"
1480         self.nf_inst_id = "test_verify_vnfs"
1481         self.m_nf_inst_id = "test_verify_vnfs_m_nf_inst_id"
1482         self.vnfm_inst_id = "test_verify_vnfs_vnfm_inst_id"
1483         self.vnfd_model = {"metadata": {"vnfdId": "1"}}
1484         self.data = {
1485             "PackageID": self.package_id,
1486         }
1487         self.job_id = JobUtil.create_job(JOB_TYPE.VNF, "verify_vnfs", self.nf_inst_id)
1488         NfInstModel.objects.all().delete()
1489         NfInstModel.objects.create(package_id=self.package_id,
1490                                    nfinstid=self.nf_inst_id,
1491                                    vnfm_inst_id=self.vnfm_inst_id,
1492                                    status=VNF_STATUS.NULL,
1493                                    mnfinstid=self.m_nf_inst_id,
1494                                    vnfd_model=self.vnfd_model
1495                                    )
1496
1497     def tearDown(self):
1498         NfInstModel.objects.all().delete()
1499
1500     @mock.patch.object(VerifyVnfs, "run")
1501     def test_verify_vnfs_view(self, mock_run):
1502         response = self.client.post(self.url, data=self.data)
1503         self.assertEqual(status.HTTP_202_ACCEPTED, response.status_code)
1504
1505     def test_verify_vnfs_view_when_data_is_not_valid(self):
1506         response = self.client.post(self.url, data={})
1507         self.assertEqual(status.HTTP_409_CONFLICT, response.status_code)
1508
1509     @mock.patch.object(time, "sleep")
1510     @mock.patch.object(restcall, "call_req")
1511     def test_verify_vnfs_thread(self, mock_call_req, mock_sleep):
1512         job_info_1 = {
1513             "jobId": "test_1",
1514             "responseDescriptor": {
1515                 "status": JOB_MODEL_STATUS.FINISHED,
1516                 "progress": 100,
1517                 "responseId": 0,
1518                 "statusDescription": ""
1519             }
1520         }
1521         job_info_2 = {
1522             "jobId": "test_2",
1523             "responseDescriptor": {
1524                 "status": JOB_MODEL_STATUS.FINISHED,
1525                 "progress": 100,
1526                 "responseId": 0,
1527                 "statusDescription": ""
1528             }
1529         }
1530         job_info_task = {
1531             "jobId": "task_id",
1532             "responseDescriptor": {
1533                 "status": JOB_MODEL_STATUS.FINISHED,
1534                 "progress": 100,
1535                 "responseId": 0,
1536                 "statusDescription": ""
1537             }
1538         }
1539         mock_vals = {
1540             "/api/nslcm/v1/vnfpackage":
1541                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1542             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1543                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1544             "/api/nslcm/v1/ns/ns_vnfs":
1545                 [0, json.JSONEncoder().encode({"jobId": "test_2", "vnfInstId": ""}), "200"],
1546             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_2", 0):
1547                 [0, json.JSONEncoder().encode(job_info_2), "200"],
1548             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks":
1549                 [0, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1550             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s?responseId=%s" % ("task_id", 0):
1551                 [0, json.JSONEncoder().encode(job_info_task), "200"],
1552             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s/result" % "task_id":
1553                 [0, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1554         }
1555
1556         def side_effect(*args):
1557             return mock_vals[args[4]]
1558         mock_call_req.side_effect = side_effect
1559         VerifyVnfs(self.data, self.job_id).run()
1560         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.FINISHED)
1561
1562     @mock.patch.object(time, "sleep")
1563     @mock.patch.object(restcall, "call_req")
1564     def test_verify_vnfs_thread_when_failed_to_call_vnf_onboarding(self, mock_call_req, mock_sleep):
1565         mock_vals = {
1566             "/api/nslcm/v1/vnfpackage":
1567                 [1, json.JSONEncoder().encode({}), "200"]
1568         }
1569
1570         def side_effect(*args):
1571             return mock_vals[args[4]]
1572
1573         mock_call_req.side_effect = side_effect
1574         VerifyVnfs(self.data, self.job_id).run()
1575         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.ERROR)
1576
1577     @mock.patch.object(time, "sleep")
1578     @mock.patch.object(restcall, "call_req")
1579     def test_verify_vnfs_thread_when_do_on_boarding_failed_to_query_job(self, mock_call_req, mock_sleep):
1580         job_info_1 = {
1581             "jobId": "test_1",
1582             "responseDescriptor": {
1583                 "status": JOB_MODEL_STATUS.FINISHED,
1584                 "progress": 100,
1585                 "responseId": 0,
1586                 "statusDescription": ""
1587             }
1588         }
1589         mock_vals = {
1590             "/api/nslcm/v1/vnfpackage":
1591                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1592             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1593                 [1, json.JSONEncoder().encode(job_info_1), "200"],
1594         }
1595
1596         def side_effect(*args):
1597             return mock_vals[args[4]]
1598
1599         mock_call_req.side_effect = side_effect
1600         VerifyVnfs(self.data, self.job_id).run()
1601         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.ERROR)
1602
1603     @mock.patch.object(time, "sleep")
1604     @mock.patch.object(restcall, "call_req")
1605     def test_verify_vnfs_thread_when_do_on_boarding_job_does_not_exist(self, mock_call_req, mock_sleep):
1606         job_info_1 = {
1607             "jobId": "test_1",
1608         }
1609         mock_vals = {
1610             "/api/nslcm/v1/vnfpackage":
1611                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1612             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1613                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1614         }
1615
1616         def side_effect(*args):
1617             return mock_vals[args[4]]
1618
1619         mock_call_req.side_effect = side_effect
1620         VerifyVnfs(self.data, self.job_id).run()
1621         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.ERROR)
1622
1623     @mock.patch.object(time, "sleep")
1624     @mock.patch.object(restcall, "call_req")
1625     def test_verify_vnfs_thread_when_do_on_boarding_job_process_error(self, mock_call_req, mock_sleep):
1626         job_info_1 = {
1627             "jobId": "test_1",
1628             "responseDescriptor": {
1629                 "status": JOB_MODEL_STATUS.FINISHED,
1630                 "progress": JOB_PROGRESS.ERROR,
1631                 "responseId": 1,
1632                 "statusDescription": "already onBoarded"
1633             }
1634         }
1635         job_info_2 = {
1636             "jobId": "test_2",
1637             "responseDescriptor": {
1638                 "status": JOB_MODEL_STATUS.FINISHED,
1639                 "progress": 100,
1640                 "responseId": 0,
1641                 "statusDescription": ""
1642             }
1643         }
1644         job_info_task = {
1645             "jobId": "task_id",
1646             "responseDescriptor": {
1647                 "status": JOB_MODEL_STATUS.FINISHED,
1648                 "progress": 100,
1649                 "responseId": 0,
1650                 "statusDescription": ""
1651             }
1652         }
1653         mock_vals = {
1654             "/api/nslcm/v1/vnfpackage":
1655                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1656             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1657                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1658             "/api/nslcm/v1/ns/ns_vnfs":
1659                 [0, json.JSONEncoder().encode({"jobId": "test_2", "vnfInstId": ""}), "200"],
1660             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_2", 0):
1661                 [0, json.JSONEncoder().encode(job_info_2), "200"],
1662             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks":
1663                 [0, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1664             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s?responseId=%s" % ("task_id", 0):
1665                 [0, json.JSONEncoder().encode(job_info_task), "200"],
1666             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s/result" % "task_id":
1667                 [0, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1668         }
1669
1670         def side_effect(*args):
1671             return mock_vals[args[4]]
1672
1673         mock_call_req.side_effect = side_effect
1674         VerifyVnfs(self.data, self.job_id).run()
1675         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.FINISHED)
1676
1677     @mock.patch.object(time, "sleep")
1678     @mock.patch.object(restcall, "call_req")
1679     def test_verify_vnfs_thread_when_failed_to_call_inst_vnf(self, mock_call_req, mock_sleep):
1680         job_info_1 = {
1681             "jobId": "test_1",
1682             "responseDescriptor": {
1683                 "status": JOB_MODEL_STATUS.FINISHED,
1684                 "progress": 100,
1685                 "responseId": 0,
1686                 "statusDescription": ""
1687             }
1688         }
1689         mock_vals = {
1690             "/api/nslcm/v1/vnfpackage":
1691                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1692             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1693                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1694             "/api/nslcm/v1/ns/ns_vnfs":
1695                 [1, json.JSONEncoder().encode({"jobId": "test_2", "vnfInstId": ""}), "200"],
1696         }
1697
1698         def side_effect(*args):
1699             return mock_vals[args[4]]
1700
1701         mock_call_req.side_effect = side_effect
1702         VerifyVnfs(self.data, self.job_id).run()
1703         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.ERROR)
1704
1705     @mock.patch.object(time, "sleep")
1706     @mock.patch.object(restcall, "call_req")
1707     def test_verify_vnfs_thread_when_do_term_vnf_job_process_error(self, mock_call_req, mock_sleep):
1708         job_info_1 = {
1709             "jobId": "test_1",
1710             "responseDescriptor": {
1711                 "status": JOB_MODEL_STATUS.FINISHED,
1712                 "progress": 100,
1713                 "responseId": 0,
1714                 "statusDescription": ""
1715             }
1716         }
1717         job_info_2 = {
1718             "jobId": "test_2",
1719             "responseDescriptor": {
1720                 "status": JOB_MODEL_STATUS.FINISHED,
1721                 "progress": JOB_PROGRESS.ERROR,
1722                 "responseId": 0,
1723                 "statusDescription": ""
1724             }
1725         }
1726         mock_vals = {
1727             "/api/nslcm/v1/vnfpackage":
1728                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1729             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1730                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1731             "/api/nslcm/v1/ns/ns_vnfs":
1732                 [0, json.JSONEncoder().encode({"jobId": "test_2", "vnfInstId": ""}), "200"],
1733             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_2", 0):
1734                 [0, json.JSONEncoder().encode(job_info_2), "200"],
1735         }
1736
1737         def side_effect(*args):
1738             return mock_vals[args[4]]
1739
1740         mock_call_req.side_effect = side_effect
1741         VerifyVnfs(self.data, self.job_id).run()
1742         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.ERROR)
1743
1744     @mock.patch.object(time, "sleep")
1745     @mock.patch.object(restcall, "call_req")
1746     def test_verify_vnfs_thread_when_failed_to_call_func_test(self, mock_call_req, mock_sleep):
1747         job_info_1 = {
1748             "jobId": "test_1",
1749             "responseDescriptor": {
1750                 "status": JOB_MODEL_STATUS.FINISHED,
1751                 "progress": 100,
1752                 "responseId": 0,
1753                 "statusDescription": ""
1754             }
1755         }
1756         job_info_2 = {
1757             "jobId": "test_2",
1758             "responseDescriptor": {
1759                 "status": JOB_MODEL_STATUS.FINISHED,
1760                 "progress": 100,
1761                 "responseId": 0,
1762                 "statusDescription": ""
1763             }
1764         }
1765         mock_vals = {
1766             "/api/nslcm/v1/vnfpackage":
1767                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1768             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1769                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1770             "/api/nslcm/v1/ns/ns_vnfs":
1771                 [0, json.JSONEncoder().encode({"jobId": "test_2", "vnfInstId": ""}), "200"],
1772             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_2", 0):
1773                 [0, json.JSONEncoder().encode(job_info_2), "200"],
1774             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks":
1775                 [1, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"]
1776         }
1777
1778         def side_effect(*args):
1779             return mock_vals[args[4]]
1780
1781         mock_call_req.side_effect = side_effect
1782         VerifyVnfs(self.data, self.job_id).run()
1783         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.ERROR)
1784
1785     @mock.patch.object(time, "sleep")
1786     @mock.patch.object(restcall, "call_req")
1787     def test_verify_vnfs_thread_when_do_func_test_failed_query_job(self, mock_call_req, mock_sleep):
1788         job_info_1 = {
1789             "jobId": "test_1",
1790             "responseDescriptor": {
1791                 "status": JOB_MODEL_STATUS.FINISHED,
1792                 "progress": 100,
1793                 "responseId": 0,
1794                 "statusDescription": ""
1795             }
1796         }
1797         job_info_2 = {
1798             "jobId": "test_2",
1799             "responseDescriptor": {
1800                 "status": JOB_MODEL_STATUS.FINISHED,
1801                 "progress": 100,
1802                 "responseId": 0,
1803                 "statusDescription": ""
1804             }
1805         }
1806         job_info_task = {
1807             "jobId": "task_id",
1808             "responseDescriptor": {
1809                 "status": JOB_MODEL_STATUS.FINISHED,
1810                 "progress": 100,
1811                 "responseId": 0,
1812                 "statusDescription": ""
1813             }
1814         }
1815         mock_vals = {
1816             "/api/nslcm/v1/vnfpackage":
1817                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1818             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1819                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1820             "/api/nslcm/v1/ns/ns_vnfs":
1821                 [0, json.JSONEncoder().encode({"jobId": "test_2", "vnfInstId": ""}), "200"],
1822             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_2", 0):
1823                 [0, json.JSONEncoder().encode(job_info_2), "200"],
1824             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks":
1825                 [0, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1826             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s?responseId=%s" % ("task_id", 0):
1827                 [1, json.JSONEncoder().encode(job_info_task), "200"],
1828         }
1829
1830         def side_effect(*args):
1831             return mock_vals[args[4]]
1832
1833         mock_call_req.side_effect = side_effect
1834         VerifyVnfs(self.data, self.job_id).run()
1835         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.ERROR)
1836
1837     @mock.patch.object(time, "sleep")
1838     @mock.patch.object(restcall, "call_req")
1839     def test_verify_vnfs_thread_when_do_func_test_job_does_not_exist(self, mock_call_req, mock_sleep):
1840         job_info_1 = {
1841             "jobId": "test_1",
1842             "responseDescriptor": {
1843                 "status": JOB_MODEL_STATUS.FINISHED,
1844                 "progress": 100,
1845                 "responseId": 0,
1846                 "statusDescription": ""
1847             }
1848         }
1849         job_info_2 = {
1850             "jobId": "test_2",
1851             "responseDescriptor": {
1852                 "status": JOB_MODEL_STATUS.FINISHED,
1853                 "progress": 100,
1854                 "responseId": 0,
1855                 "statusDescription": ""
1856             }
1857         }
1858         job_info_task = {
1859             "jobId": "task_id",
1860         }
1861         mock_vals = {
1862             "/api/nslcm/v1/vnfpackage":
1863                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1864             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1865                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1866             "/api/nslcm/v1/ns/ns_vnfs":
1867                 [0, json.JSONEncoder().encode({"jobId": "test_2", "vnfInstId": ""}), "200"],
1868             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_2", 0):
1869                 [0, json.JSONEncoder().encode(job_info_2), "200"],
1870             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks":
1871                 [0, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1872             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s?responseId=%s" % ("task_id", 0):
1873                 [0, json.JSONEncoder().encode(job_info_task), "200"],
1874             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s/result" % "task_id":
1875                 [0, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1876         }
1877
1878         def side_effect(*args):
1879             return mock_vals[args[4]]
1880
1881         mock_call_req.side_effect = side_effect
1882         VerifyVnfs(self.data, self.job_id).run()
1883         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.ERROR)
1884
1885     @mock.patch.object(time, "sleep")
1886     @mock.patch.object(restcall, "call_req")
1887     def test_verify_vnfs_thread_when_do_func_test_job_process_error(self, mock_call_req, mock_sleep):
1888         job_info_1 = {
1889             "jobId": "test_1",
1890             "responseDescriptor": {
1891                 "status": JOB_MODEL_STATUS.FINISHED,
1892                 "progress": 100,
1893                 "responseId": 0,
1894                 "statusDescription": ""
1895             }
1896         }
1897         job_info_2 = {
1898             "jobId": "test_2",
1899             "responseDescriptor": {
1900                 "status": JOB_MODEL_STATUS.FINISHED,
1901                 "progress": 100,
1902                 "responseId": 0,
1903                 "statusDescription": ""
1904             }
1905         }
1906         job_info_task = {
1907             "jobId": "task_id",
1908             "responseDescriptor": {
1909                 "status": JOB_MODEL_STATUS.ERROR,
1910                 "progress": JOB_PROGRESS.ERROR,
1911                 "responseId": 1,
1912                 "statusDescription": "already onBoarded"
1913             }
1914         }
1915         mock_vals = {
1916             "/api/nslcm/v1/vnfpackage":
1917                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1918             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1919                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1920             "/api/nslcm/v1/ns/ns_vnfs":
1921                 [0, json.JSONEncoder().encode({"jobId": "test_2", "vnfInstId": ""}), "200"],
1922             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_2", 0):
1923                 [0, json.JSONEncoder().encode(job_info_2), "200"],
1924             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks":
1925                 [0, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1926             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s?responseId=%s" % ("task_id", 0):
1927                 [0, json.JSONEncoder().encode(job_info_task), "200"],
1928             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s/result" % "task_id":
1929                 [0, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1930         }
1931
1932         def side_effect(*args):
1933             return mock_vals[args[4]]
1934
1935         mock_call_req.side_effect = side_effect
1936         VerifyVnfs(self.data, self.job_id).run()
1937         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.FINISHED)
1938
1939     @mock.patch.object(time, "sleep")
1940     @mock.patch.object(restcall, "call_req")
1941     def test_verify_vnfs_thread_when_do_func_test_failed_to_get_func_test_result(self, mock_call_req, mock_sleep):
1942         job_info_1 = {
1943             "jobId": "test_1",
1944             "responseDescriptor": {
1945                 "status": JOB_MODEL_STATUS.FINISHED,
1946                 "progress": 100,
1947                 "responseId": 0,
1948                 "statusDescription": ""
1949             }
1950         }
1951         job_info_2 = {
1952             "jobId": "test_2",
1953             "responseDescriptor": {
1954                 "status": JOB_MODEL_STATUS.FINISHED,
1955                 "progress": 100,
1956                 "responseId": 0,
1957                 "statusDescription": ""
1958             }
1959         }
1960         job_info_task = {
1961             "jobId": "task_id",
1962             "responseDescriptor": {
1963                 "status": JOB_MODEL_STATUS.FINISHED,
1964                 "progress": 100,
1965                 "responseId": 1,
1966                 "statusDescription": "already onBoarded"
1967             }
1968         }
1969         mock_vals = {
1970             "/api/nslcm/v1/vnfpackage":
1971                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1972             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_1", 0):
1973                 [0, json.JSONEncoder().encode(job_info_1), "200"],
1974             "/api/nslcm/v1/ns/ns_vnfs":
1975                 [0, json.JSONEncoder().encode({"jobId": "test_2", "vnfInstId": ""}), "200"],
1976             "/api/nslcm/v1/jobs/%s?responseId=%s" % ("test_2", 0):
1977                 [0, json.JSONEncoder().encode(job_info_2), "200"],
1978             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks":
1979                 [0, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1980             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s?responseId=%s" % ("task_id", 0):
1981                 [0, json.JSONEncoder().encode(job_info_task), "200"],
1982             "/openapi/vnfsdk/v1/functest/taskmanager/testtasks/%s/result" % "task_id":
1983                 [1, json.JSONEncoder().encode({"TaskID": "task_id"}), "200"],
1984         }
1985
1986         def side_effect(*args):
1987             return mock_vals[args[4]]
1988
1989         mock_call_req.side_effect = side_effect
1990         VerifyVnfs(self.data, self.job_id).run()
1991         self.assertEqual(JobModel.objects.get(jobid=self.job_id).progress, JOB_PROGRESS.ERROR)
1992
1993
1994 class TestLcmNotifyViews(TestCase):
1995     def setUp(self):
1996         self.client = Client()
1997         self.data = {
1998             "status": "START",
1999             "operation": "Instantiate",
2000             "jobId": "",
2001             "vnfdmodule": "",
2002             "affectedVnfc": [{"vnfcInstanceId": "vnfc_instance_id",
2003                               "vduId": "vdu_id",
2004                               "changeType": VNFC_CHANGE_TYPE.ADDED,
2005                               "vimId": "vim_id",
2006                               "vmId": "vm_id",
2007                               "vmName": "vm_name"
2008                               }],
2009             "affectedVl": [{"vlInstanceId": "vl_instance_id",
2010                             "vldId": "vld_id",
2011                             "changeType": VNFC_CHANGE_TYPE.ADDED,
2012                             "networkResource": {
2013                                 "resourceType": NETWORK_RESOURCE_TYPE.NETWORK,
2014                                 "resourceId": "resource_id",
2015                                 "resourceName": "resource_name"
2016                             }
2017                             }],
2018             "affectedCp": [{"changeType": VNFC_CHANGE_TYPE.ADDED,
2019                             "virtualLinkInstanceId": "virtual_link_instance_id",
2020                             "cpInstanceId": "cp_instance_id",
2021                             "cpdId": "cpd_id",
2022                             "ownerType": 0,
2023                             "ownerId": "owner_id",
2024                             "portResource": {
2025                                 "vimId": "vim_id",
2026                                 "resourceId": "resource_id",
2027                                 "resourceName": "resource_name",
2028                                 "tenant": "tenant",
2029                                 "ipAddress": "ip_address",
2030                                 "macAddress": "mac_address",
2031                                 "instId": "inst_id"
2032                             }
2033                             }],
2034             "affectedVirtualStorage": [{}]
2035         }
2036         self.nf_inst_id = "test_lcm_notify"
2037         self.m_nf_inst_id = "test_lcm_notify_m_nf_inst_id"
2038         self.vnfm_inst_id = "test_lcm_notify_vnfm_inst_id"
2039         self.vnfd_model = {"metadata": {"vnfdId": "1"}}
2040         self.url = "/api/nslcm/v1/ns/%s/vnfs/%s/Notify" % (self.m_nf_inst_id, self.vnfm_inst_id)
2041         NfInstModel.objects.all().delete()
2042         NfInstModel.objects.create(nfinstid=self.nf_inst_id,
2043                                    vnfm_inst_id=self.vnfm_inst_id,
2044                                    status=VNF_STATUS.NULL,
2045                                    mnfinstid=self.m_nf_inst_id,
2046                                    vnfd_model=self.vnfd_model
2047                                    )
2048
2049     def tearDown(self):
2050         NfInstModel.objects.all().delete()
2051         VNFCInstModel.objects.all().delete()
2052         VmInstModel.objects.all().delete()
2053         VLInstModel.objects.all().delete()
2054         PortInstModel.objects.all().delete()
2055         CPInstModel.objects.all().delete()
2056
2057     def test_lcm_notify_view_when_change_type_is_added(self):
2058         NotifyLcm(self.vnfm_inst_id, self.m_nf_inst_id, self.data).do_biz()
2059         vnfc_inst = VNFCInstModel.objects.get(vnfcinstanceid="vnfc_instance_id", vduid="vdu_id", vmid="vm_id",
2060                                               nfinstid=self.nf_inst_id)
2061         self.assertIsInstance(vnfc_inst, VNFCInstModel)
2062         vm_inst = VmInstModel.objects.get(vmid="vm_id", vimid="vim_id", resouceid="vm_id", insttype=INST_TYPE.VNF,
2063                                           instid=self.nf_inst_id, vmname="vm_name", hostid='1')
2064         self.assertIsInstance(vm_inst, VmInstModel)
2065         vl_inst = VLInstModel.objects.get(vlinstanceid="vl_instance_id", vldid="vld_id", vlinstancename="resource_name",
2066                                           ownertype=0, ownerid=self.nf_inst_id, relatednetworkid="resource_id",
2067                                           vltype=0)
2068         self.assertIsInstance(vl_inst, VLInstModel)
2069         port_inst = PortInstModel.objects.get(networkid='unknown', subnetworkid='unknown', vimid="vim_id",
2070                                               resourceid="resource_id", name="resource_name", instid="inst_id",
2071                                               cpinstanceid="cp_instance_id", bandwidth='unknown',
2072                                               operationalstate='active', ipaddress="ip_address",
2073                                               macaddress='mac_address', floatipaddress='unknown',
2074                                               serviceipaddress='unknown', typevirtualnic='unknown',
2075                                               sfcencapsulation='gre', direction='unknown', tenant="tenant")
2076         self.assertIsInstance(port_inst, PortInstModel)
2077         cp_inst = CPInstModel.objects.get(cpinstanceid="cp_instance_id", cpdid="cpd_id", ownertype=0,
2078                                           ownerid=self.nf_inst_id, relatedtype=2, status='active')
2079         self.assertIsInstance(cp_inst, CPInstModel)
2080
2081     def test_lcm_notify_view__when_change_type_is_added_when_nf_not_exists(self):
2082         NfInstModel.objects.all().delete()
2083         data = {
2084             "status": "START",
2085             "operation": "Instantiate",
2086             "jobId": "",
2087             "vnfdmodule": "",
2088         }
2089         try:
2090             NotifyLcm(self.vnfm_inst_id, self.m_nf_inst_id, data).do_biz()
2091             self.assertEqual(1, 0)
2092         except Exception:
2093             self.assertEqual(1, 1)
2094
2095     def test_lcm_notify_view_when_change_type_is_removeed(self):
2096         VNFCInstModel.objects.create(vnfcinstanceid="vnfc_instance_id")
2097         VLInstModel.objects.create(vlinstanceid="vl_instance_id", ownertype=0)
2098         CPInstModel.objects.create(cpinstanceid="cp_instance_id", cpdid="cpd_id", ownertype=0, ownerid=self.nf_inst_id,
2099                                    relatedtype=2, relatedport="related_port", status="active")
2100         data = {
2101             "status": "START",
2102             "operation": "Instantiate",
2103             "jobId": "",
2104             "vnfdmodule": "",
2105             "affectedVnfc": [{"vnfcInstanceId": "vnfc_instance_id",
2106                               "vduId": "vdu_id",
2107                               "changeType": VNFC_CHANGE_TYPE.REMOVED,
2108                               "vimId": "vim_id",
2109                               "vmId": "vm_id",
2110                               "vmName": "vm_name"
2111                               }],
2112             "affectedVl": [{"vlInstanceId": "vl_instance_id",
2113                             "vldId": "vld_id",
2114                             "changeType": VNFC_CHANGE_TYPE.REMOVED,
2115                             "networkResource": {
2116                                 "resourceType": NETWORK_RESOURCE_TYPE.NETWORK,
2117                                 "resourceId": "resource_id",
2118                                 "resourceName": "resource_name"
2119                             }
2120                             }],
2121             "affectedCp": [{"changeType": VNFC_CHANGE_TYPE.REMOVED,
2122                             "virtualLinkInstanceId": "virtual_link_instance_id",
2123                             "cpInstanceId": "cp_instance_id",
2124                             "cpdId": "cpd_id",
2125                             "ownerType": 0,
2126                             "ownerId": "owner_id",
2127                             "portResource": {
2128                                 "vimId": "vim_id",
2129                                 "resourceId": "resource_id",
2130                                 "resourceName": "resource_name",
2131                                 "tenant": "tenant",
2132                                 "ipAddress": "ip_address",
2133                                 "macAddress": "mac_address",
2134                                 "instId": "inst_id"
2135                             }
2136                             }],
2137             "affectedVirtualStorage": [{}]
2138         }
2139         NotifyLcm(self.vnfm_inst_id, self.m_nf_inst_id, data).do_biz()
2140         vnfc_inst = VNFCInstModel.objects.filter(vnfcinstanceid="vnfc_instance_id")
2141         self.assertEqual(len(vnfc_inst), 0)
2142         vl_inst = VLInstModel.objects.filter(vlinstanceid="vl_instance_id")
2143         self.assertEqual(len(vl_inst), 0)
2144         port_inst = PortInstModel.objects.get(networkid='unknown', subnetworkid='unknown', vimid="vim_id",
2145                                               resourceid="resource_id", name="resource_name", instid="inst_id",
2146                                               cpinstanceid="cp_instance_id", bandwidth='unknown',
2147                                               operationalstate='active', ipaddress="ip_address",
2148                                               macaddress='mac_address', floatipaddress='unknown',
2149                                               serviceipaddress='unknown', typevirtualnic='unknown',
2150                                               sfcencapsulation='gre', direction='unknown', tenant="tenant")
2151         self.assertIsInstance(port_inst, PortInstModel)
2152         cp_inst = CPInstModel.objects.filter(cpinstanceid="cp_instance_id")
2153         self.assertEqual(len(cp_inst), 0)
2154
2155     def test_lcm_notify_view_when_change_type_is_modified(self):
2156         VNFCInstModel.objects.create(vnfcinstanceid="vnfc_instance_id")
2157         VLInstModel.objects.create(vlinstanceid="vl_instance_id", ownertype=0)
2158         CPInstModel.objects.create(cpinstanceid="cp_instance_id", cpdid="cpd_id", ownertype=0, ownerid=self.nf_inst_id,
2159                                    relatedtype=2, relatedport="related_port")
2160         data = {
2161             "status": "START",
2162             "operation": "Instantiate",
2163             "jobId": "",
2164             "vnfdmodule": "",
2165             "affectedVnfc": [{"vnfcInstanceId": "vnfc_instance_id",
2166                               "vduId": "vdu_id",
2167                               "changeType": VNFC_CHANGE_TYPE.MODIFIED,
2168                               "vimId": "vim_id",
2169                               "vmId": "vm_id",
2170                               "vmName": "vm_name"
2171                               }],
2172             "affectedVl": [{"vlInstanceId": "vl_instance_id",
2173                             "vldId": "vld_id",
2174                             "changeType": VNFC_CHANGE_TYPE.MODIFIED,
2175                             "networkResource": {
2176                                 "resourceType": NETWORK_RESOURCE_TYPE.NETWORK,
2177                                 "resourceId": "resource_id",
2178                                 "resourceName": "resource_name"
2179                             }
2180                             }],
2181             "affectedCp": [{"changeType": VNFC_CHANGE_TYPE.MODIFIED,
2182                             "virtualLinkInstanceId": "virtual_link_instance_id",
2183                             "cpInstanceId": "cp_instance_id",
2184                             "cpdId": "cpd_id",
2185                             "ownerType": 0,
2186                             "ownerId": "owner_id",
2187                             "portResource": {
2188                                 "vimId": "vim_id",
2189                                 "resourceId": "resource_id",
2190                                 "resourceName": "resource_name",
2191                                 "tenant": "tenant",
2192                                 "ipAddress": "ip_address",
2193                                 "macAddress": "mac_address",
2194                                 "instId": "inst_id"
2195                             }
2196                             }],
2197             "affectedVirtualStorage": [{}]
2198         }
2199         NotifyLcm(self.vnfm_inst_id, self.m_nf_inst_id, data).do_biz()
2200         vnfc_inst = VNFCInstModel.objects.get(vnfcinstanceid="vnfc_instance_id", vduid="vdu_id", vmid="vm_id",
2201                                               nfinstid=self.nf_inst_id)
2202         self.assertIsInstance(vnfc_inst, VNFCInstModel)
2203         vl_inst = VLInstModel.objects.get(vlinstanceid="vl_instance_id", vldid="vld_id", vlinstancename="resource_name",
2204                                           ownertype=0, ownerid=self.nf_inst_id, relatednetworkid="resource_id",
2205                                           vltype=0)
2206         self.assertIsInstance(vl_inst, VLInstModel)
2207         port_inst = PortInstModel.objects.get(networkid='unknown', subnetworkid='unknown', vimid="vim_id",
2208                                               resourceid="resource_id", name="resource_name", instid="inst_id",
2209                                               cpinstanceid="cp_instance_id", bandwidth='unknown',
2210                                               operationalstate='active', ipaddress="ip_address",
2211                                               macaddress='mac_address', floatipaddress='unknown',
2212                                               serviceipaddress='unknown', typevirtualnic='unknown',
2213                                               sfcencapsulation='gre', direction='unknown', tenant="tenant")
2214         self.assertIsInstance(port_inst, PortInstModel)
2215         cp_inst = CPInstModel.objects.get(cpinstanceid="cp_instance_id", cpdid="cpd_id", ownertype=0,
2216                                           ownerid=self.nf_inst_id, relatedtype=2)
2217         self.assertIsInstance(cp_inst, CPInstModel)
2218
2219
2220 class TestVnfNotifyView(TestCase):
2221     def setUp(self):
2222         self.client = Client()
2223         self.nf_inst_id = "test_vnf_notify"
2224         self.m_nf_inst_id = "test_vnf_notify_m_nf_inst_id"
2225         self.vnfm_inst_id = "test_vnf_notify_vnfm_inst_id"
2226         self.vnfd_model = {"metadata": {"vnfdId": "1"}}
2227         self.url = "/api/nslcm/v2/ns/%s/vnfs/%s/Notify" % (self.vnfm_inst_id, self.m_nf_inst_id)
2228         self.data = {
2229             "id": "1111",
2230             "notificationType": "VnfLcmOperationOccurrenceNotification",
2231             "subscriptionId": "1111",
2232             "timeStamp": "1111",
2233             "notificationStatus": "START",
2234             "operationState": "STARTING",
2235             "vnfInstanceId": self.nf_inst_id,
2236             "operation": "INSTANTIATE",
2237             "isAutomaticInvocation": "1111",
2238             "vnfLcmOpOccId": "1111",
2239             "affectedVnfcs": [{"id": "vnfc_instance_id",
2240                               "vduId": "vdu_id",
2241                                "changeType": VNFC_CHANGE_TYPE.ADDED,
2242                                "computeResource": {
2243                                   "vimConnectionId": "vim_connection_id",
2244                                   "resourceId": "resource_id"
2245                                }
2246                                }],
2247             "affectedVirtualLinks": [{"id": "vl_instance_id",
2248                                       "virtualLinkDescId": "virtual_link_desc_id",
2249                                       "changeType": VNFC_CHANGE_TYPE.ADDED,
2250                                       "networkResource": {
2251                                           "vimLevelResourceType": "network",
2252                                           "resourceId": "resource_id"
2253                                       }}],
2254             "changedExtConnectivity": [{"id": "virtual_link_instance_id",
2255                                         "extLinkPorts": [{"cpInstanceId": "cp_instance_id",
2256                                                           "id": "cpd_id",
2257                                                           "resourceHandle": {
2258                                                               "vimConnectionId": "vim_connection_id",
2259                                                               "resourceId": "resource_id",
2260                                                               "resourceProviderId": "resourceProviderId",
2261                                                               "tenant": "tenant",
2262                                                               "ipAddress": "ipAddress",
2263                                                               "macAddress": "macAddress",
2264                                                               "instId": "instId",
2265                                                               "networkId": "networkId",
2266                                                               "subnetId": "subnetId"
2267                                                           }
2268                                                           }],
2269                                         }]
2270         }
2271         NfInstModel.objects.all().delete()
2272         VNFCInstModel.objects.all().delete()
2273         VmInstModel.objects.all().delete()
2274         NfInstModel.objects.create(nfinstid=self.nf_inst_id,
2275                                    vnfm_inst_id=self.vnfm_inst_id,
2276                                    status=VNF_STATUS.NULL,
2277                                    mnfinstid=self.m_nf_inst_id,
2278                                    vnfd_model=self.vnfd_model
2279                                    )
2280
2281     def tearDown(self):
2282         NfInstModel.objects.all().delete()
2283         VNFCInstModel.objects.all().delete()
2284         VmInstModel.objects.all().delete()
2285         VLInstModel.objects.all().delete()
2286         PortInstModel.objects.all().delete()
2287         CPInstModel.objects.all().delete()
2288
2289     def test_handle_vnf_lcm_ooc_notification_when_change_type_is_added(self):
2290         # response = self.client.post(self.url, data=self.data)
2291         HandleVnfLcmOocNotification(self.vnfm_inst_id, self.m_nf_inst_id, self.data).do_biz()
2292         vnfc_inst = VNFCInstModel.objects.get(vnfcinstanceid="vnfc_instance_id", vduid="vdu_id",
2293                                               nfinstid=self.nf_inst_id, vmid="resource_id")
2294         self.assertIsInstance(vnfc_inst, VNFCInstModel)
2295         vm_inst = VmInstModel.objects.get(vmid="resource_id", vimid="vim_connection_id", resouceid="resource_id",
2296                                           insttype=INST_TYPE.VNF, instid=self.nf_inst_id, vmname="resource_id",
2297                                           hostid='1')
2298         self.assertIsInstance(vm_inst, VmInstModel)
2299         vl_inst = VLInstModel.objects.get(vlinstanceid="vl_instance_id", vldid="virtual_link_desc_id",
2300                                           vlinstancename="resource_id", ownertype=0, ownerid=self.nf_inst_id,
2301                                           relatednetworkid="resource_id", vltype=0)
2302         self.assertIsInstance(vl_inst, VLInstModel)
2303         port_inst = PortInstModel.objects.get(networkid='networkId', subnetworkid='subnetId', vimid="vim_connection_id",
2304                                               resourceid="resource_id", name="resourceProviderId", instid="instId",
2305                                               cpinstanceid="cp_instance_id", bandwidth='unknown',
2306                                               operationalstate='active', ipaddress="ipAddress", macaddress='macAddress',
2307                                               floatipaddress='unknown', serviceipaddress='unknown',
2308                                               typevirtualnic='unknown', sfcencapsulation='gre', direction='unknown',
2309                                               tenant="tenant")
2310         self.assertIsInstance(port_inst, PortInstModel)
2311         cp_inst = CPInstModel.objects.get(cpinstanceid="cp_instance_id", cpdid="cpd_id", ownertype=0,
2312                                           ownerid=self.nf_inst_id, relatedtype=2, status='active')
2313         self.assertIsInstance(cp_inst, CPInstModel)
2314
2315     def test_handle_vnf_lcm_ooc_notification_when_change_type_is_added_when_nf_not_exists(self):
2316         data = {
2317             "id": "1111",
2318             "notificationType": "VnfLcmOperationOccurrenceNotification",
2319             "subscriptionId": "1111",
2320             "timeStamp": "1111",
2321             "notificationStatus": "START",
2322             "operationState": "STARTING",
2323             "vnfInstanceId": "nf_not_exists",
2324             "operation": "INSTANTIATE",
2325             "isAutomaticInvocation": "1111",
2326             "vnfLcmOpOccId": "1111"
2327         }
2328         try:
2329             HandleVnfLcmOocNotification(self.vnfm_inst_id, self.m_nf_inst_id, data).do_biz()
2330             self.assertEqual(1, 0)
2331         except Exception:
2332             self.assertEqual(1, 1)
2333
2334     def test_handle_vnf_lcm_ooc_notification_when_change_type_is_removed(self):
2335         VNFCInstModel.objects.create(vnfcinstanceid="vnfc_instance_id")
2336         VLInstModel.objects.create(vlinstanceid="vl_instance_id", ownertype=0)
2337         data = {
2338             "id": "1111",
2339             "notificationType": "VnfLcmOperationOccurrenceNotification",
2340             "subscriptionId": "1111",
2341             "timeStamp": "1111",
2342             "notificationStatus": "START",
2343             "operationState": "STARTING",
2344             "vnfInstanceId": self.nf_inst_id,
2345             "operation": "INSTANTIATE",
2346             "isAutomaticInvocation": "1111",
2347             "vnfLcmOpOccId": "1111",
2348             "affectedVnfcs": [{"id": "vnfc_instance_id",
2349                                "vduId": "vdu_id",
2350                                "changeType": VNFC_CHANGE_TYPE.REMOVED,
2351                                "computeResource": {
2352                                    "vimConnectionId": "vim_connection_id",
2353                                    "resourceId": "resource_id"
2354                                }}],
2355             "affectedVirtualLinks": [{"id": "vl_instance_id",
2356                                       "virtualLinkDescId": "virtual_link_desc_id",
2357                                       "changeType": VNFC_CHANGE_TYPE.REMOVED,
2358                                       "networkResource": {
2359                                           "vimLevelResourceType": "network",
2360                                           "resourceId": "resource_id"
2361                                       }}]
2362         }
2363         HandleVnfLcmOocNotification(self.vnfm_inst_id, self.m_nf_inst_id, data).do_biz()
2364         vnfc_inst = VNFCInstModel.objects.filter(vnfcinstanceid="vnfc_instance_id")
2365         self.assertEqual(len(vnfc_inst), 0)
2366         vl_inst = VLInstModel.objects.filter(vlinstanceid="vl_instance_id")
2367         self.assertEqual(len(vl_inst), 0)
2368
2369     def test_handle_vnf_lcm_ooc_notification_when_change_type_is_modified(self):
2370         VNFCInstModel.objects.create(vnfcinstanceid="vnfc_instance_id")
2371         VLInstModel.objects.create(vlinstanceid="vl_instance_id", ownertype=0)
2372         data = {
2373             "id": "1111",
2374             "notificationType": "VnfLcmOperationOccurrenceNotification",
2375             "subscriptionId": "1111",
2376             "timeStamp": "1111",
2377             "notificationStatus": "START",
2378             "operationState": "STARTING",
2379             "vnfInstanceId": self.nf_inst_id,
2380             "operation": "INSTANTIATE",
2381             "isAutomaticInvocation": "1111",
2382             "vnfLcmOpOccId": "1111",
2383             "affectedVnfcs": [{"id": "vnfc_instance_id",
2384                                "vduId": "vdu_id",
2385                                "changeType": VNFC_CHANGE_TYPE.MODIFIED,
2386                                "computeResource": {
2387                                    "vimConnectionId": "vim_connection_id",
2388                                    "resourceId": "resource_id"
2389                                }}],
2390             "affectedVirtualLinks": [{"id": "vl_instance_id",
2391                                       "virtualLinkDescId": "virtual_link_desc_id",
2392                                       "changeType": VNFC_CHANGE_TYPE.MODIFIED,
2393                                       "networkResource": {
2394                                           "vimLevelResourceType": "network",
2395                                           "resourceId": "resource_id"
2396                                       }}],
2397             "changedExtConnectivity": [{"id": "virtual_link_instance_id",
2398                                         "extLinkPorts": [{"cpInstanceId": "cp_instance_id",
2399                                                           "id": "cpd_id",
2400                                                           "resourceHandle": {
2401                                                               "vimConnectionId": "vim_connection_id",
2402                                                               "resourceId": "resource_id",
2403                                                               "resourceProviderId": "resourceProviderId",
2404                                                               "tenant": "tenant",
2405                                                               "ipAddress": "ipAddress",
2406                                                               "macAddress": "macAddress",
2407                                                               "instId": "instId",
2408                                                               "networkId": "networkId",
2409                                                               "subnetId": "subnetId"
2410                                                           }
2411                                                           }],
2412                                         }]
2413         }
2414         HandleVnfLcmOocNotification(self.vnfm_inst_id, self.m_nf_inst_id, data).do_biz()
2415         vnfc_inst = VNFCInstModel.objects.get(vnfcinstanceid="vnfc_instance_id", vduid="vdu_id",
2416                                               nfinstid=self.nf_inst_id, vmid="resource_id")
2417         self.assertIsInstance(vnfc_inst, VNFCInstModel)
2418         vl_inst = VLInstModel.objects.get(vlinstanceid="vl_instance_id", vldid="virtual_link_desc_id",
2419                                           vlinstancename="resource_id", ownertype=0, ownerid=self.nf_inst_id,
2420                                           relatednetworkid="resource_id", vltype=0)
2421         self.assertIsInstance(vl_inst, VLInstModel)
2422         port_inst = PortInstModel.objects.get(networkid='networkId', subnetworkid='subnetId', vimid="vim_connection_id",
2423                                               resourceid="resource_id", name="resourceProviderId", instid="instId",
2424                                               cpinstanceid="cp_instance_id", bandwidth='unknown',
2425                                               operationalstate='active', ipaddress="ipAddress", macaddress='macAddress',
2426                                               floatipaddress='unknown', serviceipaddress='unknown',
2427                                               typevirtualnic='unknown', sfcencapsulation='gre', direction='unknown',
2428                                               tenant="tenant")
2429         self.assertIsInstance(port_inst, PortInstModel)
2430         cp_inst = CPInstModel.objects.get(cpinstanceid="cp_instance_id", cpdid="cpd_id", ownertype=0,
2431                                           ownerid=self.nf_inst_id, relatedtype=2, status='active')
2432         self.assertIsInstance(cp_inst, CPInstModel)
2433
2434     def test_handle_vnf_identifier_creation_notification(self):
2435         vnfm_id = "vnfm_id"
2436         vnf_instance_id = "vnf_instance_id"
2437         data = {
2438             "timeStamp": "20190809",
2439         }
2440         HandleVnfIdentifierCreationNotification(vnfm_id, vnf_instance_id, data).do_biz()
2441         nf_inst = NfInstModel.objects.get(mnfinstid=vnf_instance_id, vnfm_inst_id=vnfm_id, create_time="20190809")
2442         self.assertIsInstance(nf_inst, NfInstModel)
2443
2444     def test_handle_vnf_identifier_deletion_notification(self):
2445         nf_inst_id = "nf_inst_id"
2446         vnfm_id = "vnfm_id"
2447         vnf_instance_id = "vnf_instance_id"
2448         NfInstModel.objects.create(nfinstid=nf_inst_id,
2449                                    vnfm_inst_id=vnfm_id,
2450                                    status=VNF_STATUS.NULL,
2451                                    mnfinstid=vnf_instance_id,
2452                                    vnfd_model=self.vnfd_model
2453                                    )
2454         data = {
2455             "timeStamp": "20190809",
2456         }
2457         HandleVnfIdentifierDeletionNotification(vnfm_id, vnf_instance_id, data).do_biz()
2458         nf_inst = NfInstModel.objects.filter(mnfinstid=vnf_instance_id, vnfm_inst_id=vnfm_id)
2459         self.assertEqual(len(nf_inst), 0)
2460
2461     def test_handle_vnf_identifier_deletion_notification_when_nf_not_exists(self):
2462         NfInstModel.objects.all().delete()
2463         vnfm_id = "nf_not_exists"
2464         vnf_instance_id = "nf_not_exists"
2465         data = {
2466             "timeStamp": "20190809",
2467         }
2468         try:
2469             HandleVnfIdentifierDeletionNotification(vnfm_id, vnf_instance_id, data).do_biz()
2470             self.assertEqual(1, 0)
2471         except Exception:
2472             self.assertEqual(1, 1)
2473
2474     @mock.patch.object(restcall, "call_req")
2475     def test_handle_vnf_identifier_notification_when_save_ip_aai(self, mock_call_req):
2476         l_interface_info_aai = {
2477             "interface-name": "resourceProviderId",
2478             "is-port-mirrored": False,
2479             "resource-version": "1589506153510",
2480             "in-maint": False,
2481             "is-ip-unnumbered": False
2482         }
2483         l3_interface_ipv4_address_list = {
2484             "l3-interface-ipv4-address": "ipAddress",
2485             "resource-version": "1589527363970"
2486         }
2487         mock_vals = {
2488             "/network/generic-vnfs/generic-vnf/%s/l-interfaces/l-interface/%s"
2489             % ("test_vnf_notify", "resourceProviderId"):
2490                 [0, json.JSONEncoder().encode(l_interface_info_aai), "200"],
2491             "/network/generic-vnfs/generic-vnf/%s/l-interfaces/l-interface/%s/l3-interface-ipv4-address-list/%s"
2492             % ("test_vnf_notify", "resourceProviderId", "ipAddress"):
2493                 [0, json.JSONEncoder().encode(l3_interface_ipv4_address_list), "200"],
2494             "/network/l3-networks/l3-network/%s" % "vl_instance_id":
2495                 [0, json.JSONEncoder().encode({}), "200"],
2496
2497         }
2498
2499         def side_effect(*args):
2500             return mock_vals[args[4]]
2501
2502         mock_call_req.side_effect = side_effect
2503
2504         data = {
2505             "id": "1111",
2506             "notificationType": "VnfLcmOperationOccurrenceNotification",
2507             "subscriptionId": "1111",
2508             "timeStamp": "1111",
2509             "notificationStatus": "START",
2510             "operationState": "STARTING",
2511             "vnfInstanceId": self.nf_inst_id,
2512             "operation": "INSTANTIATE",
2513             "isAutomaticInvocation": "1111",
2514             "vnfLcmOpOccId": "1111",
2515             "affectedVnfcs": [{"id": "vnfc_instance_id",
2516                                "vduId": "vdu_id",
2517                                "changeType": VNFC_CHANGE_TYPE.MODIFIED,
2518                                "computeResource": {
2519                                    "vimConnectionId": "vim_connection_id",
2520                                    "resourceId": "resource_id"
2521                                }}],
2522             "affectedVirtualLinks": [{"id": "vl_instance_id",
2523                                       "virtualLinkDescId": "virtual_link_desc_id",
2524                                       "changeType": VNFC_CHANGE_TYPE.MODIFIED,
2525                                       "networkResource": {
2526                                           "vimLevelResourceType": "network",
2527                                           "resourceId": "resource_id"
2528                                       }}],
2529             "changedExtConnectivity": [{"id": "virtual_link_instance_id",
2530                                         "extLinkPorts": [{"cpInstanceId": "cp_instance_id",
2531                                                           "id": "cpd_id",
2532                                                           "resourceHandle": {
2533                                                               "vimConnectionId": "vim_connection_id",
2534                                                               "resourceId": "resource_id",
2535                                                               "resourceProviderId": "resourceProviderId",
2536                                                               "tenant": "tenant",
2537                                                               "ipAddress": "ipAddress",
2538                                                               "macAddress": "macAddress",
2539                                                               "instId": "instId",
2540                                                               "networkId": "networkId",
2541                                                               "subnetId": "subnetId"
2542                                                           }
2543                                                           }],
2544                                         "changeType": VNFC_CHANGE_TYPE.MODIFIED
2545                                         }]
2546         }
2547         HandleVnfLcmOocNotification(self.vnfm_inst_id, self.m_nf_inst_id, data).do_biz()
2548         url = '/api/nslcm/v2/ns/%s/vnfs/%s/Notify' % (self.vnfm_inst_id, self.m_nf_inst_id)
2549         response = self.client.post(url, data)
2550         self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code, response.content)