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