Fixing SO build
[so.git] / adapters / etsi-sol003-adapter / etsi-sol003-lcm / etsi-sol003-lcm-adapter / src / test / java / org / onap / so / adapters / vnfmadapter / rest / VnfmAdapterControllerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.adapters.vnfmadapter.rest;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertNull;
26 import static org.mockito.ArgumentMatchers.eq;
27 import static org.mockito.Mockito.doReturn;
28 import static org.mockito.Mockito.timeout;
29 import static org.mockito.Mockito.verify;
30 import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE;
31 import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
32 import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
33 import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest;
34 import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
35 import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
36 import com.google.gson.Gson;
37 import java.net.URI;
38 import java.util.Optional;
39 import org.hamcrest.BaseMatcher;
40 import org.hamcrest.Description;
41 import org.junit.Before;
42 import org.junit.Ignore;
43 import org.junit.Test;
44 import org.junit.runner.RunWith;
45 import org.mockito.ArgumentCaptor;
46 import org.mockito.hamcrest.MockitoHamcrest;
47 import org.onap.aai.domain.yang.EsrSystemInfo;
48 import org.onap.aai.domain.yang.EsrSystemInfoList;
49 import org.onap.aai.domain.yang.EsrVnfm;
50 import org.onap.aai.domain.yang.EsrVnfmList;
51 import org.onap.aai.domain.yang.GenericVnf;
52 import org.onap.aai.domain.yang.Relationship;
53 import org.onap.aai.domain.yang.RelationshipData;
54 import org.onap.aai.domain.yang.RelationshipList;
55 import org.onap.so.adapters.vnfmadapter.extclients.SdcPackageProvider;
56 import org.onap.so.adapters.vnfmadapter.lcn.JSON;
57 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200;
58 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse2001;
59 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201;
60 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum;
61 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201Links;
62 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201LinksSelf;
63 import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfmNotFoundException;
64 import org.onap.so.client.aai.AAIResourcesClient;
65 import org.onap.so.client.aai.AAIVersion;
66 import org.onap.so.client.aai.entities.uri.AAIResourceUri;
67 import org.onap.vnfmadapter.v1.model.CreateVnfRequest;
68 import org.onap.vnfmadapter.v1.model.CreateVnfResponse;
69 import org.onap.vnfmadapter.v1.model.DeleteVnfResponse;
70 import org.onap.vnfmadapter.v1.model.OperationEnum;
71 import org.onap.vnfmadapter.v1.model.OperationStateEnum;
72 import org.onap.vnfmadapter.v1.model.QueryJobResponse;
73 import org.onap.vnfmadapter.v1.model.Tenant;
74 import org.springframework.beans.factory.annotation.Autowired;
75 import org.springframework.beans.factory.annotation.Qualifier;
76 import org.springframework.boot.test.context.SpringBootTest;
77 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
78 import org.springframework.boot.test.mock.mockito.MockBean;
79 import org.springframework.boot.test.web.client.TestRestTemplate;
80 import org.springframework.boot.web.server.LocalServerPort;
81 import org.springframework.http.HttpStatus;
82 import org.springframework.http.MediaType;
83 import org.springframework.http.RequestEntity;
84 import org.springframework.http.ResponseEntity;
85 import org.springframework.test.context.ActiveProfiles;
86 import org.springframework.test.context.junit4.SpringRunner;
87 import org.springframework.test.web.client.MockRestServiceServer;
88 import org.springframework.web.client.RestTemplate;
89 import org.threeten.bp.LocalDateTime;
90 import org.threeten.bp.OffsetDateTime;
91 import org.threeten.bp.ZoneOffset;
92
93 @RunWith(SpringRunner.class)
94 @SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
95 @ActiveProfiles("test")
96
97 public class VnfmAdapterControllerTest {
98
99     private static final OffsetDateTime JAN_1_2019_12_00 =
100             OffsetDateTime.of(LocalDateTime.of(2019, 1, 1, 12, 0), ZoneOffset.UTC);
101     private static final OffsetDateTime JAN_1_2019_1_00 =
102             OffsetDateTime.of(LocalDateTime.of(2019, 1, 1, 1, 0), ZoneOffset.UTC);
103     private static final String CLOUD_OWNER = "myTestCloudOwner";
104     private static final String REGION = "myTestRegion";
105     private static final String TENANT_ID = "myTestTenantId";
106
107     @LocalServerPort
108     private int port;
109     @Autowired
110     @Qualifier(CONFIGURABLE_REST_TEMPLATE)
111     private RestTemplate testRestTemplate;
112     private MockRestServiceServer mockRestServer;
113
114     @MockBean
115     AAIResourcesClient aaiResourcesClient;
116
117     @MockBean
118     SdcPackageProvider sdcPackageProvider;
119
120     @Autowired
121     VnfmAdapterController controller;
122     Gson gson = new JSON().getGson();
123
124     @Before
125     public void setUp() throws Exception {
126         mockRestServer = MockRestServiceServer.bindTo(testRestTemplate).build();
127     }
128
129     @Test
130     public void createVnf_ValidRequest_Returns202AndJobId() throws Exception {
131         final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID);
132         final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant);
133
134         setUpGenericVnfInMockAai("vnfmType2");
135         setUpVnfmsInMockAai();
136         setUpVimInMockAai();
137
138         final String expectedsubscriptionRequest =
139                 "{\"filter\":{\"vnfInstanceSubscriptionFilter\":{\"vnfInstanceIds\":[\"vnfId\"]},\"notificationTypes\":[\"VnfLcmOperationOccurrenceNotification\"]},\"callbackUri\":\"https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/lcn/VnfLcmOperationOccurrenceNotification\",\"authentication\":{\"authType\":[\"OAUTH2_CLIENT_CREDENTIALS\", \"BASIC\", \"TLS_CERT\"],\"paramsOauth2ClientCredentials\":{\"clientId\":\"vnfm\",\"clientPassword\":\"password1$\",\"tokenEndpoint\":\"https://so-vnfm-adapter.onap:30406/oauth/token\"},\"paramsBasic\":{\"userName\":\"vnfm\",\"password\":\"password1$\"}}}";
140         final InlineResponse2001 subscriptionResponse = new InlineResponse2001();
141
142         final InlineResponse201 createResponse = createCreateResponse();
143         mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances"))
144                 .andRespond(withSuccess(gson.toJson(createResponse), MediaType.APPLICATION_JSON));
145
146         mockRestServer.expect(requestTo("http://vnfm2:8080/subscriptions"))
147                 .andExpect(content().json(expectedsubscriptionRequest))
148                 .andRespond(withSuccess(gson.toJson(subscriptionResponse), MediaType.APPLICATION_JSON));
149
150         mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances/vnfId/instantiate"))
151                 .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON)
152                         .location(new URI("http://vnfm2:8080/vnf_lcm_op_occs/123456")));
153
154         final InlineResponse200 firstOperationQueryResponse = createOperationQueryResponse(
155                 org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200.OperationEnum.INSTANTIATE,
156                 org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200.OperationStateEnum.PROCESSING);
157         mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_lcm_op_occs/123456"))
158                 .andRespond(withSuccess(gson.toJson(firstOperationQueryResponse), MediaType.APPLICATION_JSON));
159
160         final InlineResponse200 secondOperationQueryReponse = createOperationQueryResponse(
161                 org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200.OperationEnum.INSTANTIATE,
162                 org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200.OperationStateEnum.COMPLETED);
163         mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_lcm_op_occs/123456"))
164                 .andRespond(withSuccess(gson.toJson(secondOperationQueryReponse), MediaType.APPLICATION_JSON));
165
166         // Invoke the create request
167
168         final ResponseEntity<CreateVnfResponse> createVnfResponse =
169                 controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213");
170         assertEquals(HttpStatus.ACCEPTED, createVnfResponse.getStatusCode());
171         assertNotNull(createVnfResponse.getBody().getJobId());
172
173         final ArgumentCaptor<GenericVnf> genericVnfArgument = ArgumentCaptor.forClass(GenericVnf.class);
174         final ArgumentCaptor<AAIResourceUri> uriArgument = ArgumentCaptor.forClass(AAIResourceUri.class);
175
176         verify(aaiResourcesClient).update(uriArgument.capture(), genericVnfArgument.capture());
177
178         assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", uriArgument.getValue().build().toString());
179
180         assertEquals("myTestVnfId", genericVnfArgument.getValue().getVnfId());
181
182         final ArgumentCaptor<AAIResourceUri> uriArgument1Connect = ArgumentCaptor.forClass(AAIResourceUri.class);
183         final ArgumentCaptor<AAIResourceUri> uriArgument2Connect = ArgumentCaptor.forClass(AAIResourceUri.class);
184         verify(aaiResourcesClient, timeout(1000)).connect(uriArgument1Connect.capture(), uriArgument2Connect.capture());
185         assertEquals("/external-system/esr-vnfm-list/esr-vnfm/vnfm2",
186                 uriArgument1Connect.getAllValues().get(0).build().toString());
187         assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId",
188                 uriArgument2Connect.getAllValues().get(0).build().toString());
189
190         // check the job status
191
192         final ResponseEntity<QueryJobResponse> firstJobQueryResponse =
193                 controller.jobQuery(createVnfResponse.getBody().getJobId(), "", "so", "1213");
194         assertEquals(OperationEnum.INSTANTIATE, firstJobQueryResponse.getBody().getOperation());
195         assertEquals(OperationStateEnum.PROCESSING, firstJobQueryResponse.getBody().getOperationState());
196         assertEquals(JAN_1_2019_12_00, firstJobQueryResponse.getBody().getStartTime());
197         assertEquals(JAN_1_2019_1_00, firstJobQueryResponse.getBody().getStateEnteredTime());
198
199         final ResponseEntity<QueryJobResponse> secondJobQueryResponse =
200                 controller.jobQuery(createVnfResponse.getBody().getJobId(), "", "so", "1213");
201         assertEquals(OperationEnum.INSTANTIATE, secondJobQueryResponse.getBody().getOperation());
202         assertEquals(OperationStateEnum.COMPLETED, secondJobQueryResponse.getBody().getOperationState());
203         assertEquals(JAN_1_2019_12_00, secondJobQueryResponse.getBody().getStartTime());
204         assertEquals(JAN_1_2019_1_00, secondJobQueryResponse.getBody().getStateEnteredTime());
205     }
206
207     @Test(expected = IllegalArgumentException.class)
208     public void createVnf_VnfAlreadyExistsOnVnfm_ThrowsIllegalArgumentException() throws Exception {
209         final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID);
210         final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant);
211
212         final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1");
213         addSelfLinkToGenericVnf(genericVnf);
214         addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1");
215         setUpVnfmsInMockAai();
216
217         final InlineResponse201 reponse = new InlineResponse201();
218         mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm")))
219                 .andRespond(withSuccess(gson.toJson(reponse), MediaType.APPLICATION_JSON));
220
221         controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213");
222     }
223
224     @Test(expected = VnfmNotFoundException.class)
225     public void createVnf_NoMatchingVnfmFound_ThrowsException() throws Exception {
226         final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID);
227         final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant);
228
229         setUpGenericVnfInMockAai("anotherType");
230         setUpVnfmsInMockAai();
231
232         controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213");
233     }
234
235     @Test
236     public void createVnf_VnfmAlreadyAssociatedWithVnf_Returns202AndJobId() throws Exception {
237         final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID);
238         final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant);
239
240         final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType2");
241         addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm2");
242         setUpVnfmsInMockAai();
243         setUpVimInMockAai();
244
245         final InlineResponse201 createResponse = createCreateResponse();
246         mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances"))
247                 .andRespond(withSuccess(gson.toJson(createResponse), MediaType.APPLICATION_JSON));
248
249         mockRestServer.expect(requestTo("http://vnfm2:8080/subscriptions")).andRespond(withBadRequest());
250
251         mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances/vnfId/instantiate"))
252                 .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON)
253                         .location(new URI("http://vnfm2:8080/vnf_lcm_op_occs/123456")));
254
255         final ResponseEntity<CreateVnfResponse> response =
256                 controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213");
257         assertEquals(HttpStatus.ACCEPTED, response.getStatusCode());
258         assertNotNull(response.getBody().getJobId());
259     }
260
261     @Test
262     @Ignore
263     public void createVnf_UnauthorizedUser_Returns401() throws Exception {
264         final TestRestTemplate restTemplateWrongPassword = new TestRestTemplate("test", "wrongPassword");
265         final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID);
266         final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant);
267
268         final RequestEntity<CreateVnfRequest> request =
269                 RequestEntity.post(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myVnfId"))
270                         .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
271                         .header("X-ONAP-RequestId", "myRequestId").header("X-ONAP-InvocationID", "myInvocationId")
272                         .body(createVnfRequest);
273         final ResponseEntity<CreateVnfResponse> response =
274                 restTemplateWrongPassword.exchange(request, CreateVnfResponse.class);
275         assertEquals(401, response.getStatusCode().value());
276     }
277
278     @Test
279     public void deleteVnf_ValidRequest_Returns202AndJobId() throws Exception {
280         final TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
281
282         final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1");
283         addSelfLinkToGenericVnf(genericVnf);
284         addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1");
285         setUpVnfmsInMockAai();
286
287         mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate"))
288                 .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON)
289                         .location(new URI("http://vnfm1:8080/vnf_lcm_op_occs/1234567")));
290
291         final InlineResponse200 firstOperationQueryResponse = createOperationQueryResponse(
292                 org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200.OperationEnum.TERMINATE,
293                 org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200.OperationStateEnum.PROCESSING);
294         mockRestServer.expect(requestTo("http://vnfm1:8080/vnf_lcm_op_occs/1234567"))
295                 .andRespond(withSuccess(gson.toJson(firstOperationQueryResponse), MediaType.APPLICATION_JSON));
296
297         final InlineResponse200 secondOperationQueryReponse = createOperationQueryResponse(
298                 org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200.OperationEnum.TERMINATE,
299                 org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200.OperationStateEnum.COMPLETED);
300         mockRestServer.expect(requestTo("http://vnfm1:8080/vnf_lcm_op_occs/1234567"))
301                 .andRespond(withSuccess(gson.toJson(secondOperationQueryReponse), MediaType.APPLICATION_JSON));
302
303         final RequestEntity<Void> request = RequestEntity
304                 .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId"))
305                 .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId")
306                 .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build();
307         final ResponseEntity<DeleteVnfResponse> deleteVnfResponse =
308                 restTemplate.exchange(request, DeleteVnfResponse.class);
309         assertEquals(202, deleteVnfResponse.getStatusCode().value());
310         assertNotNull(deleteVnfResponse.getBody().getJobId());
311
312         final ResponseEntity<QueryJobResponse> firstJobQueryResponse =
313                 controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213");
314         assertEquals(OperationEnum.TERMINATE, firstJobQueryResponse.getBody().getOperation());
315         assertEquals(OperationStateEnum.PROCESSING, firstJobQueryResponse.getBody().getOperationState());
316         assertEquals(JAN_1_2019_12_00, firstJobQueryResponse.getBody().getStartTime());
317         assertEquals(JAN_1_2019_1_00, firstJobQueryResponse.getBody().getStateEnteredTime());
318
319         final ResponseEntity<QueryJobResponse> secondJobQueryResponse =
320                 controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213");
321         assertEquals(OperationEnum.TERMINATE, secondJobQueryResponse.getBody().getOperation());
322         assertEquals(OperationStateEnum.PROCESSING, secondJobQueryResponse.getBody().getOperationState());
323         assertEquals(JAN_1_2019_12_00, secondJobQueryResponse.getBody().getStartTime());
324         assertEquals(JAN_1_2019_1_00, secondJobQueryResponse.getBody().getStateEnteredTime());
325     }
326
327     @Test
328     public void deleteVnf_VnfAlreadyTerminated_Returns202AndJobId() throws Exception {
329         final TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
330
331         final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1");
332         addSelfLinkToGenericVnf(genericVnf);
333         addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1");
334         setUpVnfmsInMockAai();
335
336         mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate"))
337                 .andRespond(withStatus(HttpStatus.CONFLICT).contentType(MediaType.APPLICATION_JSON));
338
339         final InlineResponse201 reponse = new InlineResponse201();
340         reponse.setInstantiationState(InstantiationStateEnum.NOT_INSTANTIATED);
341         mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm")))
342                 .andRespond(withSuccess(gson.toJson(reponse), MediaType.APPLICATION_JSON));
343
344         mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))
345                 .andRespond(withStatus(HttpStatus.NO_CONTENT).contentType(MediaType.APPLICATION_JSON));
346
347         final RequestEntity<Void> request = RequestEntity
348                 .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId"))
349                 .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId")
350                 .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build();
351         final ResponseEntity<DeleteVnfResponse> deleteVnfResponse =
352                 restTemplate.exchange(request, DeleteVnfResponse.class);
353         assertEquals(202, deleteVnfResponse.getStatusCode().value());
354         assertNotNull(deleteVnfResponse.getBody().getJobId());
355
356         final ResponseEntity<QueryJobResponse> jobQueryResponse =
357                 controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213");
358         assertEquals(OperationStateEnum.COMPLETED, jobQueryResponse.getBody().getOperationState());
359     }
360
361     @Test
362     public void deleteVnf_GenericVnfNotFound_Returns404() throws Exception {
363         final TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
364
365         final RequestEntity<Void> request = RequestEntity
366                 .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myNonExistingVnfId"))
367                 .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId")
368                 .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build();
369         final ResponseEntity<DeleteVnfResponse> deleteVnfResponse =
370                 restTemplate.exchange(request, DeleteVnfResponse.class);
371         assertEquals(404, deleteVnfResponse.getStatusCode().value());
372         assertNull(deleteVnfResponse.getBody().getJobId());
373     }
374
375     @Test
376     public void deleteVnf_NoAssignedVnfm_Returns400() throws Exception {
377         final TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
378
379         setUpGenericVnfInMockAai("vnfmType");
380
381         final RequestEntity<Void> request = RequestEntity
382                 .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId"))
383                 .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId")
384                 .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build();
385         final ResponseEntity<DeleteVnfResponse> deleteVnfResponse =
386                 restTemplate.exchange(request, DeleteVnfResponse.class);
387         assertEquals(400, deleteVnfResponse.getStatusCode().value());
388         assertNull(deleteVnfResponse.getBody().getJobId());
389     }
390
391     @Test
392     public void deleteVnf_ErrorStatusCodeFromVnfm_Returns500() throws Exception {
393         final TestRestTemplate restTemplate = new TestRestTemplate("test", "test");
394
395         final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1");
396         addSelfLinkToGenericVnf(genericVnf);
397         addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1");
398         setUpVnfmsInMockAai();
399
400         mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate"))
401                 .andRespond(withStatus(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON));
402
403         final RequestEntity<Void> request = RequestEntity
404                 .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId"))
405                 .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId")
406                 .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build();
407         final ResponseEntity<DeleteVnfResponse> deleteVnfResponse =
408                 restTemplate.exchange(request, DeleteVnfResponse.class);
409         assertEquals(500, deleteVnfResponse.getStatusCode().value());
410         assertNull(deleteVnfResponse.getBody().getJobId());
411
412     }
413
414     private InlineResponse200 createOperationQueryResponse(
415             final org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200.OperationEnum operation,
416             final org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse200.OperationStateEnum operationState) {
417         final InlineResponse200 response = new InlineResponse200();
418         response.setId("9876");
419         response.setOperation(operation);
420         response.setOperationState(operationState);
421         response.setStartTime(JAN_1_2019_12_00);
422         response.setStateEnteredTime(JAN_1_2019_1_00);
423         response.setVnfInstanceId("myVnfInstanceId");
424         return response;
425     }
426
427     private GenericVnf createGenericVnf(final String type) {
428         final GenericVnf genericVnf = new GenericVnf();
429         genericVnf.setVnfId("myTestVnfId");
430         genericVnf.setNfType(type);
431         return genericVnf;
432     }
433
434     private GenericVnf setUpGenericVnfInMockAai(final String type) {
435         final GenericVnf genericVnf = createGenericVnf(type);
436
437         doReturn(Optional.of(genericVnf)).when(aaiResourcesClient).get(eq(GenericVnf.class),
438                 MockitoHamcrest.argThat(new AaiResourceUriMatcher("/network/generic-vnfs/generic-vnf/myTestVnfId")));
439         return genericVnf;
440     }
441
442     private void addSelfLinkToGenericVnf(final GenericVnf vnf) {
443         vnf.setSelflink("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm");
444     }
445
446     private void addRelationshipFromGenericVnfToVnfm(final GenericVnf genericVnf, final String vnfmId) {
447         final Relationship relationshipToVnfm = new Relationship();
448         relationshipToVnfm
449                 .setRelatedLink("/aai/" + AAIVersion.LATEST + "/external-system/esr-vnfm-list/esr-vnfm/" + vnfmId);
450         relationshipToVnfm.setRelatedTo("esr-vnfm");
451         final RelationshipData relationshipData = new RelationshipData();
452         relationshipData.setRelationshipKey("esr-vnfm.vnfm-id");
453         relationshipData.setRelationshipValue(vnfmId);
454         relationshipToVnfm.getRelationshipData().add(relationshipData);
455
456         final RelationshipList relationshipList = new RelationshipList();
457         relationshipList.getRelationship().add(relationshipToVnfm);
458         genericVnf.setRelationshipList(relationshipList);
459     }
460
461     private void setUpVnfmsInMockAai() {
462         final EsrSystemInfo esrSystemInfo1 = new EsrSystemInfo();
463         esrSystemInfo1.setServiceUrl("http://vnfm1:8080");
464         esrSystemInfo1.setType("vnfmType1");
465         esrSystemInfo1.setSystemType("VNFM");
466         final EsrSystemInfoList esrSystemInfoList1 = new EsrSystemInfoList();
467         esrSystemInfoList1.getEsrSystemInfo().add(esrSystemInfo1);
468
469         final EsrVnfm esrVnfm1 = new EsrVnfm();
470         esrVnfm1.setVnfmId("vnfm1");
471         esrVnfm1.setEsrSystemInfoList(esrSystemInfoList1);
472         esrVnfm1.setResourceVersion("1234");
473
474         final EsrSystemInfo esrSystemInfo2 = new EsrSystemInfo();
475         esrSystemInfo2.setServiceUrl("http://vnfm2:8080");
476         esrSystemInfo2.setType("vnfmType2");
477         esrSystemInfo2.setSystemType("VNFM");
478         final EsrSystemInfoList esrSystemInfoList2 = new EsrSystemInfoList();
479         esrSystemInfoList2.getEsrSystemInfo().add(esrSystemInfo2);
480
481         final EsrVnfm esrVnfm2 = new EsrVnfm();
482         esrVnfm2.setVnfmId("vnfm2");
483         esrVnfm2.setEsrSystemInfoList(esrSystemInfoList2);
484         esrVnfm2.setResourceVersion("1234");
485
486         final EsrVnfmList esrVnfmList = new EsrVnfmList();
487         esrVnfmList.getEsrVnfm().add(esrVnfm1);
488         esrVnfmList.getEsrVnfm().add(esrVnfm2);
489
490         doReturn(Optional.of(esrVnfm1)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest
491                 .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm1?depth=1")));
492
493         doReturn(Optional.of(esrVnfm2)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest
494                 .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm2?depth=1")));
495
496         doReturn(Optional.of(esrVnfmList)).when(aaiResourcesClient).get(eq(EsrVnfmList.class),
497                 MockitoHamcrest.argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list")));
498
499         doReturn(Optional.of(esrSystemInfoList1)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class),
500                 MockitoHamcrest.argThat(new AaiResourceUriMatcher(
501                         "/external-system/esr-vnfm-list/esr-vnfm/vnfm1/esr-system-info-list")));
502         doReturn(Optional.of(esrSystemInfoList2)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class),
503                 MockitoHamcrest.argThat(new AaiResourceUriMatcher(
504                         "/external-system/esr-vnfm-list/esr-vnfm/vnfm2/esr-system-info-list")));
505     }
506
507     private void setUpVimInMockAai() {
508         final EsrSystemInfo esrSystemInfo = new EsrSystemInfo();
509         esrSystemInfo.setServiceUrl("http://myVim:8080");
510         esrSystemInfo.setType("openstack");
511         esrSystemInfo.setSystemType("VIM");
512         esrSystemInfo.setCloudDomain("myDomain");
513         esrSystemInfo.setUserName("myUser");
514         esrSystemInfo.setPassword("myPassword");
515
516         final EsrSystemInfoList esrSystemInfoList = new EsrSystemInfoList();
517         esrSystemInfoList.getEsrSystemInfo().add(esrSystemInfo);
518
519         doReturn(Optional.of(esrSystemInfoList)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class),
520                 MockitoHamcrest.argThat(new AaiResourceUriMatcher("/cloud-infrastructure/cloud-regions/cloud-region/"
521                         + CLOUD_OWNER + "/" + REGION + "/esr-system-info-list")));
522     }
523
524     private InlineResponse201 createCreateResponse() {
525         final InlineResponse201 createResponse = new InlineResponse201();
526         createResponse.setVnfdId("myTestVnfd");
527         final InlineResponse201Links links = new InlineResponse201Links();
528         final InlineResponse201LinksSelf self = new InlineResponse201LinksSelf();
529         self.setHref("http://vnfm2:8080/vnf_instances/vnfId");
530         links.setSelf(self);
531         createResponse.setLinks(links);
532         createResponse.setId("vnfId");
533         return createResponse;
534     }
535
536
537     private class AaiResourceUriMatcher extends BaseMatcher<AAIResourceUri> {
538
539         final String uriAsString;
540
541         public AaiResourceUriMatcher(final String uriAsString) {
542             this.uriAsString = uriAsString;
543         }
544
545         @Override
546         public boolean matches(final Object item) {
547             if (item instanceof AAIResourceUri) {
548                 if (uriAsString.endsWith("...")) {
549                     return ((AAIResourceUri) item).build().toString()
550                             .startsWith(uriAsString.substring(0, uriAsString.indexOf("...")));
551                 }
552                 return ((AAIResourceUri) item).build().toString().equals(uriAsString);
553             }
554             return false;
555         }
556
557         @Override
558         public void describeTo(final Description description) {}
559
560     }
561
562 }