d500ba3ed798610c7c505f75a29d8136fe1cfcc7
[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.ImmutableWebClientConfig;
40 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
41 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
42 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RefreshConfigTask;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.boot.test.context.SpringBootTest;
45 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
46 import org.springframework.boot.test.context.TestConfiguration;
47 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
48 import org.springframework.boot.web.server.LocalServerPort;
49 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
50 import org.springframework.context.ApplicationContext;
51 import org.springframework.context.annotation.Bean;
52 import org.springframework.http.HttpStatus;
53 import org.springframework.http.MediaType;
54 import org.springframework.test.context.TestPropertySource;
55 import org.springframework.test.context.junit.jupiter.SpringExtension;
56 import org.springframework.web.reactive.function.client.WebClientResponseException;
57
58 import reactor.core.publisher.Mono;
59 import reactor.test.StepVerifier;
60
61 @ExtendWith(SpringExtension.class)
62 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
63 @TestPropertySource(properties = { //
64         "server.ssl.key-store=./config/keystore.jks", //
65         "app.webclient.trust-store=./config/truststore.jks", //
66         "app.vardata-directory=./target", //
67         "app.config-file-schema-path=/application_configuration_schema.json" //
68 })
69 class ConfigurationControllerTest {
70     @Autowired
71     ApplicationContext context;
72
73     @Autowired
74     ApplicationConfig applicationConfig;
75
76     @Autowired
77     private Rics rics;
78
79     @TempDir
80     public static File temporaryFolder;
81     private static File configFile;
82
83     @BeforeAll
84     private static void setup() throws Exception {
85         Field f1 = RefreshConfigTask.class.getDeclaredField("configRefreshInterval");
86         f1.setAccessible(true);
87         f1.set(null, Duration.ofSeconds(1));
88     }
89
90     public static class MockApplicationConfig extends ApplicationConfig {
91         @Override
92         public String getLocalConfigurationFilePath() {
93             configFile = new File(temporaryFolder, "config.json");
94             return configFile.getAbsolutePath();
95         }
96     }
97
98     /**
99      * Overrides the BeanFactory.
100      */
101     @TestConfiguration
102     static class TestBeanFactory {
103         @Bean
104         public ApplicationConfig getApplicationConfig() {
105             return new MockApplicationConfig();
106         }
107
108         @Bean
109         public ServletWebServerFactory servletContainer() {
110             return new TomcatServletWebServerFactory();
111         }
112     }
113
114     @LocalServerPort
115     private int port;
116
117     @Test
118     void putValidConfigurationWithNewRic_shouldUpdateRepository() throws Exception {
119         String url = "a1-policy/v2/configuration";
120
121         String resp = restClient().put(url, configAsString()).block();
122
123         assertThat(resp).isEmpty();
124         await().until(rics::size, equalTo(2));
125
126         // GET config
127         resp = restClient().get(url).block();
128         assertThat(resp).contains("config");
129     }
130
131     @Test
132     void getNoFileExists() {
133         String url = "a1-policy/v2/configuration";
134         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND, "File does not exist");
135     }
136
137     private String configAsString() throws Exception {
138         File configFile = new File(getClass().getClassLoader()
139                 .getResource("test_application_configuration_with_dmaap_config.json").getFile());
140         return FileUtils.readFileToString(configFile, "UTF-8");
141     }
142
143     @Test
144     void putInvalidConfiguration_shouldReturnError400() throws Exception {
145         String url = "a1-policy/v2/configuration";
146
147         // Valid JSON but invalid configuration.
148         testErrorCode(restClient().put(url, "{\"error\":\"error\"}"), HttpStatus.BAD_REQUEST, "");
149     }
150
151     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
152         StepVerifier.create(request) //
153                 .expectSubscription() //
154                 .expectErrorMatches(t -> checkWebClientError(t, expStatus, responseContains)) //
155                 .verify();
156     }
157
158     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains) {
159         assertTrue(throwable instanceof WebClientResponseException);
160         WebClientResponseException responseException = (WebClientResponseException) throwable;
161         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
162         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
163         assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
164         return true;
165     }
166
167     private AsyncRestClient restClient() {
168         WebClientConfig config = this.applicationConfig.getWebClientConfig();
169         config = ImmutableWebClientConfig.builder() //
170                 .keyStoreType(config.keyStoreType()) //
171                 .keyStorePassword(config.keyStorePassword()) //
172                 .keyStore(config.keyStore()) //
173                 .keyPassword(config.keyPassword()) //
174                 .isTrustStoreUsed(false) //
175                 .trustStore(config.trustStore()) //
176                 .trustStorePassword(config.trustStorePassword()) //
177                 .httpProxyConfig(config.httpProxyConfig()) //
178                 .build();
179
180         AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
181         return f.createRestClientNoHttpProxy("https://localhost:" + port);
182
183     }
184 }