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.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;
68 import reactor.core.publisher.Mono;
69 import reactor.test.StepVerifier;
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"//
78 class ApplicationTest {
81 private ApplicationConfig applicationConfig;
84 private ProducerRegstrationTask producerRegstrationTask;
90 private InfoTypes types;
93 private ConsumerController consumerController;
96 private EcsSimulatorController ecsSimulatorController;
98 private com.google.gson.Gson gson = new com.google.gson.GsonBuilder().create();
101 int localServerHttpPort;
103 static class TestApplicationConfig extends ApplicationConfig {
105 public String getEcsBaseUrl() {
106 return thisProcessUrl();
110 public String getDmaapBaseUrl() {
111 return thisProcessUrl();
115 public String getSelfUrl() {
116 return thisProcessUrl();
119 private String thisProcessUrl() {
120 final String url = "https://localhost:" + getLocalServerHttpPort();
126 * Overrides the BeanFactory.
129 static class TestBeanFactory extends BeanFactory {
133 public ServletWebServerFactory servletContainer() {
134 return new TomcatServletWebServerFactory();
139 public ApplicationConfig getApplicationConfig() {
140 TestApplicationConfig cfg = new TestApplicationConfig();
147 this.consumerController.testResults.reset();
148 this.ecsSimulatorController.testResults.reset();
153 private AsyncRestClient restClient(boolean useTrustValidation) {
154 WebClientConfig config = this.applicationConfig.getWebClientConfig();
155 HttpProxyConfig httpProxyConfig = ImmutableHttpProxyConfig.builder() //
156 .httpProxyHost("") //
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();
169 AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config);
170 return restClientFactory.createRestClientNoHttpProxy(baseUrl());
173 private AsyncRestClient restClient() {
174 return restClient(false);
177 private String baseUrl() {
178 return "https://localhost:" + this.applicationConfig.getLocalServerHttpPort();
181 private ConsumerJobInfo consumerJobInfo() {
182 InfoType type = this.types.getAll().iterator().next();
183 return consumerJobInfo(type.getId(), "EI_JOB_ID");
186 private Object jsonObject() {
187 return jsonObject("{}");
190 private Object jsonObject(String json) {
192 return JsonParser.parseString(json).getAsJsonObject();
193 } catch (Exception e) {
194 throw new NullPointerException(e.toString());
198 private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId) {
200 String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
201 return new ConsumerJobInfo(typeId, jsonObject(), "owner", targetUri, "");
202 } catch (Exception e) {
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();
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"))) {
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);
229 String jobUrl = baseUrl() + ProducerCallbacksController.JOB_URL;
230 resp = restClient().deleteForEntity(jobUrl + "/junk").block();
231 assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
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");
239 void testWholeChain() throws Exception {
240 final String JOB_ID = "ID";
242 // Register producer, Register types
243 await().untilAsserted(() -> assertThat(producerRegstrationTask.isRegisteredInEcs()).isTrue());
246 this.ecsSimulatorController.addJob(consumerJobInfo(), JOB_ID, restClient());
247 await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
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");
258 this.ecsSimulatorController.deleteJob(JOB_ID, restClient());
259 await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
262 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
263 testErrorCode(request, expStatus, responseContains, true);
266 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
267 boolean expectApplicationProblemJsonMediaType) {
268 StepVerifier.create(request) //
269 .expectSubscription() //
271 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
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);