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