Merge "NONRTRIC - Implement DMaaP mediator producer service in Java"
[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.vardata-directory=./target", //
69         "app.configuration-filepath=./src/test/resources/test_application_configuration.json"//
70 })
71 class ApplicationTest {
72
73     @Autowired
74     private ApplicationConfig applicationConfig;
75
76     @Autowired
77     private ProducerRegstrationTask producerRegstrationTask;
78
79     @Autowired
80     private Jobs jobs;
81
82     @Autowired
83     private InfoTypes types;
84
85     @Autowired
86     private ConsumerController consumerController;
87
88     @Autowired
89     private EcsSimulatorController ecsSimulatorController;
90
91     @LocalServerPort
92     int localServerHttpPort;
93
94     static class TestApplicationConfig extends ApplicationConfig {
95         @Override
96         public String getEcsBaseUrl() {
97             return thisProcessUrl();
98         }
99
100         @Override
101         public String getDmaapBaseUrl() {
102             return thisProcessUrl();
103         }
104
105         @Override
106         public String getSelfUrl() {
107             return thisProcessUrl();
108         }
109
110         private String thisProcessUrl() {
111             final String url = "https://localhost:" + getLocalServerHttpPort();
112             return url;
113         }
114     }
115
116     /**
117      * Overrides the BeanFactory.
118      */
119     @TestConfiguration
120     static class TestBeanFactory extends BeanFactory {
121
122         @Override
123         @Bean
124         public ServletWebServerFactory servletContainer() {
125             return new TomcatServletWebServerFactory();
126         }
127
128         @Override
129         @Bean
130         public ApplicationConfig getApplicationConfig() {
131             TestApplicationConfig cfg = new TestApplicationConfig();
132             return cfg;
133         }
134     }
135
136     @AfterEach
137     void reset() {
138         this.consumerController.testResults.reset();
139         this.ecsSimulatorController.testResults.reset();
140         this.jobs.clear();
141         this.types.clear();
142     }
143
144     private AsyncRestClient restClient(boolean useTrustValidation) {
145         WebClientConfig config = this.applicationConfig.getWebClientConfig();
146         HttpProxyConfig httpProxyConfig = ImmutableHttpProxyConfig.builder() //
147                 .httpProxyHost("") //
148                 .httpProxyPort(0) //
149                 .build();
150         config = ImmutableWebClientConfig.builder() //
151                 .keyStoreType(config.keyStoreType()) //
152                 .keyStorePassword(config.keyStorePassword()) //
153                 .keyStore(config.keyStore()) //
154                 .keyPassword(config.keyPassword()) //
155                 .isTrustStoreUsed(useTrustValidation) //
156                 .trustStore(config.trustStore()) //
157                 .trustStorePassword(config.trustStorePassword()) //
158                 .httpProxyConfig(httpProxyConfig).build();
159
160         AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config);
161         return restClientFactory.createRestClientNoHttpProxy(baseUrl());
162     }
163
164     private AsyncRestClient restClient() {
165         return restClient(false);
166     }
167
168     private String baseUrl() {
169         return "https://localhost:" + this.applicationConfig.getLocalServerHttpPort();
170     }
171
172     private ConsumerJobInfo consumerJobInfo() {
173         InfoType type = this.types.getAll().iterator().next();
174         return consumerJobInfo(type.getId(), "EI_JOB_ID");
175     }
176
177     private Object jsonObject() {
178         return jsonObject("{}");
179     }
180
181     private Object jsonObject(String json) {
182         try {
183             return JsonParser.parseString(json).getAsJsonObject();
184         } catch (Exception e) {
185             throw new NullPointerException(e.toString());
186         }
187     }
188
189     private ConsumerJobInfo consumerJobInfo(String typeId, String infoJobId) {
190         try {
191             String targetUri = baseUrl() + ConsumerController.CONSUMER_TARGET_URL;
192             return new ConsumerJobInfo(typeId, jsonObject(), "owner", targetUri, "");
193         } catch (Exception e) {
194             return null;
195         }
196     }
197
198     @Test
199     void generateApiDoc() throws IOException {
200         String url = "https://localhost:" + applicationConfig.getLocalServerHttpPort() + "/v3/api-docs";
201         ResponseEntity<String> resp = restClient().getForEntity(url).block();
202         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
203         JSONObject jsonObj = new JSONObject(resp.getBody());
204         assertThat(jsonObj.remove("servers")).isNotNull();
205
206         String indented = (jsonObj).toString(4);
207         String docDir = "api/";
208         Files.createDirectories(Paths.get(docDir));
209         try (PrintStream out = new PrintStream(new FileOutputStream(docDir + "api.json"))) {
210             out.print(indented);
211         }
212     }
213
214     @Test
215     void testWholeChain() throws Exception {
216         await().untilAsserted(() -> assertThat(producerRegstrationTask.isRegisteredInEcs()).isTrue());
217
218         this.ecsSimulatorController.addJob(consumerJobInfo(), restClient());
219
220         await().untilAsserted(() -> assertThat(this.jobs.size()).isEqualTo(1));
221
222         DmaapSimulatorController.dmaapResponses.add("DmaapResponse1");
223         DmaapSimulatorController.dmaapResponses.add("DmaapResponse2");
224
225         ConsumerController.TestResults consumer = this.consumerController.testResults;
226         await().untilAsserted(() -> assertThat(consumer.receivedBodies.size()).isEqualTo(2));
227         assertThat(consumer.receivedBodies.get(0)).isEqualTo("DmaapResponse1");
228
229     }
230
231 }