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