Convert junit4 to junit5
[policy/apex-pdp.git] / testsuites / integration / integration-uservice-test / src / test / java / org / onap / policy / apex / testsuites / integration / uservice / taskparameters / TestTaskParameters.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020, 2023-2024 Nordix Foundation.
4  *  Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.testsuites.integration.uservice.taskparameters;
23
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.jupiter.api.Assertions.assertTrue;
26
27 import jakarta.ws.rs.client.Client;
28 import jakarta.ws.rs.client.ClientBuilder;
29 import jakarta.ws.rs.core.Response;
30 import java.util.concurrent.TimeUnit;
31 import org.junit.jupiter.api.AfterAll;
32 import org.junit.jupiter.api.BeforeAll;
33 import org.junit.jupiter.api.BeforeEach;
34 import org.junit.jupiter.api.Test;
35 import org.onap.policy.apex.auth.clieditor.tosca.ApexCliToscaEditorMain;
36 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
37 import org.onap.policy.apex.service.engine.main.ApexMain;
38 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
39 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
40 import org.onap.policy.common.gson.GsonMessageBodyHandler;
41 import org.onap.policy.common.utils.network.NetworkUtil;
42 import org.slf4j.ext.XLogger;
43 import org.slf4j.ext.XLoggerFactory;
44
45 /**
46  * This class runs integration tests for taskParameters. Task parameters are read from the ApexConfig, and they can be
47  * accessed in task logic. In this case, the taskParameters are used to set values in executionProperties. URL
48  * dynamically populated using executionProperties is hit and values get updated in
49  * {@link RestClientEndpointForTaskParameters} which acts as a temporary server for requests.
50  */
51 class TestTaskParameters {
52
53     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestTaskParameters.class);
54
55     private static HttpServletServer server;
56     private static final int PORT = 32801;
57     private static final String HOST = "localhost";
58
59     /**
60      * Sets up a server for testing.
61      *
62      * @throws Exception the exception
63      */
64     @BeforeAll
65     static void setUp() throws Exception {
66         if (NetworkUtil.isTcpPortOpen(HOST, PORT, 3, 50L)) {
67             throw new IllegalStateException("port " + PORT + " is still in use");
68         }
69
70         server =
71             HttpServletServerFactoryInstance.getServerFactory().build("TestTaskParameters", false, null, PORT, false,
72                 "/TestTaskParametersRest", false, false);
73
74         server.addServletClass(null, RestClientEndpointForTaskParameters.class.getName());
75         server.setSerializationProvider(GsonMessageBodyHandler.class.getName());
76
77         server.start();
78
79         if (!NetworkUtil.isTcpPortOpen(HOST, PORT, 60, 500L)) {
80             throw new IllegalStateException("port " + PORT + " is still not in use");
81         }
82
83     }
84
85     /**
86      * Tear down.
87      *
88      */
89     @AfterAll
90     static void tearDown() {
91         if (server != null) {
92             server.stop();
93         }
94     }
95
96     /**
97      * Clear relative file root environment variable.
98      */
99     @BeforeEach
100     void clearRelativeFileRoot() {
101         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
102     }
103
104     /**
105      * Test taskParameters with no taskIds. When taskIds are not provided, all taskParameters provided in config will be
106      * updated to all tasks.
107      */
108     @Test
109     void testTaskParameters_with_noTaskIds() throws Exception {
110         String responseEntity = testTaskParameters(
111             "src/test/resources/testdata/taskparameters/TaskParameterTestConfig_with_noTaskIds.json");
112         assertTrue(responseEntity.contains("{\"closedLoopId\": closedLoopId123,\"serviceId\": serviceId123}"));
113     }
114
115     /**
116      * Test taskParameters with valid taskIds. When valid taskIds are provided, the the taskParameter will be updated in
117      * that particular task alone.
118      */
119     @Test
120     void testTaskParameters_with_validTaskIds() throws Exception {
121         String responseEntity = testTaskParameters(
122             "src/test/resources/testdata/taskparameters/TaskParameterTestConfig_with_validTaskIds.json");
123         assertTrue(responseEntity.contains("{\"closedLoopId\": closedLoopIdxyz,\"serviceId\": serviceIdxyz}"));
124     }
125
126     /**
127      * Test taskParameters with invalid taskIds. When invalid taskIds are provided, or when a taskParameter assigned to
128      * a particular taskId is tried to be accessed in a taskLogic of a different task, such taskParameters won't be
129      * accessible in the task
130      */
131     @Test
132     void testTaskParameters_with_invalidTaskIds() throws Exception {
133         String responseEntity = testTaskParameters(
134             "src/test/resources/testdata/taskparameters/TaskParameterTestConfig_with_invalidTaskIds.json");
135         assertTrue(responseEntity.contains("{\"closedLoopId\": INVALID - closedLoopId not available in TaskParameters,"
136             + "\"serviceId\": INVALID - serviceId not available in TaskParameters}"));
137     }
138
139     private String testTaskParameters(String apexConfigPath) throws ApexException {
140         final Client client = ClientBuilder.newClient();
141         // @formatter:off
142         final String[] cliArgs = new String[] {
143             "-c",
144             "src/test/resources/policies/taskparameters/TaskParametersTestPolicyModel.apex",
145             "-ac",
146             apexConfigPath,
147             "-t",
148             "src/test/resources/tosca/ToscaTemplate.json",
149             "-ot",
150             "target/classes/APEXPolicy.json"
151         };
152         // @formatter:on
153
154         new ApexCliToscaEditorMain(cliArgs);
155         final String[] args = {
156             "target/classes/APEXPolicy.json"
157         };
158         // clear the details set in server
159         client.target("http://" + HOST + ":" + PORT + "/TestTaskParametersRest/apex/event/clearDetails")
160             .request("application/json").get();
161         final ApexMain apexMain = new ApexMain(args);
162
163         String getDetailsUrl = "http://" + HOST + ":" + PORT + "/TestTaskParametersRest/apex/event/getDetails";
164         // wait for success response code to be received, until a timeout
165         await().atMost(5, TimeUnit.SECONDS)
166             .until(() -> 200 == client.target(getDetailsUrl).request("application/json").get().getStatus());
167         apexMain.shutdown();
168         Response response = client.target(getDetailsUrl).request("application/json").get();
169         String responseEntity = response.readEntity(String.class);
170
171         LOGGER.info("testTaskParameters-OUTSTRING=\n {}", responseEntity);
172         client.close();
173         return responseEntity;
174     }
175 }