aboutsummaryrefslogtreecommitdiffstats
path: root/so-etsi-sol003-adapter-lcm/so-etsi-sol003-adapter-lcm-service/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterControllerTest.java
blob: 1352e37b529493b40fb5ead703b05046361b8cbb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.so.adapters.etsisol003adapter.lcm.rest;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.net.URI;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Optional;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.hamcrest.MockitoHamcrest;
import org.onap.aai.domain.yang.EsrSystemInfo;
import org.onap.aai.domain.yang.EsrSystemInfoList;
import org.onap.aai.domain.yang.EsrVnfm;
import org.onap.aai.domain.yang.EsrVnfmList;
import org.onap.aai.domain.yang.GenericVnf;
import org.onap.aai.domain.yang.Relationship;
import org.onap.aai.domain.yang.RelationshipData;
import org.onap.aai.domain.yang.RelationshipList;
import org.onap.aaiclient.client.aai.AAIResourcesClient;
import org.onap.aaiclient.client.aai.AAIVersion;
import org.onap.aaiclient.client.aai.entities.uri.AAIBaseResourceUri;
import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri;
import org.onap.so.adapters.etsi.sol003.adapter.common.GsonProvider;
import org.onap.so.adapters.etsisol003adapter.lcm.extclients.EtsiPackageProvider;
import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.VnfmRestTemplateConfiguration;
import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200;
import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse2001;
import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201;
import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201.InstantiationStateEnum;
import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201Links;
import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse201LinksSelf;
import org.onap.so.adapters.etsisol003adapter.lcm.rest.exceptions.VnfmNotFoundException;
import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.CreateVnfRequest;
import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.CreateVnfResponse;
import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.DeleteVnfResponse;
import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationEnum;
import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStateEnum;
import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.QueryJobResponse;
import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.Tenant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class EtsiSol003AdapterControllerTest {
    

    private static final OffsetDateTime JAN_1_2019_12_00 =
            OffsetDateTime.of(LocalDateTime.of(2019, 1, 1, 12, 0), ZoneOffset.UTC);
    private static final OffsetDateTime JAN_1_2019_1_00 =
            OffsetDateTime.of(LocalDateTime.of(2019, 1, 1, 1, 0), ZoneOffset.UTC);
    private static final String CLOUD_OWNER = "myTestCloudOwner";
    private static final String REGION = "myTestRegion";
    private static final String TENANT_ID = "myTestTenantId";

    @LocalServerPort
    private int port;
    @Autowired
    @Qualifier(VnfmRestTemplateConfiguration.SOL003_LCM_REST_TEMPLATE)
    private RestTemplate testRestTemplate;
    private MockRestServiceServer mockRestServer;

    @MockBean
    AAIResourcesClient aaiResourcesClient;

    @MockBean
    EtsiPackageProvider etsiPackageProvider;

    @Autowired
    EtsiSol003AdapterController controller;

    @Autowired
    GsonProvider gsonProvider;

    @Before
    public void setUp() throws Exception {
        mockRestServer = MockRestServiceServer.bindTo(testRestTemplate).build();
    }

    @Test
    public void createVnf_ValidRequest_Returns202AndJobId() throws Exception {
        final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID);
        final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant);

        setUpGenericVnfInMockAai("vnfmType2");
        setUpVnfmsInMockAai();
        setUpVimInMockAai();

        final String expectedsubscriptionRequest =
                "{\"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$\"}}}";
        final InlineResponse2001 subscriptionResponse = new InlineResponse2001();

        final InlineResponse201 createResponse = createCreateResponse();
        mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances"))
                .andRespond(withSuccess(gsonProvider.getGson().toJson(createResponse), MediaType.APPLICATION_JSON));

        mockRestServer.expect(requestTo("http://vnfm2:8080/subscriptions"))
                .andExpect(content().json(expectedsubscriptionRequest))
                .andRespond(withSuccess(gsonProvider.getGson().toJson(subscriptionResponse), MediaType.APPLICATION_JSON));

        mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances/vnfId/instantiate"))
                .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON)
                        .location(new URI("http://vnfm2:8080/vnf_lcm_op_occs/123456")));

        final InlineResponse200 firstOperationQueryResponse = createOperationQueryResponse(
                org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.INSTANTIATE,
                org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.PROCESSING);
        mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_lcm_op_occs/123456"))
                .andRespond(withSuccess(gsonProvider.getGson().toJson(firstOperationQueryResponse), MediaType.APPLICATION_JSON));

        final InlineResponse200 secondOperationQueryReponse = createOperationQueryResponse(
                org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.INSTANTIATE,
                org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.COMPLETED);
        mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_lcm_op_occs/123456"))
                .andRespond(withSuccess(gsonProvider.getGson().toJson(secondOperationQueryReponse), MediaType.APPLICATION_JSON));

        // Invoke the create request

        final ResponseEntity<CreateVnfResponse> createVnfResponse =
                controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213");
        assertEquals(HttpStatus.ACCEPTED, createVnfResponse.getStatusCode());
        assertNotNull(createVnfResponse.getBody().getJobId());

        final ArgumentCaptor<GenericVnf> genericVnfArgument = ArgumentCaptor.forClass(GenericVnf.class);
        final ArgumentCaptor<AAIResourceUri> uriArgument = ArgumentCaptor.forClass(AAIResourceUri.class);

        verify(aaiResourcesClient).update(uriArgument.capture(), genericVnfArgument.capture());

        assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", uriArgument.getValue().build().toString());

        assertEquals("myTestVnfId", genericVnfArgument.getValue().getVnfId());

        final ArgumentCaptor<AAIResourceUri> uriArgument1Connect = ArgumentCaptor.forClass(AAIResourceUri.class);
        final ArgumentCaptor<AAIResourceUri> uriArgument2Connect = ArgumentCaptor.forClass(AAIResourceUri.class);
        verify(aaiResourcesClient, timeout(1000)).connect(uriArgument1Connect.capture(), uriArgument2Connect.capture());
        assertEquals("/external-system/esr-vnfm-list/esr-vnfm/vnfm2",
                uriArgument1Connect.getAllValues().get(0).build().toString());
        assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId",
                uriArgument2Connect.getAllValues().get(0).build().toString());

        // check the job status

        final ResponseEntity<QueryJobResponse> firstJobQueryResponse =
                controller.jobQuery(createVnfResponse.getBody().getJobId(), "", "so", "1213");
        assertEquals(OperationEnum.INSTANTIATE, firstJobQueryResponse.getBody().getOperation());
        assertEquals(OperationStateEnum.PROCESSING, firstJobQueryResponse.getBody().getOperationState());
        assertEquals(JAN_1_2019_12_00, firstJobQueryResponse.getBody().getStartTime());
        assertEquals(JAN_1_2019_1_00, firstJobQueryResponse.getBody().getStateEnteredTime());

        final ResponseEntity<QueryJobResponse> secondJobQueryResponse =
                controller.jobQuery(createVnfResponse.getBody().getJobId(), "", "so", "1213");
        assertEquals(OperationEnum.INSTANTIATE, secondJobQueryResponse.getBody().getOperation());
        assertEquals(OperationStateEnum.COMPLETED, secondJobQueryResponse.getBody().getOperationState());
        assertEquals(JAN_1_2019_12_00, secondJobQueryResponse.getBody().getStartTime());
        assertEquals(JAN_1_2019_1_00, secondJobQueryResponse.getBody().getStateEnteredTime());
    }

    @Test(expected = IllegalArgumentException.class)
    public void createVnf_VnfAlreadyExistsOnVnfm_ThrowsIllegalArgumentException() throws Exception {
        final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID);
        final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant);

        final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1");
        addSelfLinkToGenericVnf(genericVnf);
        addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1");
        setUpVnfmsInMockAai();

        final InlineResponse201 reponse = new InlineResponse201();
        mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm")))
                .andRespond(withSuccess(gsonProvider.getGson().toJson(reponse), MediaType.APPLICATION_JSON));

        controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213");
    }

    @Test(expected = VnfmNotFoundException.class)
    public void createVnf_NoMatchingVnfmFound_ThrowsException() throws Exception {
        final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID);
        final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant);

        setUpGenericVnfInMockAai("anotherType");
        setUpVnfmsInMockAai();

        controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213");
    }

    @Test
    public void createVnf_VnfmAlreadyAssociatedWithVnf_Returns202AndJobId() throws Exception {
        final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID);
        final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant);

        final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType2");
        addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm2");
        setUpVnfmsInMockAai();
        setUpVimInMockAai();

        final InlineResponse201 createResponse = createCreateResponse();
        mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances"))
                .andRespond(withSuccess(gsonProvider.getGson().toJson(createResponse), MediaType.APPLICATION_JSON));

        mockRestServer.expect(requestTo("http://vnfm2:8080/subscriptions")).andRespond(withBadRequest());

        mockRestServer.expect(requestTo("http://vnfm2:8080/vnf_instances/vnfId/instantiate"))
                .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON)
                        .location(new URI("http://vnfm2:8080/vnf_lcm_op_occs/123456")));

        final ResponseEntity<CreateVnfResponse> response =
                controller.vnfCreate("myTestVnfId", createVnfRequest, "asadas", "so", "1213");
        assertEquals(HttpStatus.ACCEPTED, response.getStatusCode());
        assertNotNull(response.getBody().getJobId());
    }

    @Test
    @Ignore
    public void createVnf_UnauthorizedUser_Returns401() throws Exception {
        final TestRestTemplate restTemplateWrongPassword = new TestRestTemplate("test", "wrongPassword");
        final Tenant tenant = new Tenant().cloudOwner(CLOUD_OWNER).regionName(REGION).tenantId(TENANT_ID);
        final CreateVnfRequest createVnfRequest = new CreateVnfRequest().name("myTestName").tenant(tenant);

        final RequestEntity<CreateVnfRequest> request =
                RequestEntity.post(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myVnfId"))
                        .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
                        .header("X-ONAP-RequestId", "myRequestId").header("X-ONAP-InvocationID", "myInvocationId")
                        .body(createVnfRequest);
        final ResponseEntity<CreateVnfResponse> response =
                restTemplateWrongPassword.exchange(request, CreateVnfResponse.class);
        assertEquals(401, response.getStatusCode().value());
    }

    @Test
    public void deleteVnf_ValidRequest_Returns202AndJobId() throws Exception {
        final TestRestTemplate restTemplate = new TestRestTemplate("test", "test");

        final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1");
        addSelfLinkToGenericVnf(genericVnf);
        addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1");
        setUpVnfmsInMockAai();

        mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate"))
                .andRespond(withStatus(HttpStatus.ACCEPTED).contentType(MediaType.APPLICATION_JSON)
                        .location(new URI("http://vnfm1:8080/vnf_lcm_op_occs/1234567")));

        final InlineResponse200 firstOperationQueryResponse = createOperationQueryResponse(
                org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.TERMINATE,
                org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.PROCESSING);
        mockRestServer.expect(requestTo("http://vnfm1:8080/vnf_lcm_op_occs/1234567"))
                .andRespond(withSuccess(gsonProvider.getGson().toJson(firstOperationQueryResponse), MediaType.APPLICATION_JSON));

        final InlineResponse200 secondOperationQueryReponse = createOperationQueryResponse(
                org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum.TERMINATE,
                org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum.COMPLETED);
        mockRestServer.expect(requestTo("http://vnfm1:8080/vnf_lcm_op_occs/1234567"))
                .andRespond(withSuccess(gsonProvider.getGson().toJson(secondOperationQueryReponse), MediaType.APPLICATION_JSON));

        final RequestEntity<Void> request = RequestEntity
                .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId"))
                .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId")
                .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build();
        final ResponseEntity<DeleteVnfResponse> deleteVnfResponse =
                restTemplate.exchange(request, DeleteVnfResponse.class);
        assertEquals(202, deleteVnfResponse.getStatusCode().value());
        assertNotNull(deleteVnfResponse.getBody().getJobId());

        final ResponseEntity<QueryJobResponse> firstJobQueryResponse =
                controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213");
        assertEquals(OperationEnum.TERMINATE, firstJobQueryResponse.getBody().getOperation());
        assertEquals(OperationStateEnum.PROCESSING, firstJobQueryResponse.getBody().getOperationState());
        assertEquals(JAN_1_2019_12_00, firstJobQueryResponse.getBody().getStartTime());
        assertEquals(JAN_1_2019_1_00, firstJobQueryResponse.getBody().getStateEnteredTime());

        final ResponseEntity<QueryJobResponse> secondJobQueryResponse =
                controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213");
        assertEquals(OperationEnum.TERMINATE, secondJobQueryResponse.getBody().getOperation());
        assertEquals(OperationStateEnum.PROCESSING, secondJobQueryResponse.getBody().getOperationState());
        assertEquals(JAN_1_2019_12_00, secondJobQueryResponse.getBody().getStartTime());
        assertEquals(JAN_1_2019_1_00, secondJobQueryResponse.getBody().getStateEnteredTime());
    }

    @Test
    public void deleteVnf_VnfAlreadyTerminated_Returns202AndJobId() throws Exception {
        final TestRestTemplate restTemplate = new TestRestTemplate("test", "test");

        final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1");
        addSelfLinkToGenericVnf(genericVnf);
        addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1");
        setUpVnfmsInMockAai();

        mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate"))
                .andRespond(withStatus(HttpStatus.CONFLICT).contentType(MediaType.APPLICATION_JSON));

        final InlineResponse201 reponse = new InlineResponse201();
        reponse.setInstantiationState(InstantiationStateEnum.NOT_INSTANTIATED);
        mockRestServer.expect(requestTo(new URI("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm")))
                .andRespond(withSuccess(gsonProvider.getGson().toJson(reponse), MediaType.APPLICATION_JSON));

        mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm"))
                .andRespond(withStatus(HttpStatus.NO_CONTENT).contentType(MediaType.APPLICATION_JSON));

        final RequestEntity<Void> request = RequestEntity
                .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId"))
                .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId")
                .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build();
        final ResponseEntity<DeleteVnfResponse> deleteVnfResponse =
                restTemplate.exchange(request, DeleteVnfResponse.class);
        assertEquals(202, deleteVnfResponse.getStatusCode().value());
        assertNotNull(deleteVnfResponse.getBody().getJobId());

        final ResponseEntity<QueryJobResponse> jobQueryResponse =
                controller.jobQuery(deleteVnfResponse.getBody().getJobId(), "", "so", "1213");
        assertEquals(OperationStateEnum.COMPLETED, jobQueryResponse.getBody().getOperationState());
    }

    @Test
    public void deleteVnf_GenericVnfNotFound_Returns404() throws Exception {
        final TestRestTemplate restTemplate = new TestRestTemplate("test", "test");

        final RequestEntity<Void> request = RequestEntity
                .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myNonExistingVnfId"))
                .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId")
                .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build();
        final ResponseEntity<DeleteVnfResponse> deleteVnfResponse =
                restTemplate.exchange(request, DeleteVnfResponse.class);
        assertEquals(404, deleteVnfResponse.getStatusCode().value());
        assertNull(deleteVnfResponse.getBody().getJobId());
    }

    @Test
    public void deleteVnf_NoAssignedVnfm_Returns400() throws Exception {
        final TestRestTemplate restTemplate = new TestRestTemplate("test", "test");

        setUpGenericVnfInMockAai("vnfmType");

        final RequestEntity<Void> request = RequestEntity
                .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId"))
                .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId")
                .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build();
        final ResponseEntity<DeleteVnfResponse> deleteVnfResponse =
                restTemplate.exchange(request, DeleteVnfResponse.class);
        assertEquals(400, deleteVnfResponse.getStatusCode().value());
        assertNull(deleteVnfResponse.getBody().getJobId());
    }

    @Test
    public void deleteVnf_ErrorStatusCodeFromVnfm_Returns500() throws Exception {
        final TestRestTemplate restTemplate = new TestRestTemplate("test", "test");

        final GenericVnf genericVnf = setUpGenericVnfInMockAai("vnfmType1");
        addSelfLinkToGenericVnf(genericVnf);
        addRelationshipFromGenericVnfToVnfm(genericVnf, "vnfm1");
        setUpVnfmsInMockAai();

        mockRestServer.expect(requestTo("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm/terminate"))
                .andRespond(withStatus(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON));

        final RequestEntity<Void> request = RequestEntity
                .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myTestVnfId"))
                .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId")
                .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build();
        final ResponseEntity<DeleteVnfResponse> deleteVnfResponse =
                restTemplate.exchange(request, DeleteVnfResponse.class);
        assertEquals(500, deleteVnfResponse.getStatusCode().value());
        assertNull(deleteVnfResponse.getBody().getJobId());

    }

    private InlineResponse200 createOperationQueryResponse(
            final org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationEnum operation,
            final org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.model.InlineResponse200.OperationStateEnum operationState) {
        final InlineResponse200 response = new InlineResponse200();
        response.setId("9876");
        response.setOperation(operation);
        response.setOperationState(operationState);
        response.setStartTime(JAN_1_2019_12_00);
        response.setStateEnteredTime(JAN_1_2019_1_00);
        response.setVnfInstanceId("myVnfInstanceId");
        return response;
    }

    private GenericVnf createGenericVnf(final String type) {
        final GenericVnf genericVnf = new GenericVnf();
        genericVnf.setVnfId("myTestVnfId");
        genericVnf.setNfType(type);
        return genericVnf;
    }

    private GenericVnf setUpGenericVnfInMockAai(final String type) {
        final GenericVnf genericVnf = createGenericVnf(type);

        doReturn(Optional.of(genericVnf)).when(aaiResourcesClient).get(eq(GenericVnf.class),
                MockitoHamcrest.argThat(new AaiResourceUriMatcher("/network/generic-vnfs/generic-vnf/myTestVnfId")));
        return genericVnf;
    }

    private void addSelfLinkToGenericVnf(final GenericVnf vnf) {
        vnf.setSelflink("http://vnfm:8080/vnfs/myTestVnfIdOnVnfm");
    }

    private void addRelationshipFromGenericVnfToVnfm(final GenericVnf genericVnf, final String vnfmId) {
        final Relationship relationshipToVnfm = new Relationship();
        relationshipToVnfm
                .setRelatedLink("/aai/" + AAIVersion.LATEST + "/external-system/esr-vnfm-list/esr-vnfm/" + vnfmId);
        relationshipToVnfm.setRelatedTo("esr-vnfm");
        final RelationshipData relationshipData = new RelationshipData();
        relationshipData.setRelationshipKey("esr-vnfm.vnfm-id");
        relationshipData.setRelationshipValue(vnfmId);
        relationshipToVnfm.getRelationshipData().add(relationshipData);

        final RelationshipList relationshipList = new RelationshipList();
        relationshipList.getRelationship().add(relationshipToVnfm);
        genericVnf.setRelationshipList(relationshipList);
    }

    private void setUpVnfmsInMockAai() {
        final EsrSystemInfo esrSystemInfo1 = new EsrSystemInfo();
        esrSystemInfo1.setServiceUrl("http://vnfm1:8080");
        esrSystemInfo1.setType("vnfmType1");
        esrSystemInfo1.setSystemType("VNFM");
        final EsrSystemInfoList esrSystemInfoList1 = new EsrSystemInfoList();
        esrSystemInfoList1.getEsrSystemInfo().add(esrSystemInfo1);

        final EsrVnfm esrVnfm1 = new EsrVnfm();
        esrVnfm1.setVnfmId("vnfm1");
        esrVnfm1.setEsrSystemInfoList(esrSystemInfoList1);
        esrVnfm1.setResourceVersion("1234");

        final EsrSystemInfo esrSystemInfo2 = new EsrSystemInfo();
        esrSystemInfo2.setServiceUrl("http://vnfm2:8080");
        esrSystemInfo2.setType("vnfmType2");
        esrSystemInfo2.setSystemType("VNFM");
        final EsrSystemInfoList esrSystemInfoList2 = new EsrSystemInfoList();
        esrSystemInfoList2.getEsrSystemInfo().add(esrSystemInfo2);

        final EsrVnfm esrVnfm2 = new EsrVnfm();
        esrVnfm2.setVnfmId("vnfm2");
        esrVnfm2.setEsrSystemInfoList(esrSystemInfoList2);
        esrVnfm2.setResourceVersion("1234");

        final EsrVnfmList esrVnfmList = new EsrVnfmList();
        esrVnfmList.getEsrVnfm().add(esrVnfm1);
        esrVnfmList.getEsrVnfm().add(esrVnfm2);

        doReturn(Optional.of(esrVnfm1)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest
                .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm1?depth=1")));

        doReturn(Optional.of(esrVnfm2)).when(aaiResourcesClient).get(eq(EsrVnfm.class), MockitoHamcrest
                .argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list/esr-vnfm/vnfm2?depth=1")));

        doReturn(Optional.of(esrVnfmList)).when(aaiResourcesClient).get(eq(EsrVnfmList.class),
                MockitoHamcrest.argThat(new AaiResourceUriMatcher("/external-system/esr-vnfm-list")));

        doReturn(Optional.of(esrSystemInfoList1)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class),
                MockitoHamcrest.argThat(new AaiResourceUriMatcher(
                        "/external-system/esr-vnfm-list/esr-vnfm/vnfm1/esr-system-info-list")));
        doReturn(Optional.of(esrSystemInfoList2)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class),
                MockitoHamcrest.argThat(new AaiResourceUriMatcher(
                        "/external-system/esr-vnfm-list/esr-vnfm/vnfm2/esr-system-info-list")));
    }

    private void setUpVimInMockAai() {
        final EsrSystemInfo esrSystemInfo = new EsrSystemInfo();
        esrSystemInfo.setServiceUrl("http://myVim:8080");
        esrSystemInfo.setType("openstack");
        esrSystemInfo.setSystemType("VIM");
        esrSystemInfo.setCloudDomain("myDomain");
        esrSystemInfo.setUserName("myUser");
        esrSystemInfo.setPassword("myPassword");

        final EsrSystemInfoList esrSystemInfoList = new EsrSystemInfoList();
        esrSystemInfoList.getEsrSystemInfo().add(esrSystemInfo);

        doReturn(Optional.of(esrSystemInfoList)).when(aaiResourcesClient).get(eq(EsrSystemInfoList.class),
                MockitoHamcrest.argThat(new AaiResourceUriMatcher("/cloud-infrastructure/cloud-regions/cloud-region/"
                        + CLOUD_OWNER + "/" + REGION + "/esr-system-info-list")));
    }

    private InlineResponse201 createCreateResponse() {
        final InlineResponse201 createResponse = new InlineResponse201();
        createResponse.setVnfdId("myTestVnfd");
        final InlineResponse201Links links = new InlineResponse201Links();
        final InlineResponse201LinksSelf self = new InlineResponse201LinksSelf();
        self.setHref("http://vnfm2:8080/vnf_instances/vnfId");
        links.setSelf(self);
        createResponse.setLinks(links);
        createResponse.setId("vnfId");
        return createResponse;
    }


    private class AaiResourceUriMatcher extends BaseMatcher<AAIBaseResourceUri<?, ?>> {

        final String uriAsString;

        public AaiResourceUriMatcher(final String uriAsString) {
            this.uriAsString = uriAsString;
        }

        @Override
        public boolean matches(final Object item) {
            if (item instanceof AAIBaseResourceUri<?, ?>) {
                if (uriAsString.endsWith("...")) {
                    return ((AAIBaseResourceUri<?, ?>) item).build().toString()
                            .startsWith(uriAsString.substring(0, uriAsString.indexOf("...")));
                }
                return ((AAIBaseResourceUri<?, ?>) item).build().toString().equals(uriAsString);
            }
            return false;
        }

        @Override
        public void describeTo(final Description description) {}

    }

}