22cf72b262ce034f60585c01bb580b0b71b233da
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Nordix Foundation.
4  *  Modifications Copyright (C) 2020 Huawei Technologies Co., Ltd.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.so.bpmn.infrastructure.process;
23
24 import com.google.protobuf.Struct;
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.aaiclient.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.post;
48 import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
49 import static org.assertj.core.api.Assertions.fail;
50 import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
51
52 /**
53  * Basic Integration test for PNFSoftwareUpgrade.bpmn workflow.
54  */
55 public class PNFSoftwareUpgradeTest 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 = "PNFSoftwareUpgrade";
62     private static final AAIVersion VERSION = AAIVersion.LATEST;
63     private static final Map<String, Object> executionVariables = new HashMap();
64     private static final String REQUEST_ID = "50ae41ad-049c-4fe2-9950-539f111120f5";
65     private final String[] actionNames = new String[4];
66     private String requestObject;
67     private String responseObject;
68
69     @Autowired
70     private GrpcNettyServer grpcNettyServer;
71
72     @Before
73     public void setUp() throws IOException {
74         actionNames[0] = "preCheck";
75         actionNames[1] = "downloadNESw";
76         actionNames[2] = "activateNESw";
77         actionNames[3] = "postCheck";
78
79         executionVariables.clear();
80
81         requestObject = FileUtil.readResourceFile("request/" + getClass().getSimpleName() + ".json");
82         responseObject = FileUtil.readResourceFile("response/" + getClass().getSimpleName() + ".json");
83
84         executionVariables.put("bpmnRequest", requestObject);
85         executionVariables.put("requestId", REQUEST_ID);
86
87         /**
88          * This variable indicates that the flow was invoked asynchronously. It's injected by {@link WorkflowProcessor}.
89          */
90         executionVariables.put("isAsyncProcess", "true");
91         executionVariables.put(ExecutionVariableNames.PRC_CUSTOMIZATION_UUID, "38dc9a92-214c-11e7-93ae-92361f002680");
92
93         /**
94          * Temporary solution to add pnfCorrelationId to context. this value is getting from the request to SO api
95          * handler and then convert to CamudaInput
96          */
97         executionVariables.put(ExecutionVariableNames.PNF_CORRELATION_ID, "PNFDemo");
98     }
99
100
101     @Test
102     public void workflow_validInput_expectedOutput() throws InterruptedException {
103
104         mockCatalogDb();
105         mockRequestDb();
106         mockAai();
107
108         final String msoRequestId = UUID.randomUUID().toString();
109         executionVariables.put(ExecutionVariableNames.MSO_REQUEST_ID, msoRequestId);
110
111         final String testBusinessKey = UUID.randomUUID().toString();
112         logger.info("Test the process instance: {} with business key: {}", TEST_PROCESSINSTANCE_KEY, testBusinessKey);
113
114         ProcessInstance pi =
115                 runtimeService.startProcessInstanceByKey(TEST_PROCESSINSTANCE_KEY, testBusinessKey, executionVariables);
116
117         int waitCount = 10;
118         while (!isProcessInstanceEnded() && waitCount >= 0) {
119             Thread.sleep(WORKFLOW_WAIT_TIME);
120             waitCount--;
121         }
122
123         // Layout is to reflect the bpmn visual layout
124         assertThat(pi).isEnded().hasPassedInOrder("softwareUpgrade_startEvent", "ServiceTask_042uz7n",
125                 "ScriptTask_10klpg8", "ServiceTask_0slpahe", "ExclusiveGateway_0x6h0ni", "ServiceTask_0x5cje8",
126                 "ExclusiveGateway_0v3l3wv", "ServiceTask_02lxf48", "ExclusiveGateway_0ch3fef", "ServiceTask_0y2uysu",
127                 "ExclusiveGateway_1ny9b1z", "ScriptTask_1igtc83", "CallActivity_0o1mi8u", "softwareUpgrade_endEvent");
128
129         List<ExecutionServiceInput> detailedMessages = grpcNettyServer.getDetailedMessages();
130         assertThat(detailedMessages.size() == 4);
131         int count = 0;
132         try {
133             for (ExecutionServiceInput eSI : detailedMessages) {
134                 for (String action : actionNames) {
135                     if (action.equals(eSI.getActionIdentifiers().getActionName())
136                             && eSI.getCommonHeader().getRequestId().equals(msoRequestId)) {
137                         checkWithActionName(eSI, action);
138                         count++;
139                     }
140                 }
141             }
142         } catch (Exception e) {
143             e.printStackTrace();
144             fail("PNFSoftwareUpgrade request exception", e);
145         }
146         assertThat(count == actionNames.length);
147     }
148
149     private boolean isProcessInstanceEnded() {
150         return runtimeService.createProcessInstanceQuery().processDefinitionKey(TEST_PROCESSINSTANCE_KEY)
151                 .singleResult() == null;
152     }
153
154     private void checkWithActionName(ExecutionServiceInput executionServiceInput, String action) {
155
156         logger.info("Checking the " + action + " request");
157         ActionIdentifiers actionIdentifiers = executionServiceInput.getActionIdentifiers();
158
159         /**
160          * the fields of actionIdentifiers should match the one in the response/PNFSoftwareUpgrade_catalogdb.json.
161          */
162         assertThat(actionIdentifiers.getBlueprintName()).isEqualTo("test_pnf_software_upgrade_restconf");
163         assertThat(actionIdentifiers.getBlueprintVersion()).isEqualTo("1.0.0");
164         assertThat(actionIdentifiers.getActionName()).isEqualTo(action);
165         assertThat(actionIdentifiers.getMode()).isEqualTo("async");
166
167         CommonHeader commonHeader = executionServiceInput.getCommonHeader();
168         assertThat(commonHeader.getOriginatorId()).isEqualTo("SO");
169
170         Struct payload = executionServiceInput.getPayload();
171         Struct requeststruct = payload.getFieldsOrThrow(action + "-request").getStructValue();
172
173         assertThat(requeststruct.getFieldsOrThrow("resolution-key").getStringValue()).isEqualTo("PNFDemo");
174         Struct propertiesStruct = requeststruct.getFieldsOrThrow(action + "-properties").getStructValue();
175
176         assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).isEqualTo("PNFDemo");
177         assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue())
178                 .isEqualTo("32daaac6-5017-4e1e-96c8-6a27dfbe1421");
179         assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue())
180                 .isEqualTo("38dc9a92-214c-11e7-93ae-92361f002680");
181         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          * Post the pnf to AAI
205          */
206         wireMockServer.stubFor(post(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")));
207     }
208
209     private void mockRequestDb() {
210         /**
211          * Update Request DB
212          */
213         wireMockServer.stubFor(put(urlEqualTo("/infraActiveRequests/" + REQUEST_ID)));
214
215     }
216
217     /**
218      * Mock the catalobdb rest interface.
219      */
220     private void mockCatalogDb() {
221
222         String catalogdbClientResponse =
223                 FileUtil.readResourceFile("response/" + getClass().getSimpleName() + "_catalogdb.json");
224
225
226         /**
227          * Return valid json for the model UUID in the request file.
228          */
229         wireMockServer
230                 .stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelUuid=32daaac6-5017-4e1e-96c8-6a27dfbe1421"))
231                         .willReturn(okJson(responseObject)));
232
233         /**
234          * Return valid json for the service model InvariantUUID as specified in the request file.
235          */
236         wireMockServer.stubFor(
237                 get(urlEqualTo("/v2/serviceResources?serviceModelInvariantUuid=339b7a2f-9524-4dbf-9eee-f2e05521df3f"))
238                         .willReturn(okJson(responseObject)));
239
240         /**
241          * Return valid spring data rest json for the service model UUID as specified in the request file.
242          */
243         wireMockServer.stubFor(get(urlEqualTo(
244                 "/pnfResourceCustomization/search/findPnfResourceCustomizationByModelUuid?SERVICE_MODEL_UUID=32daaac6-5017-4e1e-96c8-6a27dfbe1421"))
245                         .willReturn(okJson(catalogdbClientResponse)));
246     }
247
248 }