aa300c5f420c85850e4e505962f00aaeb16b8d95
[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
26 import com.google.gson.JsonParser;
27
28 import java.io.FileOutputStream;
29 import java.io.IOException;
30 import java.io.PrintStream;
31 import java.nio.file.Files;
32 import java.nio.file.Paths;
33
34 import org.json.JSONObject;
35 import org.junit.jupiter.api.AfterEach;
36 import org.junit.jupiter.api.Test;
37 import org.junit.jupiter.api.extension.ExtendWith;
38 import org.oran.dmaapadapter.clients.AsyncRestClient;
39 import org.oran.dmaapadapter.clients.AsyncRestClientFactory;
40 import org.oran.dmaapadapter.configuration.ApplicationConfig;
41 import org.oran.dmaapadapter.configuration.ImmutableHttpProxyConfig;
42 import org.oran.dmaapadapter.configuration.ImmutableWebClientConfig;
43 import org.oran.dmaapadapter.configuration.WebClientConfig;
44 import org.oran.dmaapadapter.configuration.WebClientConfig.HttpProxyConfig;
45 import org.oran.dmaapadapter.r1.ConsumerJobInfo;
46 import org.oran.dmaapadapter.repository.InfoType;
47 import org.oran.dmaapadapter.repository.InfoTypes;
48 import org.oran.dmaapadapter.repository.Jobs;
49 import org.oran.dmaapadapter.tasks.ProducerRegstrationTask;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.boot.test.context.SpringBootTest;
52 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
53 import org.springframework.boot.test.context.TestConfiguration;
54 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
55 import org.springframework.boot.web.server.LocalServerPort;
56 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
57 import org.springframework.context.annotation.Bean;
58 import org.springframework.http.HttpStatus;
59 import org.springframework.http.ResponseEntity;
60 import org.springframework.test.context.TestPropertySource;
61 import org.springframework.test.context.junit.jupiter.SpringExtension;
62
63 @ExtendWith(SpringExtension.class)
64 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
65 @TestPropertySource(properties = { //
66         "server.ssl.key-store=./config/keystore.jks", //
67         "app.webclient.trust-store=./config/truststore.jks", //
68         "app.configuration-filepath=./src/test/resources/test_application_configuration.json"//
69 })
70 class ApplicationTest {
71
72     @Autowired
73     private ApplicationConfig applicationConfig;
74
75     @Autowired
76     private ProducerRegstrationTask producerRegstrationTask;
77
78     @Autowired
79     private Jobs jobs;
80
81     @Autowired
82     private InfoTypes types;
83
84     @Autowired
85     private ConsumerController consumerController;
86
87     @Autowired
88     private EcsSimulatorController ecsSimulatorController;
89
90     @LocalServerPort
91     int localServerHttpPort;
92
93     static class TestApplicationConfig extends ApplicationConfig {
94         @Override
95         public String getEcsBaseUrl() {
96             return thisProcessUrl();
97         }
98
99         @Override
100         public String getDmaapBaseUrl() {
101             return thisProcessUrl();
102         }
103
104         @Override
105         public String getSelfUrl() {
106             return thisProcessUrl();
107         }
108
109         private String thisProcessUrl() {
110             final String url = "https://localhost:" + getLocalServerHttpPort();
111             return url;
112         }
113     }
114
115     /**
116      * Overrides the BeanFactory.
117      */
118     @TestConfiguration
119     static class TestBeanFactory extends BeanFactory {
120
121         @Override
122         @Bean
123         public ServletWebServerFactory servletContainer() {
124             return new TomcatServletWebServerFactory();
125         }
126
127         @Override
128         @Bean
129         public ApplicationConfig getApplicationConfig() {
130             TestApplicationConfig cfg = new TestApplicationConfig();
131             return cfg;
132         }
133     }
134
135     @AfterEach
136     void reset() {
137         this.consumerController.testResults.reset();
138         this.ecsSimulatorController.testResults.reset();
139         this.jobs.clear();
140         this.types.clear();
141     }
142
143     private AsyncRestClient restClient(boolean useTrustValidation) {
144         WebClientConfig config = this.applicationConfig.getWebClientConfig();
145         HttpProxyConfig httpProxyConfig = ImmutableHttpProxyConfig.builder() //
146                 .httpProxyHost("") //
147                 .httpProxyPort(0) //
148                 .build();
149         config = ImmutableWebClientConfig.builder() //
150                 .keyStoreType(config.keyStoreType()) //
151                 .keyStorePassword(config.keyStorePassword()) //
152                 .keyStore(config.keyStore()) //
153                 .keyPassword(config.keyPassword()) //
154                 .isTrustStoreUsed(useTrustValidation) //
155                 .trustStore(config.trustStore()) //
156                 .trustStorePassword(config.trustStorePassword()) //
157                 .httpProxyConfig(httpProxyConfig).build();
158
159         AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config);
160         return restClientFactory.createRestClientNoHttpProxy(baseUrl());
161     }
162
163     private AsyncRestClient restClient() {
164         return restClient(false);
165     }
166
167     private String baseUrl() {
168         return "https://localhost:" + this.applicationConfig.getLocalServerHttpPort();
169     }
170
171     private ConsumerJobInfo consumerJobInfo() {
172         InfoType type = this.types.getAll().iterator().next();
173         return consumerJobInfo(type.getId(), "EI_JOB_ID");
174     }
175
176     private Object jsonObject() {
177         return jsonObject("{}");
178     }
179
180     private Object jsonObject(String json) {
181         try {
182             return JsonParser.parseString(json).getAsJsonObject();
183         } catch (Exception e) {
184             throw new NullPointerException(e.toString());
185         }
186     }
187
188     private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId) {
189         try {
190             String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
191             return new ConsumerJobInfo(typeId, jsonObject(), "owner", targetUri, "");
192         } catch (Exception e) {
193             return null;
194         }
195     }
196
197     @Test
198     void generateApiDoc() throws IOException {
199         String url = "https://localhost:" + applicationConfig.getLocalServerHttpPort() + "/v3/api-docs";
200         ResponseEntity<String> resp = restClient().getForEntity(url).block();
201         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
202         JSONObject jsonObj = new JSONObject(resp.getBody());
203         assertThat(jsonObj.remove("servers")).isNotNull();
204
205         String indented = (jsonObj).toString(4);
206         String docDir = "api/";
207         Files.createDirectories(Paths.get(docDir));
208         try (PrintStream out = new PrintStream(new FileOutputStream(docDir + "api.json"))) {
209             out.print(indented);
210         }
211     }
212
213     @Test
214     void testWholeChain() throws Exception {
215         final String JOB_ID = "ID";
216
217         // Register producer, Register types
218         await().untilAsserted(() -> assertThat(producerRegstrationTask.isRegisteredInEcs()).isTrue());
219
220         // Create a job
221         this.ecsSimulatorController.addJob(consumerJobInfo(), JOB_ID, restClient());
222         await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
223
224         // Return two messages from DMAAP and verify that these are sent to the owner of
225         // the job (consumer)
226         DmaapSimulatorController.dmaapResponses.add("DmaapResponse1");
227         DmaapSimulatorController.dmaapResponses.add("DmaapResponse2");
228         ConsumerController.TestResults consumer = this.consumerController.testResults;
229         await().untilAsserted(() -> assertThat(consumer.receivedBodies.size()).isEqualTo(2));
230         assertThat(consumer.receivedBodies.get(0)).isEqualTo("DmaapResponse1");
231
232         // Delete the job
233         this.ecsSimulatorController.deleteJob(JOB_ID, restClient());
234         await().untilAsserted(() -> assertThat(this.jobs.size()).isZero());
235     }
236
237 }