Modify code and test case of vnflcm and adaptor
[vfc/gvnfm/vnflcm.git] / lcm / lcm / nf / vnfs / tests / test_vnf_create.py
1 # Copyright 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
17 import mock
18 from django.test import TestCase, Client
19 from rest_framework import status
20
21 from lcm.nf.vnfs.const import vnfd_rawdata
22 from lcm.nf.vnfs.vnf_create.inst_vnf import InstVnf
23 from lcm.pub.database.models import NfInstModel, JobStatusModel, VmInstModel, NetworkInstModel, \
24     SubNetworkInstModel, PortInstModel
25 from lcm.pub.utils import restcall
26 from lcm.pub.utils.jobutil import JobUtil
27 from lcm.pub.utils.timeutil import now_time
28 from lcm.pub.vimapi import adaptor
29 from lcm.pub.vimapi import api
30
31
32 class TestNFInstantiate(TestCase):
33     def setUp(self):
34         self.client = Client()
35         VmInstModel.objects.create(vmid="1", vimid="1", resouceid="11", insttype=0, instid="1", vmname="test_01",
36                                    operationalstate=1)
37         VmInstModel.objects.create(vmid="2", vimid="2", resouceid="22", insttype=0, instid="2",
38                                    vmname="test_02", operationalstate=1)
39         NetworkInstModel.objects.create(networkid='1', vimid='1', resouceid='1', name='pnet_network',
40                                         tenant='admin', insttype=0, instid='1')
41         SubNetworkInstModel.objects.create(subnetworkid='1', vimid='1', resouceid='1', networkid='1',
42                                            name='sub_pnet', tenant='admin', insttype=0, instid='1')
43         PortInstModel.objects.create(portid='1', networkid='1', subnetworkid='1', vimid='1', resouceid='1',
44                                      name='aaa_pnet_cp', tenant='admin', insttype=0, instid='1')
45
46     def tearDown(self):
47         pass
48         VmInstModel.objects.all().delete()
49         NetworkInstModel.objects.all().delete()
50         SubNetworkInstModel.objects.all().delete()
51         PortInstModel.objects.all().delete()
52
53     def assert_job_result(self, job_id, job_progress, job_detail):
54         jobs = JobStatusModel.objects.filter(
55             jobid=job_id,
56             progress=job_progress,
57             descp=job_detail)
58         self.assertEqual(1, len(jobs))
59
60     def test_swagger_ok(self):
61         response = self.client.get("/openoapi/vnflcm/v1/swagger.json", format='json')
62         self.assertEqual(response.status_code, status.HTTP_200_OK)
63
64     @mock.patch.object(restcall, 'call_req')
65     def test_create_vnf_identifier(self, mock_call_req):
66         r1 = [0, json.JSONEncoder().encode({'package_id':'222', 'csar_id':'2222'}), '200']  # get csar_id from nslcm by vnfd_id
67         r2 = [0, json.JSONEncoder().encode(vnfd_rawdata), '200']  # get rawdata from catalog by csar_id
68         mock_call_req.side_effect = [r1, r2]
69         data = {
70             "vnfdId": "111",
71             "vnfInstanceName": "vFW_01",
72             "vnfInstanceDescription": "vFW in Nanjing TIC Edge"}
73         response = self.client.post("/openoapi/vnflcm/v1/vnf_instances", data=data, format='json')
74         self.failUnlessEqual(status.HTTP_201_CREATED, response.status_code)
75         context = json.loads(response.content)
76         self.assertTrue(NfInstModel.objects.filter(nfinstid=context['vnfInstanceId']).exists())
77
78     @mock.patch.object(InstVnf, 'run')
79     def test_instantiate_vnf(self, mock_run):
80         mock_run.re.return_value = None
81         response = self.client.post("/openoapi/vnflcm/v1/vnf_instances/12/instantiate", data={}, format='json')
82         self.failUnlessEqual(status.HTTP_202_ACCEPTED, response.status_code)
83
84     def test_instantiate_vnf_when_inst_id_not_exist(self):
85         self.nf_inst_id = str(uuid.uuid4())
86         self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id)
87         JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY")
88         jobs = JobStatusModel.objects.filter(
89             jobid=self.job_id,
90             progress=0,
91             descp="INST_VNF_READY")
92         self.assertEqual(1, len(jobs))
93         data = inst_req_data
94         InstVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
95         self.assert_job_result(self.job_id, 255, "VNF nf_inst_id is not exist.")
96
97     @mock.patch.object(restcall, 'call_req')
98     def test_instantiate_vnf_when_get_package_info_by_vnfdid_failed(self, mock_call_req):
99         NfInstModel.objects.create(nfinstid='1111', nf_name='vFW_01', package_id='222',
100                                    version='', vendor='', netype='', vnfd_model='', status='NOT_INSTANTIATED',
101                                    nf_desc='vFW in Nanjing TIC Edge', vnfdid='111', create_time=now_time())
102         r1 = [1, json.JSONEncoder().encode({'package_id':'222', 'csar_id':'2222'}), '200']  # get csar_id from nslcm by vnfd_id
103         mock_call_req.side_effect = [r1]
104         self.nf_inst_id = '1111'
105         self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id)
106         JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY")
107         data = inst_req_data
108         InstVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
109         self.assert_job_result(self.job_id, 255, "Failed to query package_info of vnfdid(111) from nslcm.")
110
111     @mock.patch.object(restcall, 'call_req')
112     def test_instantiate_vnf_when_get_rawdata_by_csarid_failed(self, mock_call_req):
113         NfInstModel.objects.create(nfinstid='1111', nf_name='vFW_01', package_id='222',
114                                    version='', vendor='', netype='', vnfd_model='', status='NOT_INSTANTIATED',
115                                    nf_desc='vFW in Nanjing TIC Edge', vnfdid='111', create_time=now_time())
116         r1 = [0, json.JSONEncoder().encode({'package_id':'222', 'csar_id':'2222'}), '200']  # get csar_id from nslcm by vnfd_id
117         r2 = [1, json.JSONEncoder().encode(vnfd_rawdata), '200']  # get rawdata from catalog by csar_id
118         mock_call_req.side_effect = [r1, r2]
119         self.nf_inst_id = '1111'
120         self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id)
121         JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY")
122         data = inst_req_data
123         InstVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
124         self.assert_job_result(self.job_id, 255, "Failed to query rawdata of CSAR(2222) from catalog.")
125
126     @mock.patch.object(restcall, 'call_req')
127     def test_instantiate_vnf_when_applay_grant_failed(self, mock_call_req):
128         NfInstModel.objects.create(nfinstid='1111', nf_name='vFW_01', package_id='222',
129                                    version='', vendor='', netype='', vnfd_model='', status='NOT_INSTANTIATED',
130                                    nf_desc='vFW in Nanjing TIC Edge', vnfdid='111', create_time=now_time())
131         r1 = [0, json.JSONEncoder().encode({'package_id': '222', 'csar_id': '2222'}), '200']  # get csar_id from nslcm by vnfd_id
132         r2 = [0, json.JSONEncoder().encode(vnfd_rawdata), '200']  # get rawdata from catalog by csar_id
133         r3 = [1, json.JSONEncoder().encode({"vim":
134                                                 {
135                                                     "vimid": '1',
136                                                     "accessinfo": {"tenant": '2'}
137                                                  }
138                                             }), '200']  # apply_grant_to_nfvo
139         mock_call_req.side_effect = [r1, r2, r3]
140         self.nf_inst_id = '1111'
141         self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id)
142         JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY")
143         data = inst_req_data
144         InstVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
145         self.assert_job_result(self.job_id, 255, "Nf instancing apply grant exception")
146
147     @mock.patch.object(restcall, 'call_req')
148     @mock.patch.object(api, 'call')
149     def test_instantiate_vnf_when_(self, mock_call, mock_call_req):
150         NfInstModel.objects.create(nfinstid='1111', nf_name='vFW_01', package_id='222',
151                                    version='', vendor='', netype='', vnfd_model='', status='NOT_INSTANTIATED',
152                                    nf_desc='vFW in Nanjing TIC Edge', vnfdid='111', create_time=now_time())
153         r1 = [0, json.JSONEncoder().encode({'package_id': '222', 'csar_id': '2222'}), '200']  # get csar_id from nslcm by vnfd_id
154         r2 = [0, json.JSONEncoder().encode(vnfd_rawdata), '200']  # get rawdata from catalog by csar_id
155         r3 = [0, json.JSONEncoder().encode({"vim":{"vimid": '1', "accessinfo": {"tenant": '2'}}}), '200']  # apply_grant_to_nfvo
156         mock_call_req.side_effect = [r1, r2, r3]
157         c1_data = {  # get_tenant_id
158             "tenants": [
159                 {
160                     "id": "1",
161                     "name": "tenantname_1"
162                 }
163             ]
164         }
165         c2_data = {
166             "returnCode": 0,
167             "vimId": "11111",
168             "vimName": "11111",
169             "status": "ACTIVE",
170             "id": "3c9eebdbbfd345658269340b9ea6fb73",
171             "name": "net1",
172             "tenantId": "tenant1",
173             "networkName": "ommnet",
174             "shared": 1,
175             "vlanTransparent": 1,
176             "networkType": "vlan",
177             "segmentationId": 202,
178             "physicalNetwork": "ctrl",
179             "routerExternal": 0
180         }
181         c3_data = {  # get_volume
182             "status": "available11",
183             "name": "wangsong",
184             "attachments": [
185                 {
186                     "device": "/dev/vdc",
187                     "serverId": "3030e666-528e-4954-88f5-cc21dab1262b",
188                     "volumeId": "4bd3e9eb-cd8b-456a-8589-910836a0ab31",
189                     "hostName": None,
190                     "id": "4bd3e9eb-cd8b-456a-8589-910836a0ab31"
191                 }
192             ],
193             "createTime": "2015-12-02T06:39:40.000000",
194             "type": None,
195             "id": "4bd3e9eb-cd8b-456a-8589-910836a0ab31",
196             "size": 40
197         }
198         mock_call.side_effect = [c1_data, c2_data, c3_data]
199
200         self.nf_inst_id = '1111'
201         self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id)
202         JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY")
203         data = inst_req_data
204         InstVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
205         self.assert_job_result(self.job_id, 255, "unexpected exception")
206
207
208
209
210
211
212     @mock.patch.object(restcall, 'call_req')
213     @mock.patch.object(api, 'call')
214     def test_instantiate_vnf_when_111(self, mock_call, mock_call_req):
215         NfInstModel.objects.create(nfinstid='1111', nf_name='vFW_01', package_id='222',
216                                    version='', vendor='', netype='', vnfd_model='', status='NOT_INSTANTIATED',
217                                    nf_desc='vFW in Nanjing TIC Edge', vnfdid='111', create_time=now_time())
218         r1 = [0, json.JSONEncoder().encode({'package_id': '222', 'csar_id': '2222'}),
219               '200']  # get csar_id from nslcm by vnfd_id
220         r2 = [0, json.JSONEncoder().encode(vnfd_rawdata), '200']  # get rawdata from catalog by csar_id
221         r3 = [0, json.JSONEncoder().encode({"vim": {"vimid": 'vimid_1', "accessinfo": {"tenant": 'tenantname_1'}}}),
222               '200']  # apply_grant_to_nfvo
223         mock_call_req.side_effect = [r1, r2, r3]
224         c1_data_get_tenant_id = {  # get_tenant_id
225             "tenants": [
226                 {
227                     "id": "1",
228                     "name": "tenantname_1"
229                 }
230             ]
231         }
232         c2_data_create_volume = {
233             "id": "4bd3e9eb-cd8b-456a-8589-910836a0ab31",
234             "name": "volume1",
235             "returnCode": 1,
236             "vimId": "vim_volume_1",
237             "vimName": "vim_volume_1",
238             "tenantId": "vim_volume_1",
239             "volumeType": "123",
240             "availabilityZone": "availabilityZone",
241             "status": "availuable",
242             "createTime": "2015-12-02T06:39:40.000000",
243             "type": None,
244             "size": 40
245         }
246         c3_data_get_volume = {  # get_volume
247             "status": "available",
248             "name": "wangsong",
249             "attachments": [
250                 {
251                     "device": "/dev/vdc",
252                     "serverId": "3030e666-528e-4954-88f5-cc21dab1262b",
253                     "volumeId": "4bd3e9eb-cd8b-456a-8589-910836a0ab31",
254                     "hostName": None,
255                     "id": "4bd3e9eb-cd8b-456a-8589-910836a0ab31"
256                 }
257             ],
258             "createTime": "2015-12-02T06:39:40.000000",
259             "type": None,
260             "id": "4bd3e9eb-cd8b-456a-8589-910836a0ab31",
261             "size": 40
262         }
263         c4_data_create_network = {  # create_network
264             "returnCode": 0,
265             "vimId": "11111",
266             "vimName": "11111",
267             "status": "ACTIVE",
268             "id": "3c9eebdbbfd345658269340b9ea6fb73",
269             "name": "net1",
270             "tenantId": "tenant1",
271             "networkName": "ommnet",
272             "shared": True,
273             "vlanTransparent": True,
274             "networkType": "vlan",
275             "segmentationId": 202,
276             "physicalNetwork": "ctrl",
277             "routerExternal": False
278         }
279         c5_data_create_subnet = {
280             "returnCode": 0,
281             "vimId": "11111",
282             "vimName": "11111",
283             "status": " ACTIVE",
284             "id": "d62019d3-bc6e-4319-9c1d-6722fc136a23",
285             "tenantId": "tenant1",
286             "networkId": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
287             "networkName": "networkName",
288             "name": "subnet1",
289             "cidr": "10.43.35.0/24",
290             "ipVersion": 4,
291             "enableDhcp": 1,
292             "gatewayIp": "10.43.35.1",
293             "dnsNameservers": [],
294             "allocationPools": [
295                 {
296                     "start": "192.168.199.2",
297                     "end": "192.168.199.254"
298                 }
299             ],
300             "hostRoutes": []
301         }
302         c6_data_create_port = {
303             "returnCode": 0,
304             "vimId": "11111",
305             "vimName": "11111",
306             "status": " ACTIVE",
307             "id": " 872019d3-bc6e-4319-9c1d-6722fc136afg",
308             "tenantId": "tenant1",
309             "name": "subnet1",
310             "networkId": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
311             "networkName": "networkName",
312             "subnetId": "d62019d3-bc6e-4319-9c1d-6722fc136a23",
313             "subnetName": "subnet1",
314             "macAddress": "212.12.61.23",
315             "ip": "10.43.38.11",
316             "vnicType": "normal",
317             "securityGroups": ""
318         }
319         mock_call.side_effect = [c1_data_get_tenant_id, c2_data_create_volume, c3_data_get_volume,
320                                  c4_data_create_network, c5_data_create_subnet, c6_data_create_port]
321
322         self.nf_inst_id = '1111'
323         self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id)
324         JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY")
325         data = inst_req_data
326         InstVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
327         self.assert_job_result(self.job_id, 255, "unexpected exception")
328
329
330
331
332     # @mock.patch.object(restcall, 'call_req')
333     # # @mock.patch.object(adaptor, 'create_vim_res')
334     # def test_instantiate_vnf_when_create_res_failed(self, mock_call_req):
335     #     NfvoRegInfoModel.objects.create(nfvoid='nfvo111', vnfminstid='vnfm111', apiurl='http://10.74.44.11',
336     #                                     nfvouser='root', nfvopassword='root123')
337     #     r1 = [0, json.JSONEncoder().encode(vnfd_model_dict), '200']
338     #     r2 = [0, json.JSONEncoder().encode(vnfd_model_dict), '200']
339     #     r3 = [0, json.JSONEncoder().encode('Nf instancing apply grant'), '200']
340     #     # r4 = [0, json.JSONEncoder().encode('Nf instancing apply resource'), '200']
341     #     mock_call_req.side_effect = [r1, r2, r3]
342     #     # mock_create_vim_res.re.return_value = None
343     #     create_data = {
344     #         "vnfdId": "111",
345     #         "vnfInstanceName": "vFW_01",
346     #         "vnfInstanceDescription": " vFW in Nanjing TIC Edge"}
347     #     self.nf_inst_id = CreateVnf(create_data).do_biz()
348     #     self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id)
349     #     JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY")
350     #     data = inst_req_data
351     #     InstVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
352     #     self.assert_job_result(self.job_id, 255, "Create resource failed")
353
354     # @mock.patch.object(restcall, 'call_req')
355     # # @mock.patch.object(adaptor, 'create_vim_res')
356     # def test_instantiate_vnf_success(self, mock_call_req):
357     #     NfvoRegInfoModel.objects.create(nfvoid='nfvo111', vnfminstid='vnfm111', apiurl='http://10.74.44.11',
358     #                                     nfvouser='root', nfvopassword='root123')
359     #     r1 = [0, json.JSONEncoder().encode(vnfd_model_dict), '200']
360     #     r2 = [0, json.JSONEncoder().encode(vnfd_model_dict), '200']
361     #     r3 = [0, json.JSONEncoder().encode('Nf instancing apply grant'), '200']
362     #     r4 = [0, json.JSONEncoder().encode('None'), '200']
363     #     mock_call_req.side_effect = [r1, r2, r3, r4]
364     #     # mock_create_vim_res.re.return_value = None
365     #     create_data = {
366     #         "vnfdId": "111",
367     #         "vnfInstanceName": "vFW_01",
368     #         "vnfInstanceDescription": " vFW in Nanjing TIC Edge"}
369     #     self.nf_inst_id = CreateVnf(create_data).do_biz()
370     #     self.job_id = JobUtil.create_job('NF', 'CREATE', self.nf_inst_id)
371     #     JobUtil.add_job_status(self.job_id, 0, "INST_VNF_READY")
372     #     data = inst_req_data
373     #     InstVnf(data, nf_inst_id=self.nf_inst_id, job_id=self.job_id).run()
374     #     self.assert_job_result(self.job_id, 100, "Instantiate Vnf success.")
375
376 inst_req_data = {
377     "flavourId": "flavour_1",
378     "instantiationLevelId": "instantiationLevel_1",
379     "extVirtualLinks": [
380         {
381             "vlInstanceId": "1",
382             "vim": {
383                 "vimInfoId": "1",
384                 "vimId": "1",
385                 "interfaceInfo": {
386                     "vimType": "vim",
387                     "apiVersion": "v2",
388                     "protocolType": "http"
389                 },
390                 "accessInfo": {
391                     "tenant": "tenant_vCPE",
392                     "username": "vCPE",
393                     "password": "vCPE_321"
394                 },
395                 "interfaceEndpoint": "http://10.43.21.105:80/"
396             },
397             "resourceId": "1246",
398             "extCps": [
399                 {
400                     "cpdId": "11",
401                     "addresses": [
402                         {
403                             "addressType": "MAC",
404                             "l2AddressData": "00:f3:43:20:a2:a3"
405                         },
406                         {
407                             "addressType": "IP",
408                             "l3AddressData": {
409                                 "iPAddressType": "IPv4",
410                                 "iPAddress": "192.168.104.2"
411                             }
412                         }
413                     ],
414                     "numDynamicAddresses": 0
415                 }
416             ]
417         }
418     ],
419     "localizationLanguage": "en_US",
420     "additionalParams": {}
421 }