cbaa59fa448732e4f08d98d11450603f2b7671ce
[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         this.types.clear();
151     }
152
153     private AsyncRestClient restClient(boolean useTrustValidation) {
154         WebClientConfig config = this.applicationConfig.getWebClientConfig();
155         HttpProxyConfig httpProxyConfig = ImmutableHttpProxyConfig.builder() //
156                 .httpProxyHost("") //
157                 .httpProxyPort(0) //
158                 .build();
159         config = ImmutableWebClientConfig.builder() //
160                 .keyStoreType(config.keyStoreType()) //
161                 .keyStorePassword(config.keyStorePassword()) //
162                 .keyStore(config.keyStore()) //
163                 .keyPassword(config.keyPassword()) //
164                 .isTrustStoreUsed(useTrustValidation) //
165                 .trustStore(config.trustStore()) //
166                 .trustStorePassword(config.trustStorePassword()) //
167                 .httpProxyConfig(httpProxyConfig).build();
168
169         AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config);
170         return restClientFactory.createRestClientNoHttpProxy(baseUrl());
171     }
172
173     private AsyncRestClient restClient() {
174         return restClient(false);
175     }
176
177     private String baseUrl() {
178         return "https://localhost:" + this.applicationConfig.getLocalServerHttpPort();
179     }
180
181     private ConsumerJobInfo consumerJobInfo() {
182         InfoType type = this.types.getAll().iterator().next();
183         return consumerJobInfo(type.getId(), "EI_JOB_ID");
184     }
185
186     private Object jsonObject() {
187         return jsonObject("{}");
188     }
189
190     private Object jsonObject(String json) {
191         try {
192             return JsonParser.parseString(json).getAsJsonObject();
193         } catch (Exception e) {
194             throw new NullPointerException(e.toString());
195         }
196     }
197
198     private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId) {
199         try {
200             String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
201             return new ConsumerJobInfo(typeId, jsonObject(), "owner", targetUri, "");
202         } catch (Exception e) {
203             return null;
204         }
205     }
206
207     @Test
208     void generateApiDoc() throws IOException {
209         String url = "https://localhost:" + applicationConfig.getLocalServerHttpPort() + "/v3/api-docs";
210         ResponseEntity<String> resp = restClient().getForEntity(url).block();
211         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
212         JSONObject jsonObj = new JSONObject(resp.getBody());
213         assertThat(jsonObj.remove("servers")).isNotNull();
214
215         String indented = (jsonObj).toString(4);
216         String docDir = "api/";
217         Files.createDirectories(Paths.get(docDir));
218         try (PrintStream out = new PrintStream(new FileOutputStream(docDir + "api.json"))) {
219             out.print(indented);
220         }
221     }
222
223     @Test
224     void testResponseCodes() throws Exception {
225         String supervisionUrl = baseUrl() + ProducerCallbacksController.SUPERVISION_URL;
226         ResponseEntity<String> resp = restClient().getForEntity(supervisionUrl).block();
227         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
228
229         String jobUrl = baseUrl() + ProducerCallbacksController.JOB_URL;
230         resp = restClient().deleteForEntity(jobUrl + "/junk").block();
231         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
232
233         ProducerJobInfo info = new ProducerJobInfo(null, "id", "typeId", "targetUri", "owner", "lastUpdated");
234         String body = gson.toJson(info);
235         testErrorCode(restClient().post(jobUrl, body), HttpStatus.NOT_FOUND, "Could not find type");
236     }
237
238     @Test
239     void testWholeChain() throws Exception {
240         final String JOB_ID = "ID";
241
242         // Register producer, Register types
243         await().untilAsserted(() -> assertThat(producerRegstrationTask.isRegisteredInEcs()).isTrue());
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         // Delete the job
258         this.ecsSimulatorController.deleteJob(JOB_ID, restClient());
259         await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
260     }
261
262     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
263         testErrorCode(request, expStatus, responseContains, true);
264     }
265
266     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
267             boolean expectApplicationProblemJsonMediaType) {
268         StepVerifier.create(request) //
269                 .expectSubscription() //
270                 .expectErrorMatches(
271                         t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
272                 .verify();
273     }
274
275     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
276             boolean expectApplicationProblemJsonMediaType) {
277         assertTrue(throwable instanceof WebClientResponseException);
278         WebClientResponseException responseException = (WebClientResponseException) throwable;
279         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
280         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
281         if (expectApplicationProblemJsonMediaType) {
282             assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
283         }
284         return true;
285     }
286
287 }