1ca4fac28c6902f25f7b1214689b0b012c4364d8
[nonrtric.git] / dmaap-adaptor-java / src / test / java / org / oran / dmaapadapter / ApplicationTest.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2021 Nordix Foundation
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  * ========================LICENSE_END===================================
19  */
20
21 package org.oran.dmaapadapter;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.jupiter.api.Assertions.assertTrue;
26
27 import com.google.gson.JsonParser;
28
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.io.PrintStream;
32 import java.nio.file.Files;
33 import java.nio.file.Paths;
34
35 import org.json.JSONObject;
36 import org.junit.jupiter.api.AfterEach;
37 import org.junit.jupiter.api.Test;
38 import org.junit.jupiter.api.extension.ExtendWith;
39 import org.oran.dmaapadapter.clients.AsyncRestClient;
40 import org.oran.dmaapadapter.clients.AsyncRestClientFactory;
41 import org.oran.dmaapadapter.configuration.ApplicationConfig;
42 import org.oran.dmaapadapter.configuration.ImmutableHttpProxyConfig;
43 import org.oran.dmaapadapter.configuration.ImmutableWebClientConfig;
44 import org.oran.dmaapadapter.configuration.WebClientConfig;
45 import org.oran.dmaapadapter.configuration.WebClientConfig.HttpProxyConfig;
46 import org.oran.dmaapadapter.controllers.ProducerCallbacksController;
47 import org.oran.dmaapadapter.r1.ConsumerJobInfo;
48 import org.oran.dmaapadapter.r1.ProducerJobInfo;
49 import org.oran.dmaapadapter.repository.InfoType;
50 import org.oran.dmaapadapter.repository.InfoTypes;
51 import org.oran.dmaapadapter.repository.Jobs;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.boot.test.context.SpringBootTest;
54 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
55 import org.springframework.boot.test.context.TestConfiguration;
56 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
57 import org.springframework.boot.web.server.LocalServerPort;
58 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
59 import org.springframework.context.annotation.Bean;
60 import org.springframework.http.HttpStatus;
61 import org.springframework.http.MediaType;
62 import org.springframework.http.ResponseEntity;
63 import org.springframework.test.context.TestPropertySource;
64 import org.springframework.test.context.junit.jupiter.SpringExtension;
65 import org.springframework.web.reactive.function.client.WebClientResponseException;
66
67 import reactor.core.publisher.Mono;
68 import reactor.test.StepVerifier;
69
70 @ExtendWith(SpringExtension.class)
71 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
72 @TestPropertySource(properties = { //
73         "server.ssl.key-store=./config/keystore.jks", //
74         "app.webclient.trust-store=./config/truststore.jks", //
75         "app.configuration-filepath=./src/test/resources/test_application_configuration.json"//
76 })
77 class ApplicationTest {
78
79     @Autowired
80     private ApplicationConfig applicationConfig;
81
82     @Autowired
83     private Jobs jobs;
84
85     @Autowired
86     private InfoTypes types;
87
88     @Autowired
89     private ConsumerController consumerController;
90
91     @Autowired
92     private EcsSimulatorController ecsSimulatorController;
93
94     private com.google.gson.Gson gson = new com.google.gson.GsonBuilder().create();
95
96     @LocalServerPort
97     int localServerHttpPort;
98
99     static class TestApplicationConfig extends ApplicationConfig {
100         @Override
101         public String getEcsBaseUrl() {
102             return thisProcessUrl();
103         }
104
105         @Override
106         public String getDmaapBaseUrl() {
107             return thisProcessUrl();
108         }
109
110         @Override
111         public String getSelfUrl() {
112             return thisProcessUrl();
113         }
114
115         private String thisProcessUrl() {
116             final String url = "https://localhost:" + getLocalServerHttpPort();
117             return url;
118         }
119     }
120
121     /**
122      * Overrides the BeanFactory.
123      */
124     @TestConfiguration
125     static class TestBeanFactory extends BeanFactory {
126
127         @Override
128         @Bean
129         public ServletWebServerFactory servletContainer() {
130             return new TomcatServletWebServerFactory();
131         }
132
133         @Override
134         @Bean
135         public ApplicationConfig getApplicationConfig() {
136             TestApplicationConfig cfg = new TestApplicationConfig();
137             return cfg;
138         }
139     }
140
141     @AfterEach
142     void reset() {
143         this.consumerController.testResults.reset();
144         this.ecsSimulatorController.testResults.reset();
145         this.jobs.clear();
146     }
147
148     private AsyncRestClient restClient(boolean useTrustValidation) {
149         WebClientConfig config = this.applicationConfig.getWebClientConfig();
150         HttpProxyConfig httpProxyConfig = ImmutableHttpProxyConfig.builder() //
151                 .httpProxyHost("") //
152                 .httpProxyPort(0) //
153                 .build();
154         config = ImmutableWebClientConfig.builder() //
155                 .keyStoreType(config.keyStoreType()) //
156                 .keyStorePassword(config.keyStorePassword()) //
157                 .keyStore(config.keyStore()) //
158                 .keyPassword(config.keyPassword()) //
159                 .isTrustStoreUsed(useTrustValidation) //
160                 .trustStore(config.trustStore()) //
161                 .trustStorePassword(config.trustStorePassword()) //
162                 .httpProxyConfig(httpProxyConfig).build();
163
164         AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config);
165         return restClientFactory.createRestClientNoHttpProxy(baseUrl());
166     }
167
168     private AsyncRestClient restClient() {
169         return restClient(false);
170     }
171
172     private String baseUrl() {
173         return "https://localhost:" + this.applicationConfig.getLocalServerHttpPort();
174     }
175
176     private ConsumerJobInfo consumerJobInfo() {
177         InfoType type = this.types.getAll().iterator().next();
178         return consumerJobInfo(type.getId(), "EI_JOB_ID");
179     }
180
181     private Object jsonObject() {
182         return jsonObject("{}");
183     }
184
185     private Object jsonObject(String json) {
186         try {
187             return JsonParser.parseString(json).getAsJsonObject();
188         } catch (Exception e) {
189             throw new NullPointerException(e.toString());
190         }
191     }
192
193     private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId) {
194         try {
195             String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
196             return new ConsumerJobInfo(typeId, jsonObject(), "owner", targetUri, "");
197         } catch (Exception e) {
198             return null;
199         }
200     }
201
202     @Test
203     void generateApiDoc() throws IOException {
204         String url = "https://localhost:" + applicationConfig.getLocalServerHttpPort() + "/v3/api-docs";
205         ResponseEntity<String> resp = restClient().getForEntity(url).block();
206         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
207         JSONObject jsonObj = new JSONObject(resp.getBody());
208         assertThat(jsonObj.remove("servers")).isNotNull();
209
210         String indented = (jsonObj).toString(4);
211         String docDir = "api/";
212         Files.createDirectories(Paths.get(docDir));
213         try (PrintStream out = new PrintStream(new FileOutputStream(docDir + "api.json"))) {
214             out.print(indented);
215         }
216     }
217
218     @Test
219     void testResponseCodes() throws Exception {
220         String supervisionUrl = baseUrl() + ProducerCallbacksController.SUPERVISION_URL;
221         ResponseEntity<String> resp = restClient().getForEntity(supervisionUrl).block();
222         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
223
224         String jobUrl = baseUrl() + ProducerCallbacksController.JOB_URL;
225         resp = restClient().deleteForEntity(jobUrl + "/junk").block();
226         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
227
228         ProducerJobInfo info = new ProducerJobInfo(null, "id", "typeId", "targetUri", "owner", "lastUpdated");
229         String body = gson.toJson(info);
230         testErrorCode(restClient().post(jobUrl, body), HttpStatus.NOT_FOUND, "Could not find type");
231     }
232
233     @Test
234     void testWholeChain() throws Exception {
235         final String JOB_ID = "ID";
236
237         // Register producer, Register types
238         await().untilAsserted(() -> assertThat(ecsSimulatorController.testResults.registrationInfo).isNotNull());
239         assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(1);
240
241         // Create a job
242         this.ecsSimulatorController.addJob(consumerJobInfo(), JOB_ID, restClient());
243         await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
244
245         // Return two messages from DMAAP and verify that these are sent to the owner of
246         // the job (consumer)
247         DmaapSimulatorController.dmaapResponses.add("DmaapResponse1");
248         DmaapSimulatorController.dmaapResponses.add("DmaapResponse2");
249         ConsumerController.TestResults consumer = this.consumerController.testResults;
250         await().untilAsserted(() -> assertThat(consumer.receivedBodies.size()).isEqualTo(2));
251         assertThat(consumer.receivedBodies.get(0)).isEqualTo("DmaapResponse1");
252
253         String jobUrl = baseUrl() + ProducerCallbacksController.JOB_URL;
254         String jobs = restClient().get(jobUrl).block();
255         assertThat(jobs).contains("ExampleInformationType");
256
257         // Delete the job
258         this.ecsSimulatorController.deleteJob(JOB_ID, restClient());
259         await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
260
261     }
262
263     @Test
264     void testReRegister() throws Exception {
265         // Wait foir register types and producer
266         await().untilAsserted(() -> assertThat(ecsSimulatorController.testResults.registrationInfo).isNotNull());
267         assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(1);
268
269         // Clear the registration, should trigger a re-register
270         ecsSimulatorController.testResults.reset();
271         await().untilAsserted(() -> assertThat(ecsSimulatorController.testResults.registrationInfo).isNotNull());
272         assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(1);
273
274         // Just clear the registerred types, should trigger a re-register
275         ecsSimulatorController.testResults.types.clear();
276         await().untilAsserted(
277                 () -> assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(1));
278
279     }
280
281     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
282         testErrorCode(request, expStatus, responseContains, true);
283     }
284
285     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
286             boolean expectApplicationProblemJsonMediaType) {
287         StepVerifier.create(request) //
288                 .expectSubscription() //
289                 .expectErrorMatches(
290                         t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
291                 .verify();
292     }
293
294     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
295             boolean expectApplicationProblemJsonMediaType) {
296         assertTrue(throwable instanceof WebClientResponseException);
297         WebClientResponseException responseException = (WebClientResponseException) throwable;
298         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
299         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
300         if (expectApplicationProblemJsonMediaType) {
301             assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
302         }
303         return true;
304     }
305
306 }