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