804f5185719282e2eca157ad85a253697a31e3da
[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.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
28 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
29 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
30 import org.onap.so.BaseBPMNTest;
31 import org.onap.so.GrpcNettyServer;
32 import org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames;
33 import org.onap.so.bpmn.mock.FileUtil;
34 import org.onap.aaiclient.client.aai.AAIVersion;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import java.util.HashMap;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.UUID;
42 import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
43 import static com.github.tomakehurst.wiremock.client.WireMock.get;
44 import static com.github.tomakehurst.wiremock.client.WireMock.put;
45 import static com.github.tomakehurst.wiremock.client.WireMock.post;
46 import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
47 import static org.assertj.core.api.Assertions.fail;
48 import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareTests.assertThat;
49 import static org.junit.Assert.assertEquals;
50 import static org.junit.Assert.assertTrue;
51
52 /**
53  * Basic Integration test for GenericPnfSoftwareUpgrade.bpmn workflow.
54  */
55 public class GenericPnfSoftwareUpgradeTest 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 = "GenericPnfSoftwareUpgrade";
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() {
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         grpcNettyServer.resetList();
109
110         final String msoRequestId = UUID.randomUUID().toString();
111         executionVariables.put(ExecutionVariableNames.MSO_REQUEST_ID, msoRequestId);
112
113         final String testBusinessKey = UUID.randomUUID().toString();
114         logger.info("Test the process instance: {} with business key: {}", TEST_PROCESSINSTANCE_KEY, testBusinessKey);
115
116         ProcessInstance pi =
117                 runtimeService.startProcessInstanceByKey(TEST_PROCESSINSTANCE_KEY, testBusinessKey, executionVariables);
118
119         int waitCount = 10;
120         while (!isProcessInstanceEnded() && waitCount >= 0) {
121             Thread.sleep(WORKFLOW_WAIT_TIME);
122             waitCount--;
123         }
124
125         // Layout is to reflect the bpmn visual layout
126         assertThat(pi).isStarted().hasPassedInOrder("softwareUpgrade_startEvent", "ServiceTask_042uz7n",
127                 "ScriptTask_10klpg8", "ServiceTask_0slpahe", "ExclusiveGateway_0x6h0ni", "ServiceTask_0x5cje8",
128                 "ExclusiveGateway_0v3l3wv", "ServiceTask_02lxf48", "ExclusiveGateway_0ch3fef", "ServiceTask_0y2uysu",
129                 "ExclusiveGateway_1ny9b1z", "ScriptTask_1igtc83", "CallActivity_0o1mi8u", "softwareUpgrade_endEvent");
130
131         List<ExecutionServiceInput> detailedMessages = grpcNettyServer.getDetailedMessages();
132         assertEquals(4, detailedMessages.size());
133         int count = 0;
134         try {
135             for (ExecutionServiceInput eSI : detailedMessages) {
136                 for (String action : actionNames) {
137                     if (action.equals(eSI.getActionIdentifiers().getActionName())
138                             && eSI.getCommonHeader().getRequestId().equals(msoRequestId)) {
139                         checkWithActionName(eSI, action);
140                         count++;
141                     }
142                 }
143             }
144         } catch (Exception e) {
145             e.printStackTrace();
146             fail("GenericPnfSoftwareUpgrade request exception", e);
147         }
148         assertTrue(count == actionNames.length);
149     }
150
151     private boolean isProcessInstanceEnded() {
152         return runtimeService.createProcessInstanceQuery().processDefinitionKey(TEST_PROCESSINSTANCE_KEY)
153                 .singleResult() == null;
154     }
155
156     private void checkWithActionName(ExecutionServiceInput executionServiceInput, String action) {
157
158         logger.info("Checking the " + action + " request");
159         ActionIdentifiers actionIdentifiers = executionServiceInput.getActionIdentifiers();
160
161         /**
162          * the fields of actionIdentifiers should match the one in the
163          * response/GenericPnfSoftwareUpgrade_catalogdb.json.
164          */
165         assertEquals("test_pnf_software_upgrade_restconf", actionIdentifiers.getBlueprintName());
166         assertEquals("1.0.0", actionIdentifiers.getBlueprintVersion());
167         assertEquals(action, actionIdentifiers.getActionName());
168         assertEquals("async", actionIdentifiers.getMode());
169
170         CommonHeader commonHeader = executionServiceInput.getCommonHeader();
171         assertEquals("SO", commonHeader.getOriginatorId());
172
173         Struct payload = executionServiceInput.getPayload();
174         Struct requeststruct = payload.getFieldsOrThrow(action + "-request").getStructValue();
175
176         assertEquals("PNFDemo", requeststruct.getFieldsOrThrow("resolution-key").getStringValue());
177         Struct propertiesStruct = requeststruct.getFieldsOrThrow(action + "-properties").getStructValue();
178
179         assertEquals("PNFDemo", propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue());
180         assertEquals("32daaac6-5017-4e1e-96c8-6a27dfbe1421",
181                 propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue());
182         assertEquals("38dc9a92-214c-11e7-93ae-92361f002680",
183                 propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue());
184         assertEquals("demo-sw-ver2.0.0", propertiesStruct.getFieldsOrThrow("target-software-version").getStringValue());
185     }
186
187     private void mockAai() {
188
189         String aaiPnfEntry =
190                 "{  \n" + "   \"pnf-name\":\"PNFDemo\",\n" + "   \"pnf-id\":\"testtest\",\n" + "   \"in-maint\":true,\n"
191                         + "   \"resource-version\":\"1541720264047\",\n" + "   \"swVersion\":\"demo-1.1\",\n"
192                         + "   \"ipaddress-v4-oam\":\"1.1.1.1\",\n" + "   \"ipaddress-v6-oam\":\"::/128\"\n" + "}";
193
194         /**
195          * PUT the PNF correlation ID to AAI.
196          */
197         wireMockServer.stubFor(put(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")));
198
199         /**
200          * Get the PNF entry from AAI.
201          */
202         wireMockServer.stubFor(
203                 get(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")).willReturn(okJson(aaiPnfEntry)));
204
205         /*
206          * Post the pnf to AAI
207          */
208         wireMockServer.stubFor(post(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")));
209     }
210
211     private void mockRequestDb() {
212         /**
213          * Update Request DB
214          */
215         wireMockServer.stubFor(put(urlEqualTo("/infraActiveRequests/" + REQUEST_ID)));
216
217     }
218
219     /**
220      * Mock the catalobdb rest interface.
221      */
222     private void mockCatalogDb() {
223
224         String catalogdbClientResponse =
225                 FileUtil.readResourceFile("response/" + getClass().getSimpleName() + "_catalogdb.json");
226
227
228         /**
229          * Return valid json for the model UUID in the request file.
230          */
231         wireMockServer
232                 .stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelUuid=32daaac6-5017-4e1e-96c8-6a27dfbe1421"))
233                         .willReturn(okJson(responseObject)));
234
235         /**
236          * Return valid json for the service model InvariantUUID as specified in the request file.
237          */
238         wireMockServer.stubFor(
239                 get(urlEqualTo("/v2/serviceResources?serviceModelInvariantUuid=339b7a2f-9524-4dbf-9eee-f2e05521df3f"))
240                         .willReturn(okJson(responseObject)));
241
242         /**
243          * Return valid spring data rest json for the service model UUID as specified in the request file.
244          */
245         wireMockServer.stubFor(get(urlEqualTo(
246                 "/pnfResourceCustomization/search/findPnfResourceCustomizationByModelUuid?SERVICE_MODEL_UUID=32daaac6-5017-4e1e-96c8-6a27dfbe1421"))
247                         .willReturn(okJson(catalogdbClientResponse)));
248     }
249
250 }