0aeb196f066e78d585d5dc0912e6098ab06230cf
[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 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.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.io.ByteArrayOutputStream;
30 import java.io.IOException;
31 import java.io.PrintStream;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.util.concurrent.TimeUnit;
35 import org.junit.After;
36 import org.junit.Before;
37 import org.junit.Test;
38 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
39 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
40 import org.onap.policy.apex.service.engine.main.ApexMain;
41 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
42 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
43 import org.onap.policy.common.gson.GsonMessageBodyHandler;
44 import org.onap.policy.common.utils.network.NetworkUtil;
45 import org.slf4j.ext.XLogger;
46 import org.slf4j.ext.XLoggerFactory;
47
48 /**
49  * The Class TestRest2File.
50  */
51 public class TestRest2File {
52     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestRest2File.class);
53
54     private static final int PORT = 32801;
55     private static HttpServletServer server;
56
57     private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
58     private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
59
60     private final PrintStream stdout = System.out;
61     private final PrintStream stderr = System.err;
62     private ApexMain apexMain;
63
64     /**
65      * Before Test.
66      */
67     @Before
68     public void beforeTest() {
69         System.clearProperty("APEX_RELATIVE_FILE_ROOT");
70         System.setOut(new PrintStream(outContent));
71         System.setErr(new PrintStream(errContent));
72     }
73
74     /**
75      * Sets the up.
76      *
77      * @throws Exception the exception
78      */
79     @Before
80     public void setUp() throws Exception {
81         server = HttpServletServerFactoryInstance.getServerFactory().build("TestRest2File", false, null, PORT,
82             "/TestRest2File", false, false);
83
84         server.addServletClass(null, TestRestClientEndpoint.class.getName());
85         server.setSerializationProvider(GsonMessageBodyHandler.class.getName());
86
87         server.start();
88
89         if (!NetworkUtil.isTcpPortOpen("localHost", PORT, 60, 500L)) {
90             throw new IllegalStateException("port " + PORT + " is still not in use");
91         }
92     }
93
94     /**
95      * Tear down.
96      *
97      * @throws Exception the exception
98      */
99     @After
100     public void tearDown() throws Exception {
101         if (null != apexMain) {
102             apexMain.shutdown();
103         }
104         if (server != null) {
105             server.stop();
106         }
107         System.setOut(stdout);
108         System.setErr(stderr);
109     }
110
111     /**
112      * Test rest events in.
113      *
114      * @throws MessagingException the messaging exception
115      * @throws ApexException the apex exception
116      * @throws IOException Signals that an I/O exception has occurred.
117      */
118     @Test
119     public void testRestEventsIn() throws MessagingException, ApexException, IOException {
120         final String[] args = {"-rfr", "target", "-p", "target/examples/config/SampleDomain/REST2FileJsonEvent.json"};
121
122         apexMain = new ApexMain(args);
123         await().atMost(5, TimeUnit.SECONDS).until(
124             () -> Files.readString(Path.of("target/examples/events/SampleDomain/EventsOut.json")).contains(
125                 "04\",\n" + "  \"version\": \"0.0.1\",\n" + "  \"nameSpace\": \"org.onap.policy.apex.sample.events\""));
126         assertTrue(apexMain.isAlive());
127     }
128
129     /**
130      * Test file empty events.
131      *
132      * @throws MessagingException the messaging exception
133      * @throws ApexException the apex exception
134      * @throws IOException Signals that an I/O exception has occurred.
135      */
136     @Test
137     public void testFileEmptyEvents() throws MessagingException, ApexException, IOException {
138
139         final String[] args = {"src/test/resources/prodcons/REST2FileJsonEmptyEvents.json"};
140         apexMain = new ApexMain(args);
141         await().atMost(5, TimeUnit.SECONDS).until(() -> outContent.toString().contains(
142             "received an empty event from URL " + "\"http://localhost:32801/TestRest2File/apex/event/GetEmptyEvent\""));
143         assertTrue(apexMain.isAlive());
144     }
145
146     /**
147      * Test file events no url.
148      *
149      * @throws MessagingException the messaging exception
150      * @throws ApexException the apex exception
151      * @throws IOException Signals that an I/O exception has occurred.
152      */
153     @Test
154     public void testFileEventsNoUrl() throws MessagingException, ApexException, IOException {
155
156         final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventNoURL.json"};
157         apexMain = new ApexMain(args);
158         final String outString = outContent.toString();
159
160         checkRequiredString(outString, " no URL has been set for event sending on RESTCLIENT");
161     }
162
163     /**
164      * Test file events bad url.
165      *
166      * @throws MessagingException the messaging exception
167      * @throws ApexException the apex exception
168      * @throws IOException Signals that an I/O exception has occurred.
169      */
170     @Test
171     public void testFileEventsBadUrl() throws MessagingException, ApexException, IOException {
172
173         final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadURL.json"};
174         apexMain = new ApexMain(args);
175
176         await().atMost(5, TimeUnit.SECONDS).until(() -> outContent.toString().contains("reception of event from URL "
177             + "\"http://localhost:32801/TestRest2File/apex/event/Bad\" failed with status code 404"));
178         assertTrue(apexMain.isAlive());
179     }
180
181     /**
182      * Test file events bad http method.
183      *
184      * @throws MessagingException the messaging exception
185      * @throws ApexException the apex exception
186      * @throws IOException Signals that an I/O exception has occurred.
187      */
188     @Test
189     public void testFileEventsBadHttpMethod() throws MessagingException, ApexException, IOException {
190
191         final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadHTTPMethod.json"};
192         apexMain = new ApexMain(args);
193
194         final String outString = outContent.toString();
195
196         checkRequiredString(outString, "specified HTTP method of \"POST\" is invalid, "
197             + "only HTTP method \"GET\" is supported for event reception on REST client consumer");
198     }
199
200     /**
201      * Test file events bad response.
202      *
203      * @throws MessagingException the messaging exception
204      * @throws ApexException the apex exception
205      * @throws IOException Signals that an I/O exception has occurred.
206      */
207     @Test
208     public void testFileEventsBadResponse() throws MessagingException, ApexException, IOException {
209
210         final String[] args = {"src/test/resources/prodcons/REST2FileJsonEventBadResponse.json"};
211         apexMain = new ApexMain(args);
212         await().atMost(5, TimeUnit.SECONDS)
213             .until(() -> outContent.toString()
214                 .contains("reception of event from URL "
215                     + "\"http://localhost:32801/TestRest2File/apex/event/GetEventBadResponse\" "
216                     + "failed with status code 400 and message \""));
217         assertTrue(apexMain.isAlive());
218     }
219
220     /**
221      * Check if a required string exists in the output.
222      *
223      * @param outputEventText the text to examine
224      * @param requiredString the string to search for
225      */
226     private void checkRequiredString(String outputEventText, String requiredString) {
227         if (!outputEventText.contains(requiredString)) {
228             LOGGER.error("\n***output text:\n" + outputEventText + "\n***");
229             fail("\n***test output did not contain required string:\n" + requiredString + "\n***");
230         }
231     }
232 }