b821c85eddc542d039b4275d0611f10051d652ab
[so.git] / 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
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 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 package org.onap.so.etsi.nfvo.ns.workflow.engine.tasks;
21
22 import com.google.gson.Gson;
23 import org.camunda.bpm.engine.history.HistoricProcessInstance;
24 import org.hamcrest.text.MatchesPattern;
25 import org.junit.After;
26 import org.junit.Before;
27 import org.junit.Rule;
28 import org.junit.Test;
29 import org.junit.rules.ExpectedException;
30 import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.DeleteVnfResponse;
31 import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStatusRetrievalStatusEnum;
32 import org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.BaseTest;
33 import org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.GsonProvider;
34 import org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.exceptions.NsRequestProcessingException;
35 import org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.service.JobExecutorService;
36 import org.onap.so.etsi.nfvo.ns.lcm.database.beans.NfvoJob;
37 import org.onap.so.etsi.nfvo.ns.lcm.database.beans.NfvoNfInst;
38 import org.onap.so.etsi.nfvo.ns.lcm.database.beans.NfvoNsInst;
39 import org.onap.so.etsi.nfvo.ns.lcm.database.beans.NsLcmOpOcc;
40 import org.onap.so.etsi.nfvo.ns.lcm.database.beans.OperationStateEnum;
41 import org.onap.so.etsi.nfvo.ns.lcm.database.beans.State;
42 import org.onap.so.etsi.nfvo.ns.lcm.model.TerminateNsRequest;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.beans.factory.annotation.Qualifier;
45 import org.springframework.http.HttpMethod;
46 import org.springframework.http.MediaType;
47 import org.springframework.http.converter.json.GsonHttpMessageConverter;
48 import org.springframework.test.web.client.MockRestServiceServer;
49 import org.springframework.web.client.RestTemplate;
50 import java.io.IOException;
51 import java.time.LocalDateTime;
52 import java.util.List;
53 import java.util.Optional;
54 import java.util.UUID;
55 import static com.github.tomakehurst.wiremock.client.WireMock.delete;
56 import static com.github.tomakehurst.wiremock.client.WireMock.get;
57 import static com.github.tomakehurst.wiremock.client.WireMock.ok;
58 import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
59 import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
60 import static org.assertj.core.api.Assertions.assertThat;
61 import static org.junit.Assert.assertEquals;
62 import static org.junit.Assert.assertNotNull;
63 import static org.junit.Assert.assertTrue;
64 import static org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_REST_TEMPLATE_BEAN;
65 import static org.onap.so.etsi.nfvo.ns.lcm.bpmn.flows.extclients.vnfm.Sol003AdapterConfiguration.SOL003_ADAPTER_REST_TEMPLATE_BEAN;
66 import static org.springframework.test.web.client.ExpectedCount.times;
67 import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
68 import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
69 import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
70
71 /**
72  * @author Andrew Lamb (andrew.a.lamb@est.tech)
73  *
74  */
75 public class TerminateNsTaskTest extends BaseTest {
76
77     @Autowired
78     @Qualifier(SOL003_ADAPTER_REST_TEMPLATE_BEAN)
79     private RestTemplate sol003AdapterRestTemplate;
80
81     private MockRestServiceServer mockSol003AdapterRestServiceServer;
82
83     @Autowired
84     private JobExecutorService objUnderTest;
85
86     @Autowired
87     private GsonProvider gsonProvider;
88
89     @Rule
90     public ExpectedException expectedException = ExpectedException.none();
91
92     private Gson gson;
93
94     @Before
95     public void before() {
96         wireMockServer.resetAll();
97         gson = gsonProvider.getGson();
98         mockSol003AdapterRestServiceServer =
99                 MockRestServiceServer.bindTo(sol003AdapterRestTemplate).ignoreExpectOrder(true).build();
100         sol003AdapterRestTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson));
101     }
102
103     @After
104     public void after() {
105         wireMockServer.resetAll();
106     }
107
108     @Test
109     public void testRunTerminateNsJob_timeSetInTerminateRequest_throwsNsRequestProcessingException() {
110         final String nsInstanceId = UUID.randomUUID().toString();
111         final TerminateNsRequest terminateNsRequest = new TerminateNsRequest().terminationTime(LocalDateTime.now());
112         final String message = "TerminateNsRequest received with terminateTime: "
113                 + terminateNsRequest.getTerminationTime()
114                 + "\nOnly immediate Terminate requests are currently supported \n(i.e., terminateTime field must not be set).";
115         expectedException.expect(NsRequestProcessingException.class);
116         expectedException.expectMessage(message);
117         objUnderTest.runTerminateNsJob(nsInstanceId, terminateNsRequest);
118     }
119
120     @Test
121     public void testRunTerminateNsJob_NsInstNotInDb_throwsNsRequestProcessingException() {
122         final String nsInstanceId = UUID.randomUUID().toString();
123         final TerminateNsRequest terminateNsRequest = new TerminateNsRequest();
124         final String message = "No matching NS Instance for id: " + nsInstanceId + " found in database.";
125         assertThat(databaseServiceProvider.getNfvoNsInst(nsInstanceId)).isEmpty();
126         expectedException.expect(NsRequestProcessingException.class);
127         expectedException.expectMessage(message);
128         objUnderTest.runTerminateNsJob(nsInstanceId, terminateNsRequest);
129     }
130
131     @Test
132     public void testTerminateNsTask_SuccessfulCase() throws InterruptedException, IOException {
133         final String nsInstanceId = UUID.randomUUID().toString();
134         addDummyNsToDatabase(nsInstanceId);
135         mockSol003AdapterEndpoints();
136         mockAAIEndpoints();
137
138         final String nsLcmOpOccId = objUnderTest.runTerminateNsJob(nsInstanceId, new TerminateNsRequest());
139
140         final Optional<NfvoJob> optional = getJobByResourceId(nsInstanceId);
141         assertTrue(optional.isPresent());
142         final NfvoJob nfvoJob = optional.get();
143
144         // Confirm Process finishes in STATE_COMPLETED
145         assertTrue(waitForProcessInstanceToFinish(nfvoJob.getProcessInstanceId()));
146         final HistoricProcessInstance historicProcessInstance =
147                 getHistoricProcessInstance(nfvoJob.getProcessInstanceId());
148         assertNotNull(historicProcessInstance);
149         assertEquals(HistoricProcessInstance.STATE_COMPLETED, historicProcessInstance.getState());
150
151         // Confirm NS Instance set to NOT_INSTANTIATED and related NF Instances Deleted
152         final Optional<NfvoNsInst> optionalNfvoNsInst = databaseServiceProvider.getNfvoNsInst(nsInstanceId);
153         assertTrue(optionalNfvoNsInst.isPresent());
154         final NfvoNsInst nfvoNsInst = optionalNfvoNsInst.get();
155         assertEquals(State.NOT_INSTANTIATED, nfvoNsInst.getStatus());
156         final List<NfvoNfInst> nfvoNfInsts = databaseServiceProvider.getNfvoNfInstByNsInstId(nsInstanceId);
157         assertTrue(nfvoNfInsts.isEmpty());
158
159         // Confirm NS LCM OP OCC Job set to Completed
160         final Optional<NsLcmOpOcc> optionalNsLcmOpOcc = databaseServiceProvider.getNsLcmOpOcc(nsLcmOpOccId);
161         assertTrue(optionalNsLcmOpOcc.isPresent());
162         final NsLcmOpOcc nsLcmOpOcc = optionalNsLcmOpOcc.get();
163         assertEquals(OperationStateEnum.COMPLETED, nsLcmOpOcc.getOperationState());
164     }
165
166     private void addDummyNsToDatabase(final String nsInstanceId) {
167         final String nsPackageId = UUID.randomUUID().toString();
168         final NfvoNsInst nfvoNsInst =
169                 new NfvoNsInst().nsInstId(nsInstanceId).name("nsName").nsPackageId(nsPackageId).nsdId("nsdId")
170                         .nsdInvariantId("nsdId").status(State.INSTANTIATED).statusUpdatedTime(LocalDateTime.now());
171         databaseServiceProvider.saveNfvoNsInst(nfvoNsInst);
172         addDummyNfToDatabase(nfvoNsInst);
173         addDummyNfToDatabase(nfvoNsInst);
174         addDummyNfToDatabase(nfvoNsInst);
175     }
176
177     private void addDummyNfToDatabase(final NfvoNsInst nfvoNsInst) {
178         final LocalDateTime localDateTime = LocalDateTime.now();
179         final String nfPackageId = UUID.randomUUID().toString();
180         final NfvoNfInst nfvoNfInst =
181                 new NfvoNfInst().status(State.INSTANTIATED).createTime(localDateTime).lastUpdateTime(localDateTime)
182                         .name("nfName").vnfdId("vnfdId").packageId(nfPackageId).nfvoNsInst(nfvoNsInst);
183         databaseServiceProvider.saveNfvoNfInst(nfvoNfInst);
184     }
185
186     private void mockSol003AdapterEndpoints() {
187         final int numTimes = 3;
188
189         mockSol003AdapterRestServiceServer
190                 .expect(times(numTimes),
191                         requestTo(MatchesPattern.matchesPattern(SOL003_ADAPTER_ENDPOINT_URL + "/vnfs/.*")))
192                 .andExpect(method(HttpMethod.DELETE))
193                 .andRespond(withSuccess(gson.toJson(new DeleteVnfResponse().jobId(UUID.randomUUID().toString())),
194                         MediaType.APPLICATION_JSON));
195
196         mockSol003AdapterRestServiceServer
197                 .expect(times(numTimes),
198                         requestTo(MatchesPattern.matchesPattern(SOL003_ADAPTER_ENDPOINT_URL + "/jobs/.*")))
199                 .andExpect(method(HttpMethod.GET))
200                 .andRespond(withSuccess(gson.toJson(
201                         new org.onap.so.adapters.etsisol003adapter.lcm.v1.model.QueryJobResponse().operationState(
202                                 org.onap.so.adapters.etsisol003adapter.lcm.v1.model.OperationStateEnum.COMPLETED)
203                                 .operationStatusRetrievalStatus(OperationStatusRetrievalStatusEnum.STATUS_FOUND)),
204                         MediaType.APPLICATION_JSON));
205     }
206
207     private void mockAAIEndpoints() {
208         final String modelEndpoint = "/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + UUID_REGEX;
209         final String resourceVersion = "12345";
210
211         final String body =
212                 "{\"resource-version\": \"" + resourceVersion + "\",\n\"orchestration-status\": \"Assigned\"}";
213         wireMockServer.stubFor(get(urlMatching(modelEndpoint)).willReturn(ok()).willReturn(okJson(body)));
214
215         wireMockServer.stubFor(
216                 delete(urlMatching(modelEndpoint + "\\?resource-version=" + resourceVersion)).willReturn(ok()));
217     }
218
219 }