c4c9602adf40f0c1df43587ebb28b60f3e35a5e1
[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.InfoTypes;
50 import org.oran.dmaapadapter.repository.Job;
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         return consumerJobInfo("DmaapInformationType", "EI_JOB_ID");
178     }
179
180     private Object jsonObject() {
181         return jsonObject("{}");
182     }
183
184     private Object jsonObject(String json) {
185         try {
186             return JsonParser.parseString(json).getAsJsonObject();
187         } catch (Exception e) {
188             throw new NullPointerException(e.toString());
189         }
190     }
191
192     private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId) {
193         try {
194             String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
195             return new ConsumerJobInfo(typeId, jsonObject(), "owner", targetUri, "");
196         } catch (Exception e) {
197             return null;
198         }
199     }
200
201     @Test
202     void generateApiDoc() throws IOException {
203         String url = "https://localhost:" + applicationConfig.getLocalServerHttpPort() + "/v3/api-docs";
204         ResponseEntity<String> resp = restClient().getForEntity(url).block();
205         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
206         JSONObject jsonObj = new JSONObject(resp.getBody());
207         assertThat(jsonObj.remove("servers")).isNotNull();
208
209         String indented = (jsonObj).toString(4);
210         String docDir = "api/";
211         Files.createDirectories(Paths.get(docDir));
212         try (PrintStream out = new PrintStream(new FileOutputStream(docDir + "api.json"))) {
213             out.print(indented);
214         }
215     }
216
217     @Test
218     void testResponseCodes() throws Exception {
219         String supervisionUrl = baseUrl() + ProducerCallbacksController.SUPERVISION_URL;
220         ResponseEntity<String> resp = restClient().getForEntity(supervisionUrl).block();
221         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
222
223         String jobUrl = baseUrl() + ProducerCallbacksController.JOB_URL;
224         resp = restClient().deleteForEntity(jobUrl + "/junk").block();
225         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
226
227         ProducerJobInfo info = new ProducerJobInfo(null, "id", "typeId", "targetUri", "owner", "lastUpdated");
228         String body = gson.toJson(info);
229         testErrorCode(restClient().post(jobUrl, body, MediaType.APPLICATION_JSON), HttpStatus.NOT_FOUND,
230                 "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(this.types.size());
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(JOB_ID);
256
257         // Delete the job
258         this.ecsSimulatorController.deleteJob(JOB_ID, restClient());
259         await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
260     }
261
262     @Test
263     void testReRegister() throws Exception {
264         // Wait foir register types and producer
265         await().untilAsserted(() -> assertThat(ecsSimulatorController.testResults.registrationInfo).isNotNull());
266         assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(this.types.size());
267
268         // Clear the registration, should trigger a re-register
269         ecsSimulatorController.testResults.reset();
270         await().untilAsserted(() -> assertThat(ecsSimulatorController.testResults.registrationInfo).isNotNull());
271         assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(this.types.size());
272
273         // Just clear the registerred types, should trigger a re-register
274         ecsSimulatorController.testResults.types.clear();
275         await().untilAsserted(
276                 () -> assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(2));
277     }
278
279     @Test
280     void testCreateKafkaJob() {
281         await().untilAsserted(() -> assertThat(ecsSimulatorController.testResults.registrationInfo).isNotNull());
282         assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(this.types.size());
283
284         final String TYPE_ID = "KafkaInformationType";
285
286         Job.Parameters param = new Job.Parameters("filter", new Job.BufferTimeout(123, 456), 1);
287         String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
288         ConsumerJobInfo jobInfo = new ConsumerJobInfo(TYPE_ID, jsonObject(gson.toJson(param)), "owner", targetUri, "");
289
290         // Create a job
291         this.ecsSimulatorController.addJob(jobInfo, "JOB_ID", restClient());
292         await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
293
294         // Delete the job
295         this.ecsSimulatorController.deleteJob("JOB_ID", restClient());
296         await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
297     }
298
299     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
300         testErrorCode(request, expStatus, responseContains, true);
301     }
302
303     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
304             boolean expectApplicationProblemJsonMediaType) {
305         StepVerifier.create(request) //
306                 .expectSubscription() //
307                 .expectErrorMatches(
308                         t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
309                 .verify();
310     }
311
312     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
313             boolean expectApplicationProblemJsonMediaType) {
314         assertTrue(throwable instanceof WebClientResponseException);
315         WebClientResponseException responseException = (WebClientResponseException) throwable;
316         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
317         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
318         if (expectApplicationProblemJsonMediaType) {
319             assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
320         }
321         return true;
322     }
323 }