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.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;
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 InfoType type = this.types.getAll().iterator().next();
178 return consumerJobInfo(type.getId(), "EI_JOB_ID");
181 private Object jsonObject() {
182 return jsonObject("{}");
185 private Object jsonObject(String json) {
187 return JsonParser.parseString(json).getAsJsonObject();
188 } catch (Exception e) {
189 throw new NullPointerException(e.toString());
193 private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId) {
195 String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
196 return new ConsumerJobInfo(typeId, jsonObject(), "owner", targetUri, "");
197 } catch (Exception e) {
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();
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"))) {
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);
224 String jobUrl = baseUrl() + ProducerCallbacksController.JOB_URL;
225 resp = restClient().deleteForEntity(jobUrl + "/junk").block();
226 assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
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");
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(1);
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("ExampleInformationType");
258 this.ecsSimulatorController.deleteJob(JOB_ID, restClient());
259 await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
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);
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);
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));
281 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
282 testErrorCode(request, expStatus, responseContains, true);
285 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
286 boolean expectApplicationProblemJsonMediaType) {
287 StepVerifier.create(request) //
288 .expectSubscription() //
290 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
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);