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