5bf4f40e50b353276e79020a70045709b0c225a5
[so.git] / bpmn / so-bpmn-infrastructure-common / src / test / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeallocateCoreNSSITest.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020  Telecom Italia
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import org.junit.Before
25 import org.junit.Test
26 import org.mockito.Mockito
27 import org.onap.aai.domain.yang.v19.*
28 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
29 import org.onap.aaiclient.client.aai.entities.Relationships
30 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
31 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
32 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
33 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
34 import org.onap.logging.filter.base.ONAPComponents
35 import org.onap.so.bpmn.common.scripts.ExternalAPIUtil
36 import org.onap.so.bpmn.common.scripts.ExternalAPIUtilFactory
37 import org.onap.so.bpmn.common.scripts.MsoGroovyTest
38 import org.onap.so.bpmn.common.scripts.MsoUtils
39 import org.onap.so.bpmn.common.scripts.OofUtils
40 import org.onap.so.client.HttpClient
41 import org.onap.so.client.HttpClientFactory
42 import org.onap.so.serviceinstancebeans.RequestDetails
43
44 import javax.ws.rs.core.Response
45
46 import static org.junit.Assert.assertNotNull
47 import static org.junit.Assert.assertTrue
48 import static org.mockito.Mockito.*
49
50 class DoDeallocateCoreNSSITest extends MsoGroovyTest {
51
52     @Before
53     void init() throws IOException {
54         super.init("DoDeallocateNSSITest")
55     }
56
57
58     @Test
59     void testPreProcessRequest() {
60
61         String nssiId = "5G-999"
62         when(mockExecution.getVariable("serviceInstanceID")).thenReturn(nssiId)
63
64         String nsiId = "5G-777"
65         when(mockExecution.getVariable("nsiId")).thenReturn(nsiId)
66
67         String snssai = "S-NSSAI"
68         String snssaiList = "[ \"${snssai}\" ]"
69         String sliceProfileId = "slice-profile-id"
70         String modifyAction = "allocate"
71         String sliceParams =  "{\n" +
72                 "\"sliceProfileId\":\"${sliceProfileId}\",\"snssaiList\":${snssaiList}\n" +
73                 "}"
74         when(mockExecution.getVariable("sliceParams")).thenReturn(sliceParams)
75
76         DoDeallocateCoreNSSI obj = new DoDeallocateCoreNSSI()
77         obj.preProcessRequest(mockExecution)
78
79         def currentNSSI = [:]
80         currentNSSI.put("nssiId", nssiId)
81         currentNSSI.put("nsiId", nsiId)
82         currentNSSI.put("sliceProfile", sliceParams)
83         currentNSSI.put("S-NSSAI", snssai)
84         currentNSSI.put("sliceProfileId", sliceProfileId)
85         Mockito.verify(mockExecution,times(1)).setVariable("currentNSSI", currentNSSI)
86
87     }
88
89
90     @Test
91     void testExecuteTerminateNSSIQuery() {
92
93         def currentNSSI = [:]
94
95         String nssiId = "5G-999"
96         currentNSSI.put("nssiId", nssiId)
97
98         when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
99
100         when(mockExecution.getVariable("mso.oof.endpoint")).thenReturn("http://oof.onap:8088")
101         when(mockExecution.getVariable("mso.oof.auth")).thenReturn("mso.oof.auth")
102         when(mockExecution.getVariable("mso.msoKey")).thenReturn("mso.msoKey")
103         when(mockExecution.getVariable("mso-request-id")).thenReturn("mso-request-id")
104
105         DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
106         when(spy.getAAIClient()).thenReturn(client)
107
108         OofUtils oofUtilsMock = mock(OofUtils.class)
109         when(spy.getOofUtils()).thenReturn(oofUtilsMock)
110
111         when(spy.encryptBasicAuth("mso.oof.auth", "mso.msoKey")).thenReturn("auth-value")
112
113         String authHeaderResponse =  "auth-header"
114
115       /*  String authHeaderResponse =  "{\n" +
116                 " \"errorCode\": \"401\",\n" +
117                 " \"errorMessage\": \"Bad request\"\n" +
118                 "}" */
119
120         when(spy.getAuthHeader(mockExecution, "auth-value", "mso.msoKey")).thenReturn(authHeaderResponse)
121
122         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
123
124         ServiceInstance nssi = new ServiceInstance()
125         nssi.setServiceInstanceId("5G-999")
126         Optional<ServiceInstance> nssiOpt = Optional.of(nssi)
127
128         when(client.get(ServiceInstance.class, nssiUri)).thenReturn(nssiOpt)
129
130         String urlString = "http://oof.onap:8088"
131
132         String httpRequest =    "{\n" +
133                 "  \"type\": \"NSSI\",\n" +
134                 "  \"NxIId\": \"5G-999\",\n" +
135                 "  \"requestInfo\": {\n" +
136                 "    \"transactionId\": \"mso-request-id\",\n" +
137                 "    \"requestId\": \"mso-request-id\",\n" +
138                 "    \"sourceId\": \"so\",\n" +
139                 "    }\n" +
140                 "}"
141
142         String requestId = "request-id"
143         String nxlId = nssi.getServiceInstanceId()
144         String nxlType = "NSSI"
145         String messageType = "cn"
146         String serviceInstanceId = nssi.getServiceInstanceId()
147
148         when(mockExecution.getVariable("msoRequestId")).thenReturn(requestId)
149         when(oofUtilsMock.buildTerminateNxiRequest(requestId, nxlId, nxlType, messageType, serviceInstanceId)).thenReturn(httpRequest)
150
151         String terminateResponse = "false"
152
153         String oofResponse =   "{\n" +
154                 " \"requestId\": \"mso-request-id\",\n" +
155                 " \"transactionId\": \"mso-request-id\",\n" +
156                 " \"statusMessage\": \"\",\n" +
157                 " \"requestStatus\": \"accepted\",\n" +
158                 " \"terminateResponse\": \"${terminateResponse}\",\n" +
159                 " \"reason\": \"\"\n" +
160                 " }\n"
161
162         String apiPath =  "/api/oof/terminate/nxi/v1"
163
164         urlString = urlString + apiPath
165
166         HttpClientFactory httpClientFactoryMock = mock(HttpClientFactory.class)
167         when(spy.getHttpClientFactory()).thenReturn(httpClientFactoryMock)
168         Response responseMock = mock(Response.class)
169
170         HttpClient httpClientMock = mock(HttpClient.class)
171
172         when(httpClientFactoryMock.newJsonClient(any(), any())).thenReturn(httpClientMock)
173
174         when(httpClientMock.post(httpRequest)).thenReturn(responseMock)
175
176         when(responseMock.getStatus()).thenReturn(200)
177         when(responseMock.hasEntity()).thenReturn(true)
178
179         when(responseMock.readEntity(String.class)).thenReturn(oofResponse)
180
181         spy.executeTerminateNSSIQuery(mockExecution)
182
183         Mockito.verify(mockExecution,times(1)).setVariable("isTerminateNSSI", terminateResponse)
184
185     }
186
187
188     @Test
189     void testDeleteServiceOrder() {
190         def currentNSSI = [:]
191         currentNSSI.put("nssiId","5G-999")
192
193         ServiceInstance networkServiceInstance = new ServiceInstance()
194         networkServiceInstance.setServiceInstanceId("NS-777")
195         networkServiceInstance.setServiceRole("Network Service")
196
197         when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
198
199         currentNSSI.put("networkServiceInstance", networkServiceInstance)
200
201         when(mockExecution.getVariable("mso.infra.endpoint.url")).thenReturn("http://mso.onap:8088")
202         when(mockExecution.getVariable("mso.msoKey")).thenReturn("mso.msoKey")
203         when(mockExecution.getVariable("mso.infra.endpoint.auth")).thenReturn("mso.infra.endpoint.auth")
204
205         DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
206         when(spy.getAAIClient()).thenReturn(client)
207
208         GenericVnf genericVnf = new GenericVnf()
209         genericVnf.setServiceId("service-id")
210         genericVnf.setVnfName("vnf-name")
211         genericVnf.setModelInvariantId("model-invariant-id")
212         genericVnf.setModelCustomizationId("model-customization-id")
213         genericVnf.setVnfName("vnf-name")
214         genericVnf.setVnfId("vnf-id")
215
216         currentNSSI.put("constituteVnf", genericVnf)
217
218         String urlString = String.format("http://mso.onap:8088/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s", networkServiceInstance.getServiceInstanceId(), genericVnf.getVnfId())
219
220         RequestDetails requestDetails = new RequestDetails()
221         ObjectMapper mapper = new ObjectMapper()
222         String requestDetailsStr = mapper.writeValueAsString(requestDetails)
223
224         when(spy.prepareRequestDetails(mockExecution)).thenReturn(requestDetailsStr)
225
226         MsoUtils msoUtilsMock = mock(MsoUtils.class)
227         String basicAuth = "basicAuth"
228         when(msoUtilsMock.getBasicAuth(anyString(), anyString())).thenReturn(basicAuth)
229
230         HttpClientFactory httpClientFactoryMock = mock(HttpClientFactory.class)
231         when(spy.getHttpClientFactory()).thenReturn(httpClientFactoryMock)
232         Response responseMock = mock(Response.class)
233
234         HttpClient httpClientMock = mock(HttpClient.class)
235
236         when(httpClientFactoryMock.newJsonClient(any(), any())).thenReturn(httpClientMock)
237
238         when(httpClientMock.delete()).thenReturn(responseMock)
239
240         when(responseMock.getStatus()).thenReturn(200)
241         when(responseMock.hasEntity()).thenReturn(true)
242
243         String macroOperationId = "request-id"
244         String requestSelfLink = "request-self-link"
245         String entity = "{\"requestReferences\":{\"requestId\": \"${macroOperationId}\",\"requestSelfLink\":\"${requestSelfLink}\"}}"
246         when(responseMock.readEntity(String.class)).thenReturn(entity)
247
248         spy.deleteServiceOrder(mockExecution)
249
250         Mockito.verify(mockExecution,times(1)).setVariable("macroOperationId", macroOperationId)
251         Mockito.verify(mockExecution,times(1)).setVariable("requestSelfLink", requestSelfLink)
252
253         assertTrue(currentNSSI['requestSelfLink'].equals(requestSelfLink))
254     }
255
256
257     @Test
258     void testCalculateSNSSAITerminateNSSI() {
259         invokeCalculateSNSSAI("true")
260     }
261
262     @Test
263     void testCalculateSNSSAINotTerminateNSSI() {
264         invokeCalculateSNSSAI("false")
265     }
266
267     void invokeCalculateSNSSAI(String isTerminateNSSI) {
268         def currentNSSI = [:]
269         when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
270
271         when(mockExecution.getVariable("isTerminateNSSI")).thenReturn(isTerminateNSSI)
272
273         String theSNSSAI = "theS-NSSAI"
274
275         currentNSSI.put("S-NSSAI", theSNSSAI)
276
277         String theSliceProfileId = "the-slice-profile-id"
278         currentNSSI['sliceProfileId'] = theSliceProfileId
279
280         List<SliceProfile> associatedProfiles = new ArrayList<>()
281         SliceProfile sliceProfile1 = new SliceProfile()
282         sliceProfile1.setProfileId(theSliceProfileId)
283         sliceProfile1.setSNssai(theSNSSAI)
284
285         SliceProfile sliceProfile2 = new SliceProfile()
286         sliceProfile2.setSNssai("snssai2")
287
288         SliceProfile sliceProfile3 = new SliceProfile()
289         sliceProfile3.setSNssai("snssai3")
290
291         if(isTerminateNSSI.equals("false")) {
292             associatedProfiles.add(sliceProfile1)
293             associatedProfiles.add(sliceProfile2)
294             associatedProfiles.add(sliceProfile3)
295         }
296
297         int sizeBefore = associatedProfiles.size()
298
299         currentNSSI.put("associatedProfiles", associatedProfiles)
300
301         DoDeallocateCoreNSSI obj = new DoDeallocateCoreNSSI()
302         obj.calculateSNSSAI(mockExecution)
303
304         List<SliceProfile> snssais = (List<SliceProfile>)currentNSSI.get("S-NSSAIs")
305         SliceProfile sliceProfileContainsSNSSAI = (SliceProfile)currentNSSI.get("sliceProfileS-NSSAI")
306
307         if(isTerminateNSSI.equals("false")) {
308             assertTrue("Either snssais doesn't exist or size is incorrect", (snssais != null && snssais.size() == (sizeBefore - 1)))
309             assertNotNull("Slice Profile which contains given S-NSSAI not found", sliceProfileContainsSNSSAI)
310             assertTrue("Wrong Slice Profile", sliceProfileContainsSNSSAI.getSNssai().equals(theSNSSAI))
311         }
312         else {
313             assertTrue("Either snssais doesn't exist or size is incorrect", (snssais != null && snssais.size() == 0))
314         }
315     }
316
317
318     @Test
319     void testRemoveNSSIAssociationWithNSI() {
320         def currentNSSI = [:]
321
322         when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
323
324         DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
325
326         when(spy.getAAIClient()).thenReturn(client)
327
328         String nssiId = "5G-999"
329         String nsiId = "5G-99"
330         currentNSSI.put("nssiId", nssiId)
331         currentNSSI.put("nsiId", nsiId)
332
333         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
334
335         ServiceInstance nssi = new ServiceInstance()
336         nssi.setServiceInstanceId(nssiId)
337
338         ServiceInstance nsi = new ServiceInstance()
339         nsi.setServiceInstanceId(nsiId)
340         nsi.setServiceRole("nsi")
341
342         AllottedResources allottedResources = new AllottedResources()
343         AllottedResource allottedResource = new AllottedResource()
344         allottedResource.setId(UUID.randomUUID().toString())
345         allottedResources.getAllottedResource().add(allottedResource)
346         nssi.setAllottedResources(allottedResources)
347
348         currentNSSI.put("nssi", nssi)
349
350         AAIResourceUri nsiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nsiId))
351
352         AAIResultWrapper wrapperMock = mock(AAIResultWrapper.class)
353         when(client.get(nssiUri)).thenReturn(wrapperMock)
354         Relationships rsMock = mock(Relationships.class)
355         Optional<Relationships> orsMock = Optional.of(rsMock)
356         when(wrapperMock.getRelationships()).thenReturn(orsMock)
357
358         List<AAIResourceUri> allottedUris = new ArrayList<>()
359         AAIResourceUri allottedUri = AAIUriFactory.createResourceUri(Types.ALLOTTED_RESOURCE.getFragment("allotted-id"))
360         allottedUris.add(allottedUri)
361
362         when(rsMock.getRelatedUris(Types.ALLOTTED_RESOURCE)).thenReturn(allottedUris)
363
364         List<AAIResourceUri> nsiUris = new ArrayList<>()
365         nsiUris.add(nsiUri)
366
367         Optional<ServiceInstance> nsiOpt = Optional.of(nsi)
368
369         when(client.get(allottedUri)).thenReturn(wrapperMock)
370         when(rsMock.getRelatedUris(Types.SERVICE_INSTANCE)).thenReturn(nsiUris)
371         when(client.get(ServiceInstance.class, nsiUri)).thenReturn(nsiOpt)
372
373         String globalSubscriberId = "globalSubscriberId"
374         String subscriptionServiceType = "subscription-service-type"
375         when(mockExecution.getVariable("globalSubscriberId")).thenReturn(globalSubscriberId)
376         when(mockExecution.getVariable("subscriptionServiceType")).thenReturn(subscriptionServiceType)
377
378         AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(nssiId).allottedResource(allottedResource.getId()))
379
380         doNothing().when(client).disconnect(nssiUri, nsiUri)
381
382         spy.removeNSSIAssociationWithNSI(mockExecution)
383
384     }
385
386
387     @Test
388     void testDeleteNSSIServiceInstance() {
389         def currentNSSI = [:]
390
391         when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
392
393         String nssiId = "5G-999"
394
395         currentNSSI.put("nssiId", nssiId)
396
397         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
398
399         DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
400
401         when(spy.getAAIClient()).thenReturn(client)
402
403         doNothing().when(client).delete(nssiUri)
404
405         spy.deleteNSSIServiceInstance(mockExecution)
406     }
407
408
409     @Test
410     void testDeleteServiceOrderProgressAcknowledged() {
411
412         executeDeleteServiceOrderProgress("ACKNOWLEDGED")
413         Mockito.verify(mockExecution,times(1)).setVariable("deleteStatus", "processing")
414     }
415
416     @Test
417     void testDeleteServiceOrderProgressInProgress() {
418
419         executeDeleteServiceOrderProgress("IN_PROGRESS")
420         Mockito.verify(mockExecution,times(1)).setVariable("deleteStatus", "processing")
421     }
422
423
424     @Test
425     void testDeleteServiceOrderProgressCompleted() {
426
427         executeDeleteServiceOrderProgress("COMPLETE")
428         Mockito.verify(mockExecution,times(1)).setVariable("deleteStatus", "completed")
429     }
430
431
432     void executeDeleteServiceOrderProgress(String state) {
433         def currentNSSI = [:]
434
435         when(mockExecution.getVariable("currentNSSI")).thenReturn(currentNSSI)
436
437         String url = "http://nbi.onap:8088/api/v4/serviceOrder/NS-777"
438
439         currentNSSI['requestSelfLink'] =  url
440
441         DoDeallocateCoreNSSI spy = spy(DoDeallocateCoreNSSI.class)
442
443         /*ExternalAPIUtilFactory externalAPIUtilFactoryMock = mock(ExternalAPIUtilFactory.class)
444         when(spy.getExternalAPIUtilFactory()).thenReturn(externalAPIUtilFactoryMock)
445
446         ExternalAPIUtil externalAPIUtilMock = mock(ExternalAPIUtil.class)
447
448         when(externalAPIUtilFactoryMock.create()).thenReturn(externalAPIUtilMock) */
449
450         MsoUtils msoUtilsMock = mock(MsoUtils.class)
451         String basicAuth = "basicAuth"
452         when(msoUtilsMock.getBasicAuth(anyString(), anyString())).thenReturn(basicAuth)
453
454         HttpClientFactory httpClientFactoryMock = mock(HttpClientFactory.class)
455         when(spy.getHttpClientFactory()).thenReturn(httpClientFactoryMock)
456         Response responseMock = mock(Response.class)
457
458         HttpClient httpClientMock = mock(HttpClient.class)
459
460
461         when(httpClientFactoryMock.newJsonClient(any(), any())).thenReturn(httpClientMock)
462
463         when(httpClientMock.get()).thenReturn(responseMock)
464 //        when(externalAPIUtilMock.executeExternalAPIGetCall(mockExecution, url)).thenReturn(responseMock)
465
466         when(responseMock.getStatus()).thenReturn(200)
467         when(responseMock.hasEntity()).thenReturn(true)
468
469         String entity = "{\"request\":{\"requestStatus\":{\"requestState\":\"${state}\"}},\"state\":\"ACCEPTED\"}"
470         when(responseMock.readEntity(String.class)).thenReturn(entity)
471
472         spy.getDeleteServiceOrderProgress(mockExecution)
473     }
474
475 }