exception handling
[so.git] / bpmn / so-bpmn-infrastructure-flows / src / test / java / org / onap / so / bpmn / infrastructure / process / CreateVcpeResCustServiceSimplifiedTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 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.ok;
25 import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
26 import static com.github.tomakehurst.wiremock.client.WireMock.post;
27 import static com.github.tomakehurst.wiremock.client.WireMock.put;
28 import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
29 import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
30 import static org.assertj.core.api.Assertions.fail;
31 import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat;
32 import com.google.protobuf.Struct;
33 import java.io.IOException;
34 import java.util.List;
35 import java.util.UUID;
36 import org.camunda.bpm.engine.runtime.ProcessInstance;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
40 import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
41 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
42 import org.onap.so.BaseBPMNTest;
43 import org.onap.so.GrpcNettyServer;
44 import org.onap.so.bpmn.mock.FileUtil;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Autowired;
48
49
50 /**
51  * Basic Integration test for createVcpeResCustService_Simplified.bpmn workflow.
52  */
53 public class CreateVcpeResCustServiceSimplifiedTest extends BaseBPMNTest {
54
55     private Logger logger = LoggerFactory.getLogger(getClass());
56
57     private static final long WORKFLOW_WAIT_TIME = 1000L;
58     private static final int DMAAP_DELAY_TIME_MS = 2000;
59
60     private static final String TEST_PROCESSINSTANCE_KEY = "CreateVcpeResCustService_simplified";
61
62     private String testBusinessKey;
63     private String requestObject;
64     private String responseObject;
65     private String msoRequestId;
66
67     @Autowired
68     private GrpcNettyServer grpcNettyServer;
69
70     @Before
71     public void setUp() throws IOException {
72
73         requestObject = FileUtil.readResourceFile("request/" + getClass().getSimpleName() + ".json");
74         responseObject = FileUtil.readResourceFile("response/" + getClass().getSimpleName() + ".json");
75
76         variables.put("bpmnRequest", requestObject);
77
78         /**
79          * This variable indicates that the flow was invoked asynchronously. It's injected by {@link WorkflowProcessor}.
80          */
81         variables.put("isAsyncProcess", "true");
82
83         /**
84          * Temporary solution to add pnfCorrelationId to context. this value is getting from the request to SO api
85          * handler and then convert to CamudaInput
86          */
87         variables.put("pnfCorrelationId", "PNFDemo");
88
89         /**
90          * Create mso-request-id.
91          */
92         msoRequestId = UUID.randomUUID().toString();
93
94         variables.put("mso-request-id", msoRequestId);
95
96         /**
97          * Create Business key for the process instance
98          */
99         testBusinessKey = UUID.randomUUID().toString();
100
101         logger.info("Test the process instance: {} with business key: {}", TEST_PROCESSINSTANCE_KEY, testBusinessKey);
102
103     }
104
105     @Test
106     public void workflow_validInput_expectedOuput() throws InterruptedException {
107
108         mockCatalogDb();
109         mockRequestDb();
110         mockAai();
111         mockDmaapForPnf();
112
113         ProcessInstance pi =
114                 runtimeService.startProcessInstanceByKey(TEST_PROCESSINSTANCE_KEY, testBusinessKey, variables);
115
116         int waitCount = 10;
117         while (!isProcessInstanceEnded() && waitCount >= 0) {
118             Thread.sleep(WORKFLOW_WAIT_TIME);
119             waitCount--;
120         }
121
122         assertThat(pi).isEnded().hasPassedInOrder("createVCPE_startEvent", "preProcessRequest_ScriptTask",
123                 "sendSyncAckResponse_ScriptTask", "ScriptTask_0cdtchu", "DecomposeService", "ScriptTask_0lpv2da",
124                 "ScriptTask_1y241p8", "CallActivity_1vc4jeh", "ScriptTask_1y5lvl7", "GeneratePnfUuid", "Task_14l19kv",
125                 "Pnf_Con", "setPONR_ScriptTask", "postProcessAndCompletionRequest_ScriptTask",
126                 "callCompleteMsoProcess_CallActivity", "ScriptTask_2", "CreateVCPE_EndEvent");
127
128         List<ExecutionServiceInput> detailedMessages = grpcNettyServer.getDetailedMessages();
129         assertThat(detailedMessages).hasSize(2);
130         try {
131             checkConfigAssign(detailedMessages.get(0));
132             checkConfigDeploy(detailedMessages.get(1));
133         } catch (Exception e) {
134             e.printStackTrace();
135             fail("ConfigAssign/deploy request exception", e);
136         }
137     }
138
139     private boolean isProcessInstanceEnded() {
140         return runtimeService.createProcessInstanceQuery().processDefinitionKey(TEST_PROCESSINSTANCE_KEY)
141                 .singleResult() == null;
142     }
143
144     private void checkConfigAssign(ExecutionServiceInput executionServiceInput) {
145
146         logger.info("Checking the configAssign request");
147         ActionIdentifiers actionIdentifiers = executionServiceInput.getActionIdentifiers();
148
149         /**
150          * the fields of actionIdentifiers should match the one in the
151          * response/createVcpeResCustServiceSimplifiedTest_catalogdb.json.
152          */
153         assertThat(actionIdentifiers.getBlueprintName()).isEqualTo("test_configuration_restconf");
154         assertThat(actionIdentifiers.getBlueprintVersion()).isEqualTo("1.0.0");
155         assertThat(actionIdentifiers.getActionName()).isEqualTo("config-assign");
156         assertThat(actionIdentifiers.getMode()).isEqualTo("sync");
157
158         CommonHeader commonHeader = executionServiceInput.getCommonHeader();
159         assertThat(commonHeader.getOriginatorId()).isEqualTo("SO");
160         assertThat(commonHeader.getRequestId()).isEqualTo(msoRequestId);
161
162         Struct payload = executionServiceInput.getPayload();
163         Struct requeststruct = payload.getFieldsOrThrow("config-assign-request").getStructValue();
164
165         assertThat(requeststruct.getFieldsOrThrow("resolution-key").getStringValue()).isEqualTo("PNFDemo");
166         Struct propertiesStruct = requeststruct.getFieldsOrThrow("config-assign-properties").getStructValue();
167
168         assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).isEqualTo("PNFDemo");
169         assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue())
170                 .isEqualTo("f2daaac6-5017-4e1e-96c8-6a27dfbe1421");
171         assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue())
172                 .isEqualTo("68dc9a92-214c-11e7-93ae-92361f002680");
173     }
174
175     private void checkConfigDeploy(ExecutionServiceInput executionServiceInput) {
176
177         logger.info("Checking the configDeploy request");
178         ActionIdentifiers actionIdentifiers = executionServiceInput.getActionIdentifiers();
179
180         /**
181          * the fields of actionIdentifiers should match the one in the
182          * response/createVcpeResCustServiceSimplifiedTest_catalogdb.json.
183          */
184         assertThat(actionIdentifiers.getBlueprintName()).isEqualTo("test_configuration_restconf");
185         assertThat(actionIdentifiers.getBlueprintVersion()).isEqualTo("1.0.0");
186         assertThat(actionIdentifiers.getActionName()).isEqualTo("config-deploy");
187         assertThat(actionIdentifiers.getMode()).isEqualTo("async");
188
189         CommonHeader commonHeader = executionServiceInput.getCommonHeader();
190         assertThat(commonHeader.getOriginatorId()).isEqualTo("SO");
191         assertThat(commonHeader.getRequestId()).isEqualTo(msoRequestId);
192
193         Struct payload = executionServiceInput.getPayload();
194         Struct requeststruct = payload.getFieldsOrThrow("config-deploy-request").getStructValue();
195
196         assertThat(requeststruct.getFieldsOrThrow("resolution-key").getStringValue()).isEqualTo("PNFDemo");
197         Struct propertiesStruct = requeststruct.getFieldsOrThrow("config-deploy-properties").getStructValue();
198
199         assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).isEqualTo("PNFDemo");
200         assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue())
201                 .isEqualTo("f2daaac6-5017-4e1e-96c8-6a27dfbe1421");
202         assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue())
203                 .isEqualTo("68dc9a92-214c-11e7-93ae-92361f002680");
204
205         /**
206          * IP addresses match the OAM ip addresses from AAI.
207          */
208         assertThat(propertiesStruct.getFieldsOrThrow("pnf-ipv4-address").getStringValue()).isEqualTo("1.1.1.1");
209         assertThat(propertiesStruct.getFieldsOrThrow("pnf-ipv6-address").getStringValue()).isEqualTo("::/128");
210     }
211
212     /**
213      * Mock the Dmaap Rest interface for Pnf topic.
214      */
215     private void mockDmaapForPnf() {
216
217         String pnfResponse = "[{\"correlationId\": \"PNFDemo\",\"key1\":\"value1\"}]";
218
219         /**
220          * Get the events from PNF topic
221          */
222         wireMockServer.stubFor(get(urlPathMatching("/events/pnfReady/consumerGroup.*"))
223                 .willReturn(okJson(pnfResponse).withFixedDelay(DMAAP_DELAY_TIME_MS)));
224     }
225
226     private void mockAai() {
227
228         String aaiResponse = "{\n" + "  \"results\": [\n" + "    {\n"
229                 + "      \"resource-type\": \"service-instance\",\n"
230                 + "      \"resource-link\": \"https://localhost:8443/aai/v15/business/customers/customer/ADemoCustomerInCiti/service-subscriptions/service-subscription/vCPE/service-instances/service-instance/key3\"\n"
231                 + "    }\n" + "  ]\n" + "}";
232
233         String aaiPnfEntry = "{  \n" + "   \"pnf-name\":\"PNFDemo\",\n" + "   \"pnf-id\":\"testtest\",\n"
234                 + "   \"in-maint\":true,\n" + "   \"resource-version\":\"1541720264047\",\n"
235                 + "   \"ipaddress-v4-oam\":\"1.1.1.1\",\n" + "   \"ipaddress-v6-oam\":\"::/128\"\n" + "}";
236
237         /**
238          * Get the AAI entry for globalCustomerId as specified in the request file.
239          */
240         wireMockServer.stubFor(
241                 get(urlPathMatching("/aai/v15/business/customers/customer/ADemoCustomerInCiti.*")).willReturn(ok()));
242
243         /**
244          * PUT the service to AAI with globalCustomerId, service type as specified in the request file. Service instance
245          * id is generated during runtime, REGEX is used to represent the information.
246          */
247         wireMockServer.stubFor(put(urlPathMatching(
248                 "/aai/v15/business/customers/customer/ADemoCustomerInCiti/service-subscriptions/service-subscription/vCPE/service-instances/service-instance/.*")));
249
250         wireMockServer.stubFor(get(urlPathMatching(
251                 "/aai/v15/business/customers/customer/ADemoCustomerInCiti/service-subscriptions/service-subscription/vCPE/service-instances/service-instance/.*"))
252                         .willReturn(okJson(aaiResponse)));
253
254         /**
255          * Get the service from AAI
256          */
257         wireMockServer.stubFor(get(urlPathMatching("/aai/v15/nodes/service-instances/service-instance/.*"))
258                 .willReturn(okJson(aaiResponse)));
259
260         /**
261          * Put the project as specified in the request file to AAI.
262          */
263         wireMockServer.stubFor(put(urlEqualTo("/aai/v15/business/projects/project/Project-Demonstration")));
264
265         /**
266          * GET the project as specified in the request file to AAI.
267          */
268         wireMockServer.stubFor(
269                 get(urlPathMatching("/aai/v15/business/projects/project/Project-Demonstration")).willReturn(ok()));
270
271         /**
272          * PUT the PNF correlation ID to AAI.
273          */
274         wireMockServer.stubFor(put(urlEqualTo("/aai/v15/network/pnfs/pnf/PNFDemo")));
275
276         /**
277          * Get the PNF entry from AAI.
278          */
279         wireMockServer.stubFor(get(urlEqualTo("/aai/v15/network/pnfs/pnf/PNFDemo")).willReturn(okJson(aaiPnfEntry)));
280
281         /**
282          * Put the PNF relationship
283          */
284         wireMockServer.stubFor(put(
285                 urlEqualTo("/aai/v15/business/projects/project/Project-Demonstration/relationship-list/relationship")));
286     }
287
288     /**
289      * Mock the catalobdb rest interface.
290      */
291     private void mockCatalogDb() {
292
293         String catalogdbClientResponse =
294                 FileUtil.readResourceFile("response/" + getClass().getSimpleName() + "_catalogdb.json");
295
296         /**
297          * Return valid json for the model UUID in the request file.
298          */
299         wireMockServer
300                 .stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelUuid=f2daaac6-5017-4e1e-96c8-6a27dfbe1421"))
301                         .willReturn(okJson(responseObject)));
302
303         /**
304          * Return valid json for the service model InvariantUUID as specified in the request file.
305          */
306         wireMockServer.stubFor(
307                 get(urlEqualTo("/v2/serviceResources?serviceModelInvariantUuid=539b7a2f-9524-4dbf-9eee-f2e05521df3f"))
308                         .willReturn(okJson(responseObject)));
309
310         /**
311          * Return valid spring data rest json for the service model UUID as specified in the request file.
312          */
313         wireMockServer.stubFor(get(urlEqualTo(
314                 "/pnfResourceCustomization/search/findPnfResourceCustomizationByModelUuid?SERVICE_MODEL_UUID=f2daaac6-5017-4e1e-96c8-6a27dfbe1421"))
315                         .willReturn(okJson(catalogdbClientResponse)));
316     }
317
318     private void mockRequestDb() {
319         wireMockServer.stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter")).willReturn(ok()));
320     }
321
322 }