aboutsummaryrefslogtreecommitdiffstats
path: root/so-etsi-nfvo/so-etsi-nfvo-ns-lcm/so-etsi-nfvo-ns-lcm-bpmn-flows/src/test/java/org/onap/so/etsi/nfvo/ns/workflow/engine/tasks/TerminateNsTaskTest.java
blob: b821c85eddc542d039b4275d0611f10051d652ab (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
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2020 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.etsi.nfvo.ns.workflow.engine.tasks;

import com.google.gson.Gson;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.hamcrest.text.MatchesPattern;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.DeleteVnfResponse;
import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStatusRetrievalStatusEnum;
import org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.BaseTest;
import org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.GsonProvider;
import org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.exceptions.NsRequestProcessingException;
import org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.service.JobExecutorService;
import org.onap.so.etsi.nfvo.ns.lcm.database.beans.NfvoJob;
import org.onap.so.etsi.nfvo.ns.lcm.database.beans.NfvoNfInst;
import org.onap.so.etsi.nfvo.ns.lcm.database.beans.NfvoNsInst;
import org.onap.so.etsi.nfvo.ns.lcm.database.beans.NsLcmOpOcc;
import org.onap.so.etsi.nfvo.ns.lcm.database.beans.OperationStateEnum;
import org.onap.so.etsi.nfvo.ns.lcm.database.beans.State;
import org.onap.so.etsi.nfvo.ns.lcm.model.TerminateNsRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_REST_TEMPLATE_BEAN;
import static org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.extclients.vnfm.Sol003AdapterConfiguration.SOL003_ADAPTER_REST_TEMPLATE_BEAN;
import static org.springframework.test.web.client.ExpectedCount.times;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

/**
 * @author Andrew Lamb (andrew.a.lamb@est.tech)
 *
 */
public class TerminateNsTaskTest extends BaseTest {

    @Autowired
    @Qualifier(SOL003_ADAPTER_REST_TEMPLATE_BEAN)
    private RestTemplate sol003AdapterRestTemplate;

    private MockRestServiceServer mockSol003AdapterRestServiceServer;

    @Autowired
    private JobExecutorService objUnderTest;

    @Autowired
    private GsonProvider gsonProvider;

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    private Gson gson;

    @Before
    public void before() {
        wireMockServer.resetAll();
        gson = gsonProvider.getGson();
        mockSol003AdapterRestServiceServer =
                MockRestServiceServer.bindTo(sol003AdapterRestTemplate).ignoreExpectOrder(true).build();
        sol003AdapterRestTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson));
    }

    @After
    public void after() {
        wireMockServer.resetAll();
    }

    @Test
    public void testRunTerminateNsJob_timeSetInTerminateRequest_throwsNsRequestProcessingException() {
        final String nsInstanceId = UUID.randomUUID().toString();
        final TerminateNsRequest terminateNsRequest = new TerminateNsRequest().terminationTime(LocalDateTime.now());
        final String message = "TerminateNsRequest received with terminateTime: "
                + terminateNsRequest.getTerminationTime()
                + "\nOnly immediate Terminate requests are currently supported \n(i.e., terminateTime field must not be set).";
        expectedException.expect(NsRequestProcessingException.class);
        expectedException.expectMessage(message);
        objUnderTest.runTerminateNsJob(nsInstanceId, terminateNsRequest);
    }

    @Test
    public void testRunTerminateNsJob_NsInstNotInDb_throwsNsRequestProcessingException() {
        final String nsInstanceId = UUID.randomUUID().toString();
        final TerminateNsRequest terminateNsRequest = new TerminateNsRequest();
        final String message = "No matching NS Instance for id: " + nsInstanceId + " found in database.";
        assertThat(databaseServiceProvider.getNfvoNsInst(nsInstanceId)).isEmpty();
        expectedException.expect(NsRequestProcessingException.class);
        expectedException.expectMessage(message);
        objUnderTest.runTerminateNsJob(nsInstanceId, terminateNsRequest);
    }

    @Test
    public void testTerminateNsTask_SuccessfulCase() throws InterruptedException, IOException {
        final String nsInstanceId = UUID.randomUUID().toString();
        addDummyNsToDatabase(nsInstanceId);
        mockSol003AdapterEndpoints();
        mockAAIEndpoints();

        final String nsLcmOpOccId = objUnderTest.runTerminateNsJob(nsInstanceId, new TerminateNsRequest());

        final Optional<NfvoJob> optional = getJobByResourceId(nsInstanceId);
        assertTrue(optional.isPresent());
        final NfvoJob nfvoJob = optional.get();

        // Confirm Process finishes in STATE_COMPLETED
        assertTrue(waitForProcessInstanceToFinish(nfvoJob.getProcessInstanceId()));
        final HistoricProcessInstance historicProcessInstance =
                getHistoricProcessInstance(nfvoJob.getProcessInstanceId());
        assertNotNull(historicProcessInstance);
        assertEquals(HistoricProcessInstance.STATE_COMPLETED, historicProcessInstance.getState());

        // Confirm NS Instance set to NOT_INSTANTIATED and related NF Instances Deleted
        final Optional<NfvoNsInst> optionalNfvoNsInst = databaseServiceProvider.getNfvoNsInst(nsInstanceId);
        assertTrue(optionalNfvoNsInst.isPresent());
        final NfvoNsInst nfvoNsInst = optionalNfvoNsInst.get();
        assertEquals(State.NOT_INSTANTIATED, nfvoNsInst.getStatus());
        final List<NfvoNfInst> nfvoNfInsts = databaseServiceProvider.getNfvoNfInstByNsInstId(nsInstanceId);
        assertTrue(nfvoNfInsts.isEmpty());

        // Confirm NS LCM OP OCC Job set to Completed
        final Optional<NsLcmOpOcc> optionalNsLcmOpOcc = databaseServiceProvider.getNsLcmOpOcc(nsLcmOpOccId);
        assertTrue(optionalNsLcmOpOcc.isPresent());
        final NsLcmOpOcc nsLcmOpOcc = optionalNsLcmOpOcc.get();
        assertEquals(OperationStateEnum.COMPLETED, nsLcmOpOcc.getOperationState());
    }

    private void addDummyNsToDatabase(final String nsInstanceId) {
        final String nsPackageId = UUID.randomUUID().toString();
        final NfvoNsInst nfvoNsInst =
                new NfvoNsInst().nsInstId(nsInstanceId).name("nsName").nsPackageId(nsPackageId).nsdId("nsdId")
                        .nsdInvariantId("nsdId").status(State.INSTANTIATED).statusUpdatedTime(LocalDateTime.now());
        databaseServiceProvider.saveNfvoNsInst(nfvoNsInst);
        addDummyNfToDatabase(nfvoNsInst);
        addDummyNfToDatabase(nfvoNsInst);
        addDummyNfToDatabase(nfvoNsInst);
    }

    private void addDummyNfToDatabase(final NfvoNsInst nfvoNsInst) {
        final LocalDateTime localDateTime = LocalDateTime.now();
        final String nfPackageId = UUID.randomUUID().toString();
        final NfvoNfInst nfvoNfInst =
                new NfvoNfInst().status(State.INSTANTIATED).createTime(localDateTime).lastUpdateTime(localDateTime)
                        .name("nfName").vnfdId("vnfdId").packageId(nfPackageId).nfvoNsInst(nfvoNsInst);
        databaseServiceProvider.saveNfvoNfInst(nfvoNfInst);
    }

    private void mockSol003AdapterEndpoints() {
        final int numTimes = 3;

        mockSol003AdapterRestServiceServer
                .expect(times(numTimes),
                        requestTo(MatchesPattern.matchesPattern(SOL003_ADAPTER_ENDPOINT_URL + "/vnfs/.*")))
                .andExpect(method(HttpMethod.DELETE))
                .andRespond(withSuccess(gson.toJson(new DeleteVnfResponse().jobId(UUID.randomUUID().toString())),
                        MediaType.APPLICATION_JSON));

        mockSol003AdapterRestServiceServer
                .expect(times(numTimes),
                        requestTo(MatchesPattern.matchesPattern(SOL003_ADAPTER_ENDPOINT_URL + "/jobs/.*")))
                .andExpect(method(HttpMethod.GET))
                .andRespond(withSuccess(gson.toJson(
                        new org.onap.so.adapters.etsisol003adapter.lcm.v1.model.QueryJobResponse().operationState(
                                org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStateEnum.COMPLETED)
                                .operationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND)),
                        MediaType.APPLICATION_JSON));
    }

    private void mockAAIEndpoints() {
        final String modelEndpoint = "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + UUID_REGEX;
        final String resourceVersion = "12345";

        final String body =
                "{\"resource-version\": \"" + resourceVersion + "\",\n\"orchestration-status\": \"Assigned\"}";
        wireMockServer.stubFor(get(urlMatching(modelEndpoint)).willReturn(ok()).willReturn(okJson(body)));

        wireMockServer.stubFor(
                delete(urlMatching(modelEndpoint + "\\?resource-version=" + resourceVersion)).willReturn(ok()));
    }

}