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