cd54c4967110b66bc88011d7ef4183579442c311
[so.git] /
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
21 package org.onap.so.bpmn.infrastructure.process;
22
23 import static com.github.tomakehurst.wiremock.client.WireMock.get;
24 import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
25 import static com.github.tomakehurst.wiremock.client.WireMock.put;
26 import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
27 import static org.assertj.core.api.Assertions.fail;
28 import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareTests.assertThat;
29 import static org.junit.Assert.assertEquals;
30 import static org.junit.Assert.assertTrue;
31 import java.io.IOException;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.UUID;
36 import org.assertj.core.api.Assertions;
37 import org.camunda.bpm.engine.runtime.ProcessInstance;
38 import org.junit.Before;
39 import org.junit.Test;
40 import org.onap.aaiclient.client.aai.AAIVersion;
41 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
42 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
43 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
44 import org.onap.so.BaseBPMNTest;
45 import org.onap.so.GrpcNettyServer;
46 import org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames;
47 import org.onap.so.bpmn.mock.FileUtil;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import com.google.protobuf.Struct;
52
53 /**
54  * Basic Integration test for GenericPnfSWUPDownloadTest.bpmn workflow.
55  */
56 public class GenericPnfSWUPDownloadTest extends BaseBPMNTest {
57
58     private final Logger logger = LoggerFactory.getLogger(getClass());
59
60     private static final long WORKFLOW_WAIT_TIME = 1000L;
61
62     private static final String TEST_PROCESSINSTANCE_KEY = "GenericPnfSWUPDownload";
63     private static final AAIVersion VERSION = AAIVersion.LATEST;
64     private static final Map<String, Object> executionVariables = new HashMap();
65     private final String[] actionNames = new String[3];
66     private String responseObject;
67     private String requestObject;
68
69     @Autowired
70     private GrpcNettyServer grpcNettyServer;
71
72     @Before
73     public void setUp() throws IOException {
74
75         actionNames[0] = "preCheck";
76         actionNames[1] = "downloadNESw";
77         actionNames[2] = "postCheck";
78
79         executionVariables.clear();
80
81         requestObject = FileUtil.readResourceFile("request/GenericPnfSoftwareUpgradeTest.json");
82         responseObject = FileUtil.readResourceFile("response/GenericPnfSoftwareUpgradeTest.json");
83
84         executionVariables.put("bpmnRequest", requestObject);
85
86         /**
87          * This variable indicates that the flow was invoked asynchronously. It's injected by {@link WorkflowProcessor}.
88          */
89         executionVariables.put("isAsyncProcess", "true");
90         executionVariables.put(ExecutionVariableNames.PRC_CUSTOMIZATION_UUID, "38dc9a92-214c-11e7-93ae-92361f002680");
91
92         /**
93          * Temporary solution to add pnfCorrelationId to context. this value is getting from the request to SO api
94          * handler and then convert to CamudaInput
95          */
96         executionVariables.put(ExecutionVariableNames.PNF_CORRELATION_ID, "PNFDemo");
97     }
98
99
100     @Test
101     public void workflow_validInput_expectedOutput() throws InterruptedException {
102
103         mockCatalogDb();
104         mockAai();
105         grpcNettyServer.resetList();
106
107         final String msoRequestId = UUID.randomUUID().toString();
108         executionVariables.put(ExecutionVariableNames.MSO_REQUEST_ID, msoRequestId);
109
110         final String testBusinessKey = UUID.randomUUID().toString();
111         logger.info("Test the process instance: {} with business key: {}", TEST_PROCESSINSTANCE_KEY, testBusinessKey);
112
113         ProcessInstance pi =
114                 runtimeService.startProcessInstanceByKey(TEST_PROCESSINSTANCE_KEY, testBusinessKey, executionVariables);
115
116         int waitCount = 10;
117         while (!isProcessInstanceEnded() && waitCount >= 0) {
118             Thread.sleep(WORKFLOW_WAIT_TIME);
119             waitCount--;
120         }
121
122         // Layout is to reflect the bpmn visual layout
123         assertThat(pi).isStarted().hasPassedInOrder("download_StartEvent", "ServiceTask_1mpt2eq", "ServiceTask_1nl90ao",
124                 "ExclusiveGateway_1rj84ne", "ServiceTask_0yavde3", "ExclusiveGateway_1ja7grm", "ServiceTask_1wxo7xz",
125                 "ExclusiveGateway_08lusga", "download_EndEvent");
126
127         List<ExecutionServiceInput> detailedMessages = grpcNettyServer.getDetailedMessages();
128         assertEquals(3, detailedMessages.size());
129         int count = 0;
130         try {
131             for (ExecutionServiceInput eSI : detailedMessages) {
132                 for (String action : actionNames) {
133                     if (action.equals(eSI.getActionIdentifiers().getActionName())
134                             && eSI.getCommonHeader().getRequestId().equals(msoRequestId)) {
135                         checkWithActionName(eSI, action, msoRequestId);
136                         count++;
137                     }
138                 }
139             }
140         } catch (Exception e) {
141             e.printStackTrace();
142             fail("GenericPnfSWUPDownload request exception", e);
143         }
144         assertTrue(count == actionNames.length);
145     }
146
147     private boolean isProcessInstanceEnded() {
148         return runtimeService.createProcessInstanceQuery().processDefinitionKey(TEST_PROCESSINSTANCE_KEY)
149                 .singleResult() == null;
150     }
151
152     private void checkWithActionName(ExecutionServiceInput executionServiceInput, String action, String msoRequestId) {
153
154         logger.info("Checking the " + action + " request");
155         ActionIdentifiers actionIdentifiers = executionServiceInput.getActionIdentifiers();
156
157         /**
158          * the fields of actionIdentifiers should match the one in the
159          * response/GenericPnfSoftwareUpgradeTest_catalogdb.json.
160          */
161         Assertions.assertThat(actionIdentifiers.getBlueprintName()).isEqualTo("test_pnf_software_upgrade_restconf");
162         Assertions.assertThat(actionIdentifiers.getBlueprintVersion()).isEqualTo("1.0.0");
163         Assertions.assertThat(actionIdentifiers.getActionName()).isEqualTo(action);
164         Assertions.assertThat(actionIdentifiers.getMode()).isEqualTo("async");
165
166         CommonHeader commonHeader = executionServiceInput.getCommonHeader();
167         Assertions.assertThat(commonHeader.getOriginatorId()).isEqualTo("SO");
168         Assertions.assertThat(commonHeader.getRequestId()).isEqualTo(msoRequestId);
169
170         Struct payload = executionServiceInput.getPayload();
171         Struct requeststruct = payload.getFieldsOrThrow(action + "-request").getStructValue();
172
173         Assertions.assertThat(requeststruct.getFieldsOrThrow("resolution-key").getStringValue()).isEqualTo("PNFDemo");
174         Struct propertiesStruct = requeststruct.getFieldsOrThrow(action + "-properties").getStructValue();
175
176         Assertions.assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).isEqualTo("PNFDemo");
177         Assertions.assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue())
178                 .isEqualTo("32daaac6-5017-4e1e-96c8-6a27dfbe1421");
179         Assertions.assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue())
180                 .isEqualTo("38dc9a92-214c-11e7-93ae-92361f002680");
181         Assertions.assertThat(propertiesStruct.getFieldsOrThrow("target-software-version").getStringValue())
182                 .isEqualTo("demo-sw-ver2.0.0");
183     }
184
185     private void mockAai() {
186
187         String aaiPnfEntry =
188                 "{  \n" + "   \"pnf-name\":\"PNFDemo\",\n" + "   \"pnf-id\":\"testtest\",\n" + "   \"in-maint\":true,\n"
189                         + "   \"resource-version\":\"1541720264047\",\n" + "   \"swVersion\":\"demo-1.1\",\n"
190                         + "   \"ipaddress-v4-oam\":\"1.1.1.1\",\n" + "   \"ipaddress-v6-oam\":\"::/128\"\n" + "}";
191
192         /**
193          * PUT the PNF correlation ID to AAI.
194          */
195         wireMockServer.stubFor(put(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")));
196
197         /**
198          * Get the PNF entry from AAI.
199          */
200         wireMockServer.stubFor(
201                 get(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")).willReturn(okJson(aaiPnfEntry)));
202     }
203
204     /**
205      * Mock the catalobdb rest interface.
206      */
207     private void mockCatalogDb() {
208
209         String catalogdbClientResponse =
210                 FileUtil.readResourceFile("response/GenericPnfSoftwareUpgradeTest_catalogdb.json");
211
212
213         /**
214          * Return valid json for the model UUID in the request file.
215          */
216         wireMockServer
217                 .stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelUuid=32daaac6-5017-4e1e-96c8-6a27dfbe1421"))
218                         .willReturn(okJson(responseObject)));
219
220         /**
221          * Return valid json for the service model InvariantUUID as specified in the request file.
222          */
223         wireMockServer.stubFor(
224                 get(urlEqualTo("/v2/serviceResources?serviceModelInvariantUuid=339b7a2f-9524-4dbf-9eee-f2e05521df3f"))
225                         .willReturn(okJson(responseObject)));
226
227         /**
228          * Return valid spring data rest json for the service model UUID as specified in the request file.
229          */
230         wireMockServer.stubFor(get(urlEqualTo(
231                 "/pnfResourceCustomization/search/findPnfResourceCustomizationByModelUuid?SERVICE_MODEL_UUID=32daaac6-5017-4e1e-96c8-6a27dfbe1421"))
232                         .willReturn(okJson(catalogdbClientResponse)));
233     }
234
235 }