3d1a8d7bc06cb5759165c3d27b62dff886429f65
[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 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.policy.apex.testsuites.integration.uservice.taskparameters;
22
23 import static org.awaitility.Awaitility.await;
24 import static org.junit.Assert.assertTrue;
25
26 import java.util.concurrent.TimeUnit;
27
28 import javax.ws.rs.client.Client;
29 import javax.ws.rs.client.ClientBuilder;
30 import javax.ws.rs.core.Response;
31
32 import org.junit.AfterClass;
33 import org.junit.Before;
34 import org.junit.BeforeClass;
35 import org.junit.Test;
36 import org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain;
37 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
38 import org.onap.policy.apex.service.engine.main.ApexMain;
39 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
40 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
41 import org.onap.policy.common.gson.GsonMessageBodyHandler;
42 import org.onap.policy.common.utils.network.NetworkUtil;
43 import org.slf4j.ext.XLogger;
44 import org.slf4j.ext.XLoggerFactory;
45
46 /**
47  * This class runs integration tests for taskParameters. Task parameters are read from the ApexConfig, and they can be
48  * accessed in task logic. In this case, the taskParameters are used to set values in executionProperties. URL
49  * dynamically populated using executionProperties is hit and values get updated in
50  * {@link RestClientEndpointForTaskParameters} which acts as a temporary server for requests.
51  */
52 public class TestTaskParameters {
53
54     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestTaskParameters.class);
55
56     private static HttpServletServer server;
57     private static final int PORT = 32801;
58     private static final String HOST = "localhost";
59
60     /**
61      * Compile the policy.
62      */
63     @BeforeClass
64     public static void compilePolicy() {
65         // @formatter:off
66         final String[] cliArgs = {
67             "-c",
68             "src/test/resources/policies/taskparameters/TaskParametersTestPolicyModel.apex",
69             "-l",
70             "target/TaskParametersTestPolicyModel.log",
71             "-o",
72             "target/TaskParametersTestPolicyModel.json"
73         };
74         // @formatter:on
75
76         new ApexCommandLineEditorMain(cliArgs);
77     }
78
79     /**
80      * Sets up a server for testing.
81      *
82      * @throws Exception the exception
83      */
84     @BeforeClass
85     public static void setUp() throws Exception {
86         if (NetworkUtil.isTcpPortOpen(HOST, PORT, 3, 50L)) {
87             throw new IllegalStateException("port " + PORT + " is still in use");
88         }
89
90         server = HttpServletServerFactoryInstance.getServerFactory().build("TestTaskParameters", false, null, PORT,
91             "/TestTaskParametersRest", false, false);
92
93         server.addServletClass(null, RestClientEndpointForTaskParameters.class.getName());
94         server.setSerializationProvider(GsonMessageBodyHandler.class.getName());
95
96         server.start();
97
98         if (!NetworkUtil.isTcpPortOpen(HOST, PORT, 60, 500L)) {
99             throw new IllegalStateException("port " + PORT + " is still not in use");
100         }
101
102     }
103
104     /**
105      * Tear down.
106      *
107      * @throws Exception the exception
108      */
109     @AfterClass
110     public static void tearDown() throws Exception {
111         if (server != null) {
112             server.stop();
113         }
114     }
115
116     /**
117      * Clear relative file root environment variable.
118      */
119     @Before
120     public void clearRelativeFileRoot() {
121         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
122     }
123
124     /**
125      * Test taskParameters with no taskIds. When taskIds are not provided, all taskParameters provided in config will be
126      * updated to all tasks.
127      */
128     @Test
129     public void testTaskParameters_with_noTaskIds() throws Exception {
130         String responseEntity = testTaskParameters(
131             "src/test/resources/testdata/taskparameters/TaskParameterTestConfig_with_noTaskIds.json");
132         assertTrue(responseEntity.contains("{\"closedLoopId\": closedLoopId123,\"serviceId\": serviceId123}"));
133     }
134
135     /**
136      * Test taskParameters with valid taskIds. When valid taskIds are provided, the the taskParameter will be updated in
137      * that particular task alone.
138      */
139     @Test
140     public void testTaskParameters_with_validTaskIds() throws Exception {
141         String responseEntity = testTaskParameters(
142             "src/test/resources/testdata/taskparameters/TaskParameterTestConfig_with_validTaskIds.json");
143         assertTrue(responseEntity.contains("{\"closedLoopId\": closedLoopIdxyz,\"serviceId\": serviceIdxyz}"));
144     }
145
146     /**
147      * Test taskParameters with invalid taskIds. When invalid taskIds are provided, or when a taskParameter assigned to
148      * a particular taskId is tried to be accessed in a taskLogic of a different task, such taskParameters won't be
149      * accessible in the task
150      */
151     @Test
152     public void testTaskParameters_with_invalidTaskIds() throws Exception {
153         String responseEntity = testTaskParameters(
154             "src/test/resources/testdata/taskparameters/TaskParameterTestConfig_with_invalidTaskIds.json");
155         assertTrue(responseEntity.contains("{\"closedLoopId\": INVALID - closedLoopId not available in TaskParameters,"
156             + "\"serviceId\": INVALID - serviceId not available in TaskParameters}"));
157     }
158
159     private String testTaskParameters(String apexConfigPath) throws ApexException {
160         final Client client = ClientBuilder.newClient();
161         final String[] args = {apexConfigPath};
162         // clear the details set in server
163         client.target("http://" + HOST + ":" + PORT + "/TestTaskParametersRest/apex/event/clearDetails")
164             .request("application/json").get();
165         final ApexMain apexMain = new ApexMain(args);
166
167         String getDetailsUrl = "http://" + HOST + ":" + PORT + "/TestTaskParametersRest/apex/event/getDetails";
168         // wait for success response code to be received, until a timeout
169         await().atMost(5, TimeUnit.SECONDS)
170             .until(() -> 200 == client.target(getDetailsUrl).request("application/json").get().getStatus());
171         apexMain.shutdown();
172         Response response = client.target(getDetailsUrl).request("application/json").get();
173         String responseEntity = response.readEntity(String.class);
174
175         LOGGER.info("testTaskParameters-OUTSTRING=\n {}", responseEntity);
176         return responseEntity;
177     }
178 }