805597cd129eb78bad984c2efe1727ffa2719f95
[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 com.google.protobuf.Struct;
24 import org.camunda.bpm.engine.runtime.ProcessInstance;
25 import org.junit.Before;
26 import org.junit.Test;
27 import org.onap.aaiclient.client.aai.AAIVersion;
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.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import java.io.IOException;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.UUID;
43 import static com.github.tomakehurst.wiremock.client.WireMock.*;
44 import static org.assertj.core.api.Assertions.fail;
45 import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
46
47 /**
48  * Basic Integration test for ServiceLevelUpgrade.bpmn workflow.
49  */
50 public class ServiceLevelUpgradeTest extends BaseBPMNTest {
51
52     private final Logger logger = LoggerFactory.getLogger(getClass());
53
54     private static final long WORKFLOW_WAIT_TIME = 1000L;
55
56     private static final String TEST_PROCESSINSTANCE_KEY = "ServiceLevelUpgrade";
57     private static final AAIVersion VERSION = AAIVersion.LATEST;
58     private static final Map<String, Object> executionVariables = new HashMap();
59     private static final String REQUEST_ID = "50ae41ad-049c-4fe2-9950-539f111120f5";
60     private static final String SERVICE_INSTANCE_ID = "5df8b6de-2083-11e7-93ae-92361f002676";
61     private final String[] actionNames = new String[5];
62     private final String CLASSNAME = getClass().getSimpleName();
63     private String requestObject;
64     private String responseObject;
65
66     @Autowired
67     private GrpcNettyServer grpcNettyServer;
68
69     @Before
70     public void setUp() throws IOException {
71         actionNames[0] = "healthCheck";
72         actionNames[1] = "preCheck";
73         actionNames[2] = "downloadNESw";
74         actionNames[3] = "activateNESw";
75         actionNames[4] = "postCheck";
76
77         executionVariables.clear();
78
79         requestObject = FileUtil.readResourceFile("request/" + CLASSNAME + ".json");
80         responseObject = FileUtil.readResourceFile("response/" + CLASSNAME + ".json");
81
82         executionVariables.put("bpmnRequest", requestObject);
83         executionVariables.put("requestId", REQUEST_ID);
84         executionVariables.put("serviceInstanceId", SERVICE_INSTANCE_ID);
85
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("Event_02mc8tr", "Activity_18vue7u", "Activity_0qgmx7a",
125                 "Activity_09bqns0", "Activity_0n17xou", "Gateway_1nr51kr", "Activity_0snmatn", "Activity_1q4o9fx",
126                 "Gateway_02fectw", "Activity_1hp67qz", "Gateway_18ch73t", "Activity_0ft7fa2", "Gateway_1vq11i7",
127                 "Activity_1n4rk7m", "Activity_1lz38px", "Event_12983th");
128
129         List<ExecutionServiceInput> detailedMessages = grpcNettyServer.getDetailedMessages();
130         assertThat(detailedMessages.size() == 5);
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/PnfHealthCheck_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("d88da85c-d9e8-4f73-b837-3a72a431622b");
179         assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue())
180                 .isEqualTo("38dc9a92-214c-11e7-93ae-92361f002680");
181     }
182
183     private void mockAai() {
184
185         final String sIUrl =
186                 "/business/customers/customer/5df8b6de-2083-11e7-93ae-92361f002676/service-subscriptions/service-subscription/pNF/service-instances/service-instance/ETE_Customer_807c7a02-249c-4db8-9fa9-bee973fe08ce";
187         final String aaiPnfEntry = FileUtil.readResourceFile("response/Pnf_aai.json");
188         final String aaiServiceInstanceEntry = FileUtil.readResourceFile("response/Service_instance_aai.json");
189
190         /**
191          * PUT the PNF correlation ID to AAI.
192          */
193         wireMockServer.stubFor(put(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")));
194
195         /**
196          * Get the PNF entry from AAI.
197          */
198         wireMockServer.stubFor(
199                 get(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")).willReturn(okJson(aaiPnfEntry)));
200
201         /**
202          * Post the pnf to AAI
203          */
204         wireMockServer.stubFor(post(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")));
205
206         /**
207          * Get the Service Instance to AAI.
208          */
209         wireMockServer.stubFor(get(urlEqualTo("/aai/" + VERSION + sIUrl)).willReturn(okJson(aaiServiceInstanceEntry)));
210
211         /**
212          * Post the Service Instance to AAI.
213          */
214         wireMockServer.stubFor(post(urlEqualTo("/aai/" + VERSION + sIUrl)));
215     }
216
217     private void mockRequestDb() {
218         /**
219          * Update Request DB
220          */
221         wireMockServer.stubFor(put(urlEqualTo("/infraActiveRequests/" + REQUEST_ID)));
222
223     }
224
225     /**
226      * Mock the catalobdb rest interface.
227      */
228     private void mockCatalogDb() {
229
230         String catalogdbClientResponse = FileUtil.readResourceFile("response/" + CLASSNAME + "_catalogdb.json");
231
232
233         /**
234          * Return valid json for the model UUID in the request file.
235          */
236         wireMockServer
237                 .stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelUuid=d88da85c-d9e8-4f73-b837-3a72a431622b"))
238                         .willReturn(okJson(responseObject)));
239
240         /**
241          * Return valid json for the service model InvariantUUID as specified in the request file.
242          */
243         wireMockServer.stubFor(
244                 get(urlEqualTo("/v2/serviceResources?serviceModelInvariantUuid=fe41489e-1563-46a3-b90a-1db629e4375b"))
245                         .willReturn(okJson(responseObject)));
246
247         /**
248          * Return valid spring data rest json for the service model UUID as specified in the request file.
249          */
250         wireMockServer.stubFor(get(urlEqualTo(
251                 "/pnfResourceCustomization/search/findPnfResourceCustomizationByModelUuid?SERVICE_MODEL_UUID=d88da85c-d9e8-4f73-b837-3a72a431622b"))
252                         .willReturn(okJson(catalogdbClientResponse)));
253     }
254
255 }