f876a13c3d6316ea814c5c10b446c90e74f621a9
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * Copyright (C) 2020 Nordix Foundation. All rights reserved.
4  * ======================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ========================LICENSE_END===================================
17  */
18
19 package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2;
20
21 import static org.assertj.core.api.Assertions.assertThat;
22 import static org.awaitility.Awaitility.await;
23 import static org.hamcrest.CoreMatchers.equalTo;
24 import static org.junit.jupiter.api.Assertions.assertTrue;
25
26 import java.io.File;
27 import java.lang.reflect.Field;
28 import java.time.Duration;
29
30 import org.apache.commons.io.FileUtils;
31 import org.junit.jupiter.api.BeforeAll;
32 import org.junit.jupiter.api.Test;
33 import org.junit.jupiter.api.extension.ExtendWith;
34 import org.junit.jupiter.api.io.TempDir;
35 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
36 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
37 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SecurityContext;
38 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
39 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
40 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
41 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RefreshConfigTask;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.boot.test.context.SpringBootTest;
44 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
45 import org.springframework.boot.test.context.TestConfiguration;
46 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
47 import org.springframework.boot.web.server.LocalServerPort;
48 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
49 import org.springframework.context.ApplicationContext;
50 import org.springframework.context.annotation.Bean;
51 import org.springframework.http.HttpStatus;
52 import org.springframework.http.MediaType;
53 import org.springframework.test.context.TestPropertySource;
54 import org.springframework.test.context.junit.jupiter.SpringExtension;
55 import org.springframework.web.reactive.function.client.WebClientResponseException;
56
57 import reactor.core.publisher.Mono;
58 import reactor.test.StepVerifier;
59
60 @ExtendWith(SpringExtension.class)
61 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
62 @TestPropertySource(properties = { //
63         "server.ssl.key-store=./config/keystore.jks", //
64         "app.webclient.trust-store=./config/truststore.jks", //
65         "app.vardata-directory=./target", //
66         "app.config-file-schema-path=/application_configuration_schema.json" //
67 })
68 class ConfigurationControllerTest {
69     @Autowired
70     ApplicationContext context;
71
72     @Autowired
73     ApplicationConfig applicationConfig;
74
75     @Autowired
76     private Rics rics;
77
78     @TempDir
79     public static File temporaryFolder;
80     private static File configFile;
81
82     @BeforeAll
83     private static void setup() throws Exception {
84         Field f1 = RefreshConfigTask.class.getDeclaredField("configRefreshInterval");
85         f1.setAccessible(true);
86         f1.set(null, Duration.ofSeconds(1));
87     }
88
89     public static class MockApplicationConfig extends ApplicationConfig {
90         @Override
91         public String getLocalConfigurationFilePath() {
92             configFile = new File(temporaryFolder, "config.json");
93             return configFile.getAbsolutePath();
94         }
95     }
96
97     /**
98      * Overrides the BeanFactory.
99      */
100     @TestConfiguration
101     static class TestBeanFactory {
102         @Bean
103         public ApplicationConfig getApplicationConfig() {
104             return new MockApplicationConfig();
105         }
106
107         @Bean
108         public ServletWebServerFactory servletContainer() {
109             return new TomcatServletWebServerFactory();
110         }
111     }
112
113     @LocalServerPort
114     private int port;
115
116     @Test
117     void putValidConfigurationWithNewRic_shouldUpdateRepository() throws Exception {
118         String url = "a1-policy/v2/configuration";
119
120         String resp = restClient().put(url, configAsString()).block();
121
122         assertThat(resp).isEmpty();
123         await().until(rics::size, equalTo(2));
124
125         // GET config
126         resp = restClient().get(url).block();
127         assertThat(resp).contains("config");
128     }
129
130     @Test
131     void getNoFileExists() {
132         String url = "a1-policy/v2/configuration";
133         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND, "File does not exist");
134     }
135
136     private String configAsString() throws Exception {
137         File configFile = new File(getClass().getClassLoader()
138                 .getResource("test_application_configuration_with_dmaap_config.json").getFile());
139         return FileUtils.readFileToString(configFile, "UTF-8");
140     }
141
142     @Test
143     void putInvalidConfiguration_shouldReturnError400() throws Exception {
144         String url = "a1-policy/v2/configuration";
145
146         // Valid JSON but invalid configuration.
147         testErrorCode(restClient().put(url, "{\"error\":\"error\"}"), HttpStatus.BAD_REQUEST, "");
148     }
149
150     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
151         StepVerifier.create(request) //
152                 .expectSubscription() //
153                 .expectErrorMatches(t -> checkWebClientError(t, expStatus, responseContains)) //
154                 .verify();
155     }
156
157     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains) {
158         assertTrue(throwable instanceof WebClientResponseException);
159         WebClientResponseException responseException = (WebClientResponseException) throwable;
160         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
161         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
162         assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
163         return true;
164     }
165
166     private AsyncRestClient restClient() {
167         WebClientConfig config = this.applicationConfig.getWebClientConfig();
168         config = WebClientConfig.builder() //
169                 .keyStoreType(config.getKeyStoreType()) //
170                 .keyStorePassword(config.getKeyStorePassword()) //
171                 .keyStore(config.getKeyStore()) //
172                 .keyPassword(config.getKeyPassword()) //
173                 .isTrustStoreUsed(false) //
174                 .trustStore(config.getTrustStore()) //
175                 .trustStorePassword(config.getTrustStorePassword()) //
176                 .httpProxyConfig(config.getHttpProxyConfig()) //
177                 .build();
178
179         AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
180         return f.createRestClientNoHttpProxy("https://localhost:" + port);
181
182     }
183 }