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