2 * ========================LICENSE_START=================================
5 * Copyright (C) 2021 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.oran.dmaapadapter;
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;
27 import com.google.gson.JsonParser;
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;
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;
67 import reactor.core.publisher.Mono;
68 import reactor.test.StepVerifier;
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"//
77 class ApplicationTest {
80 private ApplicationConfig applicationConfig;
86 private InfoTypes types;
89 private ConsumerController consumerController;
92 private EcsSimulatorController ecsSimulatorController;
94 private com.google.gson.Gson gson = new com.google.gson.GsonBuilder().create();
97 int localServerHttpPort;
99 static class TestApplicationConfig extends ApplicationConfig {
101 public String getEcsBaseUrl() {
102 return thisProcessUrl();
106 public String getDmaapBaseUrl() {
107 return thisProcessUrl();
111 public String getSelfUrl() {
112 return thisProcessUrl();
115 private String thisProcessUrl() {
116 final String url = "https://localhost:" + getLocalServerHttpPort();
122 * Overrides the BeanFactory.
125 static class TestBeanFactory extends BeanFactory {
129 public ServletWebServerFactory servletContainer() {
130 return new TomcatServletWebServerFactory();
135 public ApplicationConfig getApplicationConfig() {
136 TestApplicationConfig cfg = new TestApplicationConfig();
143 this.consumerController.testResults.reset();
144 this.ecsSimulatorController.testResults.reset();
148 private AsyncRestClient restClient(boolean useTrustValidation) {
149 WebClientConfig config = this.applicationConfig.getWebClientConfig();
150 HttpProxyConfig httpProxyConfig = ImmutableHttpProxyConfig.builder() //
151 .httpProxyHost("") //
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();
164 AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config);
165 return restClientFactory.createRestClientNoHttpProxy(baseUrl());
168 private AsyncRestClient restClient() {
169 return restClient(false);
172 private String baseUrl() {
173 return "https://localhost:" + this.applicationConfig.getLocalServerHttpPort();
176 private ConsumerJobInfo consumerJobInfo() {
177 return consumerJobInfo("DmaapInformationType", "EI_JOB_ID");
180 private Object jsonObject() {
181 return jsonObject("{}");
184 private Object jsonObject(String json) {
186 return JsonParser.parseString(json).getAsJsonObject();
187 } catch (Exception e) {
188 throw new NullPointerException(e.toString());
192 private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId) {
194 String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
195 return new ConsumerJobInfo(typeId, jsonObject(), "owner", targetUri, "");
196 } catch (Exception e) {
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();
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"))) {
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);
223 String jobUrl = baseUrl() + ProducerCallbacksController.JOB_URL;
224 resp = restClient().deleteForEntity(jobUrl + "/junk").block();
225 assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
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");
234 void testWholeChain() throws Exception {
235 final String JOB_ID = "ID";
237 // Register producer, Register types
238 await().untilAsserted(() -> assertThat(ecsSimulatorController.testResults.registrationInfo).isNotNull());
239 assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(this.types.size());
242 this.ecsSimulatorController.addJob(consumerJobInfo(), JOB_ID, restClient());
243 await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
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");
253 String jobUrl = baseUrl() + ProducerCallbacksController.JOB_URL;
254 String jobs = restClient().get(jobUrl).block();
255 assertThat(jobs).contains(JOB_ID);
258 this.ecsSimulatorController.deleteJob(JOB_ID, restClient());
259 await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
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());
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());
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));
280 void testCreateKafkaJob() {
281 await().untilAsserted(() -> assertThat(ecsSimulatorController.testResults.registrationInfo).isNotNull());
282 assertThat(ecsSimulatorController.testResults.registrationInfo.supportedTypeIds).hasSize(this.types.size());
284 final String TYPE_ID = "KafkaInformationType";
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, "");
291 this.ecsSimulatorController.addJob(jobInfo, "JOB_ID", restClient());
292 await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
295 this.ecsSimulatorController.deleteJob("JOB_ID", restClient());
296 await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
299 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
300 testErrorCode(request, expStatus, responseContains, true);
303 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
304 boolean expectApplicationProblemJsonMediaType) {
305 StepVerifier.create(request) //
306 .expectSubscription() //
308 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
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);