Merge "Stepping to springboot 3"
[nonrtric.git] / pmlog / src / test / java / org / oran / pmlog / ApplicationTest.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2023 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.pmlog;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25 import static org.mockito.ArgumentMatchers.any;
26 import static org.mockito.Mockito.spy;
27
28 import java.io.FileNotFoundException;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.io.PrintStream;
32 import java.lang.invoke.MethodHandles;
33 import java.nio.charset.Charset;
34 import java.nio.file.Files;
35 import java.nio.file.Path;
36
37 import org.json.JSONObject;
38 import org.junit.jupiter.api.AfterEach;
39 import org.junit.jupiter.api.BeforeEach;
40 import org.junit.jupiter.api.MethodOrderer;
41 import org.junit.jupiter.api.Test;
42 import org.junit.jupiter.api.TestMethodOrder;
43 import org.mockito.Mockito;
44 import org.oran.pmlog.clients.AsyncRestClient;
45 import org.oran.pmlog.clients.AsyncRestClientFactory;
46 import org.oran.pmlog.clients.SecurityContext;
47 import org.oran.pmlog.configuration.ApplicationConfig;
48 import org.oran.pmlog.configuration.ConsumerJobInfo;
49 import org.oran.pmlog.configuration.WebClientConfig;
50 import org.oran.pmlog.configuration.WebClientConfig.HttpProxyConfig;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
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.servlet.server.ServletWebServerFactory;
59 import org.springframework.context.annotation.Bean;
60 import org.springframework.http.HttpStatus;
61 import org.springframework.http.ResponseEntity;
62 import org.springframework.test.context.TestPropertySource;
63 import reactor.core.publisher.Flux;
64
65 @TestMethodOrder(MethodOrderer.MethodName.class)
66 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
67 @TestPropertySource(properties = { //
68         "server.ssl.key-store=./config/keystore.jks", //
69         "app.webclient.trust-store=./config/truststore.jks", //
70         "app.webclient.trust-store-used=true" //
71 })
72 class ApplicationTest {
73
74     @Autowired
75     private ApplicationConfig applicationConfig;
76
77     @Autowired
78     SecurityContext securityContext;
79
80     @Autowired
81     private IcsSimulatorController icsSimulatorController;
82
83     @Autowired
84     private ConsumerRegstrationTask consumerRegstrationTask;
85
86     private com.google.gson.Gson gson = new com.google.gson.GsonBuilder().disableHtmlEscaping().create();
87
88     private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
89
90     static class TestApplicationConfig extends ApplicationConfig {
91
92         @Override
93         public String getIcsBaseUrl() {
94             return thisProcessUrl();
95         }
96
97         String thisProcessUrl() {
98             final String url = "https://localhost:" + getLocalServerHttpsPort();
99             return url;
100         }
101     }
102
103     /**
104      * Overrides the BeanFactory.
105      */
106     @TestConfiguration
107     static class TestBeanFactory extends BeanFactory {
108
109         static final TestApplicationConfig applicationConfig = new TestApplicationConfig();
110         static KafkaTopicListener kafkaListener;
111         static InfluxStore influxStore;
112
113         @Override
114         @Bean
115         public ServletWebServerFactory servletContainer() {
116             return new TomcatServletWebServerFactory();
117         }
118
119         @Override
120         @Bean
121         public ApplicationConfig getApplicationConfig() {
122             return applicationConfig;
123         }
124
125         @Override
126         @Bean
127         public KafkaTopicListener getKafkaTopicListener(@Autowired ApplicationConfig appConfig) {
128             kafkaListener = new KafkaTopicListener(applicationConfig);
129             return kafkaListener;
130         }
131
132         @Override
133         @Bean
134         public InfluxStore getInfluxStore(@Autowired ApplicationConfig appConfig,
135                 @Autowired KafkaTopicListener listener) {
136             influxStore = spy(new InfluxStore(applicationConfig));
137             return influxStore;
138         }
139
140     }
141
142     @BeforeEach
143     public void init() {}
144
145     @AfterEach
146     void reset() {
147         this.icsSimulatorController.testResults.reset();
148     }
149
150     @Test
151     void generateApiDoc() throws FileNotFoundException {
152         String url = "/v3/api-docs";
153         ResponseEntity<String> resp = restClient().getForEntity(url).block();
154         assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
155
156         JSONObject jsonObj = new JSONObject(resp.getBody());
157         assertThat(jsonObj.remove("servers")).isNotNull();
158
159         String indented = jsonObj.toString(4);
160         try (PrintStream out = new PrintStream(new FileOutputStream("api/pmlog-api.json"))) {
161             out.print(indented);
162         }
163     }
164
165     @Test
166     void testPmReport() throws IOException {
167         String path = "./src/test/resources/pm_report.json";
168         String str = Files.readString(Path.of(path), Charset.defaultCharset());
169         DataFromKafkaTopic data = new DataFromKafkaTopic(null, null, str.getBytes());
170
171         Mockito.doNothing().when(TestBeanFactory.influxStore).store(any(), any());
172         TestBeanFactory.influxStore.start(Flux.just(data));
173
174         Mockito.verify(TestBeanFactory.influxStore, Mockito.times(1)).store(any(), any());
175     }
176
177     @Test
178     void testJobCreation() throws Exception {
179         await().untilAsserted(() -> assertThat(consumerRegstrationTask.isRegisteredInIcs()).isTrue());
180         ConsumerJobInfo createdJob = this.icsSimulatorController.testResults.createdJob;
181         assertThat(createdJob).isNotNull();
182         assertThat(createdJob.jobDefinition.getDeliveryInfo().getTopic())
183                 .isEqualTo(applicationConfig.getKafkaInputTopic());
184     }
185
186     private AsyncRestClient restClient() {
187         return restClient(false);
188     }
189
190     private String baseUrl() {
191         return "https://localhost:" + this.applicationConfig.getLocalServerHttpsPort();
192     }
193
194     private AsyncRestClient restClient(boolean useTrustValidation) {
195         WebClientConfig config = this.applicationConfig.getWebClientConfig();
196         HttpProxyConfig httpProxyConfig = HttpProxyConfig.builder() //
197                 .httpProxyHost("") //
198                 .httpProxyPort(0) //
199                 .build();
200         config = WebClientConfig.builder() //
201                 .keyStoreType(config.getKeyStoreType()) //
202                 .keyStorePassword(config.getKeyStorePassword()) //
203                 .keyStore(config.getKeyStore()) //
204                 .keyPassword(config.getKeyPassword()) //
205                 .isTrustStoreUsed(useTrustValidation) //
206                 .trustStore(config.getTrustStore()) //
207                 .trustStorePassword(config.getTrustStorePassword()) //
208                 .httpProxyConfig(httpProxyConfig).build();
209
210         AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config, securityContext);
211         return restClientFactory.createRestClientNoHttpProxy(baseUrl());
212     }
213
214 }