0cf7dc652e5e09a8cee85fdfe3a5f2d8629affd4
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2020 Nordix Foundation.
4  *  Modifications Copyright (C) 2020-2021 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.adapt.restclient;
23
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.awaitility.Awaitility.await;
26 import static org.junit.Assert.assertTrue;
27
28 import java.io.ByteArrayOutputStream;
29 import java.io.PrintStream;
30 import java.util.concurrent.TimeUnit;
31 import javax.ws.rs.client.Client;
32 import javax.ws.rs.client.ClientBuilder;
33 import javax.ws.rs.core.Response;
34 import org.junit.After;
35 import org.junit.AfterClass;
36 import org.junit.Before;
37 import org.junit.BeforeClass;
38 import org.junit.Test;
39 import org.onap.policy.apex.auth.clieditor.tosca.ApexCliToscaEditorMain;
40 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
41 import org.onap.policy.apex.service.engine.main.ApexMain;
42 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
43 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
44 import org.onap.policy.common.gson.GsonMessageBodyHandler;
45 import org.onap.policy.common.utils.network.NetworkUtil;
46 import org.slf4j.ext.XLogger;
47 import org.slf4j.ext.XLoggerFactory;
48
49 /**
50  * This class runs integration tests for execution property in restClient.
51  */
52 public class TestExecutionPropertyRest {
53
54     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestExecutionPropertyRest.class);
55
56     private static HttpServletServer server;
57     private static final int PORT = 32801;
58
59     private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
60     private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
61
62     private final PrintStream stdout = System.out;
63     private final PrintStream stderr = System.err;
64
65     private ApexMain apexMain;
66
67     /**
68      * Sets the up.
69      *
70      * @throws Exception the exception
71      */
72     @BeforeClass
73     public static void setUp() throws Exception {
74         if (NetworkUtil.isTcpPortOpen("localHost", PORT, 3, 50L)) {
75             throw new IllegalStateException("port " + PORT + " is still in use");
76         }
77
78         server = HttpServletServerFactoryInstance.getServerFactory().build("TestExecutionPropertyRest", false, null,
79             PORT, "/TestExecutionRest", false, false);
80
81         server.addServletClass(null, TestRestClientEndpoint.class.getName());
82         server.setSerializationProvider(GsonMessageBodyHandler.class.getName());
83
84         server.start();
85
86         if (!NetworkUtil.isTcpPortOpen("localHost", PORT, 60, 500L)) {
87             throw new IllegalStateException("port " + PORT + " is still not in use");
88         }
89
90     }
91
92     /**
93      * Tear down.
94      *
95      * @throws Exception the exception
96      */
97     @AfterClass
98     public static void tearDown() throws Exception {
99         if (server != null) {
100             server.stop();
101         }
102     }
103
104     /**
105      * Before test.
106      */
107     @Before
108     public void beforeTest() {
109         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
110         System.setOut(new PrintStream(outContent));
111         System.setErr(new PrintStream(errContent));
112     }
113
114     /**
115      * After test.
116      * @throws ApexException the exception.
117      */
118     @After
119     public void afterTest() throws ApexException {
120         if (null != apexMain) {
121             apexMain.shutdown();
122         }
123         System.setOut(stdout);
124         System.setErr(stderr);
125     }
126
127     /**
128      * Test Bad Url tag in Parameter .
129      */
130     @Test
131     public void testBadUrl() throws Exception {
132         // @formatter:off
133         final String[] cliArgs = new String[] {
134             "-c",
135             "src/test/resources/policies/executionproperties/policy/ExecutionPropertiesRestTestPolicyModel.apex",
136             "-o",
137             "target/ExecutionPropertiesRestTestPolicyModel.json",
138             "-ac",
139             "src/test/resources/testdata/executionproperties/RESTEventBadUrl.json",
140             "-t",
141             "src/test/resources/tosca/ToscaTemplate.json",
142             "-ot",
143             "target/classes/APEXPolicy.json"
144         };
145         // @formatter:on
146
147         new ApexCliToscaEditorMain(cliArgs);
148
149         // @formatter:off
150         final String[] args = {
151             "-p",
152             "target/classes/APEXPolicy.json"
153         };
154         // @formatter:on
155
156         apexMain = new ApexMain(args);
157
158         final String outString = outContent.toString();
159
160         LOGGER.info("testReplaceUrlTag-OUTSTRING=\n" + outString + "\nEnd-TagUrl");
161         assertThat(outString).contains("invalid URL http://localhost:32801/TestExecutionRest/apex/event/tagId}"
162             + " has been set for event sending on RESTCLIENT");
163     }
164
165     /**
166      * Test Not find value for tags in Url .
167      */
168     @Test
169     public void testNoValueSetForTagUrl() throws Exception {
170         // @formatter:off
171         final String[] cliArgs = new String[] {
172             "-c",
173             "src/test/resources/policies/executionproperties/policy/ExecutionPropertiesRestTestPolicyModel.apex",
174             "-o",
175             "target/ExecutionPropertiesRestTestPolicyModel.json",
176             "-ac",
177             "src/test/resources/testdata/executionproperties/RESTEventNoValueSetForTag.json",
178             "-t",
179             "src/test/resources/tosca/ToscaTemplate.json",
180             "-ot",
181             "target/classes/APEXPolicy.json"
182         };
183         // @formatter:on
184
185         new ApexCliToscaEditorMain(cliArgs);
186
187         // @formatter:off
188         final String[] args = {
189             "-p",
190             "target/classes/APEXPolicy.json"
191         };
192         // @formatter:on
193
194         apexMain = new ApexMain(args);
195
196         await().atMost(5, TimeUnit.SECONDS)
197             .until(() -> outContent.toString()
198                 .contains("key \"Number\" specified on url \"http://localhost:32801/TestExecutionRest/apex"
199                     + "/event/{tagId}/{Number}\" not found in execution properties passed by the current policy"));
200         assertTrue(apexMain.isAlive());
201         LOGGER.info("testNoValueSetForTagUrl-OUTSTRING=\n" + outContent.toString() + "\nEnd-TagUrl");
202     }
203
204     /**
205      * Test Bad Http code Filter.
206      */
207     @Test
208     public void testBadCodeFilter() throws Exception {
209         // @formatter:off
210         final String[] cliArgs = new String[] {
211             "-c",
212             "src/test/resources/policies/executionproperties/policy/ExecutionPropertiesRestTestPolicyModel.apex",
213             "-o",
214             "target/ExecutionPropertiesRestTestPolicyModel.json",
215             "-ac",
216             "src/test/resources/testdata/executionproperties/RESTEventBadHttpCodeFilter.json",
217             "-t",
218             "src/test/resources/tosca/ToscaTemplate.json",
219             "-ot",
220             "target/classes/APEXPolicy.json"
221         };
222         // @formatter:on
223
224         new ApexCliToscaEditorMain(cliArgs);
225
226         // @formatter:off
227         final String[] args = {
228             "-p",
229             "target/classes/APEXPolicy.json"
230         };
231         // @formatter:on
232
233         apexMain = new ApexMain(args);
234
235         await().atMost(5, TimeUnit.SECONDS).until(() -> outContent.toString()
236             .contains("failed with status code 500 and message \"{\"testToRun\": FetchHttpCode}"));
237         assertTrue(apexMain.isAlive());
238         LOGGER.info("testBadCodeFilter-OUTSTRING=\n" + outContent.toString() + "\nEnd-TagUrl");
239     }
240
241     /**
242      * Test Http code filter set and tag Url are transformed correctly.
243      */
244     @Test
245     public void testReplaceUrlTag() throws Exception {
246         final Client client = ClientBuilder.newClient();
247         // @formatter:off
248         final String[] cliArgs = new String[] {
249             "-c",
250             "src/test/resources/policies/executionproperties/policy/ExecutionPropertiesRestTestPolicyModel.apex",
251             "-o",
252             "target/ExecutionPropertiesRestTestPolicyModel.json",
253             "-ac",
254             "src/test/resources/testdata/executionproperties/RESTHttpCodeFilterSetToTagUrlOK.json",
255             "-t",
256             "src/test/resources/tosca/ToscaTemplate.json",
257             "-ot",
258             "target/classes/APEXPolicy.json"
259         };
260         // @formatter:on
261
262         new ApexCliToscaEditorMain(cliArgs);
263
264         // @formatter:off
265         final String[] args = {
266             "-p",
267             "target/classes/APEXPolicy.json"
268         };
269         // @formatter:on
270         apexMain = new ApexMain(args);
271
272         await().atMost(5, TimeUnit.SECONDS).until(() -> {
273             Response response = client.target("http://localhost:32801/TestExecutionRest/apex/event/GetProperUrl")
274                 .request("application/json").get();
275             return response.readEntity(String.class).contains("\"PostProperUrl\": 1");
276         });
277         assertTrue(apexMain.isAlive());
278         LOGGER.info("testReplaceUrlTag-OUTSTRING=\n" + outContent.toString() + "\nEnd-TagUrl");
279     }
280
281     /**
282      * Test Http code filter set and multi-tag Url are transformed correctly.
283      */
284     @Test
285     public void testReplaceUrlMultiTag() throws Exception {
286         final Client client = ClientBuilder.newClient();
287         // @formatter:off
288         final String[] cliArgs = new String[] {
289             "-c",
290             "src/test/resources/policies/executionproperties/policy/ExecutionPropertiesRestTestPolicyModel.apex",
291             "-o",
292             "target/ExecutionPropertiesRestTestPolicyModel.json",
293             "-ac",
294             "src/test/resources/testdata/executionproperties/RESTHttpCodeFilterSetToMultiTagUrlOK.json",
295             "-t",
296             "src/test/resources/tosca/ToscaTemplate.json",
297             "-ot",
298             "target/classes/APEXPolicy.json"
299         };
300         // @formatter:on
301
302         new ApexCliToscaEditorMain(cliArgs);
303
304         // @formatter:off
305         final String[] args = {
306             "-p",
307             "target/classes/APEXPolicy.json"
308         };
309         // @formatter:on
310         apexMain = new ApexMain(args);
311
312         await().atMost(5, TimeUnit.SECONDS).until(() -> {
313             Response response = client.target("http://localhost:32801/TestExecutionRest/apex/event/GetProperUrl")
314                 .request("application/json").get();
315             return response.readEntity(String.class).contains("\"PostProperUrl\": 3");
316         });
317         assertTrue(apexMain.isAlive());
318         LOGGER.info("testReplaceUrlMultiTag-OUTSTRING=\n" + outContent.toString() + "\nEnd-MultiTagUrl");
319     }
320
321 }