557cfdebd27e4be7a81eb4a2249cf5d7d4c041cc
[policy/apex-pdp.git] / testsuites / integration / integration-uservice-test / src / test / java / org / onap / policy / apex / testsuites / integration / uservice / adapt / restclient / TestRest2File.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020, 2023-2024 Nordix Foundation.
5  *  Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.apex.testsuites.integration.uservice.adapt.restclient;
24
25 import static org.awaitility.Awaitility.await;
26 import static org.junit.jupiter.api.Assertions.assertTrue;
27 import static org.junit.jupiter.api.Assertions.fail;
28
29 import java.io.ByteArrayOutputStream;
30 import java.io.PrintStream;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.util.concurrent.TimeUnit;
34 import org.junit.jupiter.api.AfterEach;
35 import org.junit.jupiter.api.BeforeEach;
36 import org.junit.jupiter.api.Test;
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  * The Class TestRest2File.
47  */
48 class TestRest2File {
49     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestRest2File.class);
50
51     private static final int PORT = 32801;
52     private static HttpServletServer server;
53
54     private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
55     private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
56
57     private final PrintStream stdout = System.out;
58     private final PrintStream stderr = System.err;
59     private ApexMain apexMain;
60
61     /**
62      * Before Test.
63      */
64     @BeforeEach
65     void beforeTest() {
66         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
67         System.setOut(new PrintStream(outContent));
68         System.setErr(new PrintStream(errContent));
69     }
70
71     /**
72      * Sets the up.
73      *
74      * @throws Exception the exception
75      */
76     @BeforeEach
77     void setUp() throws Exception {
78         server = HttpServletServerFactoryInstance.getServerFactory().build("TestRest2File", false, null, PORT, false,
79             "/TestRest2File", 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      * Tear down.
93      *
94      * @throws Exception the exception
95      */
96     @AfterEach
97     void tearDown() throws Exception {
98         if (null != apexMain) {
99             apexMain.shutdown();
100         }
101         if (server != null) {
102             server.stop();
103         }
104         System.setOut(stdout);
105         System.setErr(stderr);
106     }
107
108     /**
109      * Test rest events in.
110      */
111     @Test
112     void testRestEventsIn() {
113         final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/REST2FileJsonEvent.json"};
114
115         apexMain = new ApexMain(args);
116         await().atMost(5, TimeUnit.SECONDS).until(
117             () -> Files.readString(Path.of("target/examples/events/SampleDomain/EventsOut.json")).contains(
118                 """
119                     04",
120                       "version": "0.0.1",
121                       "nameSpace": "org.onap.policy.apex.sample.events\""""));
122         assertTrue(apexMain.isAlive());
123     }
124
125     /**
126      * Test file empty events.
127      */
128     @Test
129     void testFileEmptyEvents() {
130
131         final String[] args = {"src/test/resources/prodcons/REST2FileJsonEmptyEvents.json"};
132         apexMain = new ApexMain(args);
133         await().atMost(5, TimeUnit.SECONDS).until(() -> outContent.toString().contains(
134             "received an empty event from URL " + "\"http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent\""));
135         assertTrue(apexMain.isAlive());
136     }
137
138     /**
139      * Test file events no url.
140      */
141     @Test
142     void testFileEventsNoUrl() {
143
144         final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventNoURL.json"};
145         apexMain = new ApexMain(args);
146         final String outString = outContent.toString();
147
148         checkRequiredString(outString, " no URL has been set for event sending on RESTCLIENT");
149     }
150
151     /**
152      * Test file events bad url.
153      */
154     @Test
155     void testFileEventsBadUrl() {
156
157         final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadURL.json"};
158         apexMain = new ApexMain(args);
159
160         await().atMost(5, TimeUnit.SECONDS).until(() -> outContent.toString().contains("reception of event from URL "
161             + "\"http://localhost:32801/TestRest2File/apex/event/Bad\" failed with status code 404"));
162         assertTrue(apexMain.isAlive());
163     }
164
165     /**
166      * Test file events bad http method.
167      */
168     @Test
169     void testFileEventsBadHttpMethod() {
170
171         final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json"};
172         apexMain = new ApexMain(args);
173
174         final String outString = outContent.toString();
175
176         checkRequiredString(outString, "specified HTTP method of \"POST\" is invalid, "
177             + "only HTTP method \"GET\" is supported for event reception on REST client consumer");
178     }
179
180     /**
181      * Test file events bad response.
182      */
183     @Test
184     void testFileEventsBadResponse() {
185
186         final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadResponse.json"};
187         apexMain = new ApexMain(args);
188         await().atMost(5, TimeUnit.SECONDS)
189             .until(() -> outContent.toString()
190                 .contains("reception of event from URL "
191                     + "\"http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse\" "
192                     + "failed with status code 400 and message \""));
193         assertTrue(apexMain.isAlive());
194     }
195
196     /**
197      * Check if a required string exists in the output.
198      *
199      * @param outputEventText the text to examine
200      * @param requiredString  the string to search for
201      */
202     private void checkRequiredString(String outputEventText, String requiredString) {
203         if (!outputEventText.contains(requiredString)) {
204             LOGGER.error("\n***output text:\n" + outputEventText + "\n***");
205             fail("\n***test output did not contain required string:\n" + requiredString + "\n***");
206         }
207     }
208 }