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