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