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