859708a571e2ef72abf121d2eb882959d6c5b1ca
[nonrtric.git] / policy-agent / src / test / java / org / oransc / policyagent / tasks / RefreshConfigTaskTest.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 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.oransc.policyagent.tasks;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.mockito.ArgumentMatchers.any;
25 import static org.mockito.Mockito.doReturn;
26 import static org.mockito.Mockito.spy;
27 import static org.mockito.Mockito.times;
28 import static org.mockito.Mockito.verify;
29
30 import ch.qos.logback.classic.Level;
31 import ch.qos.logback.classic.spi.ILoggingEvent;
32 import ch.qos.logback.core.read.ListAppender;
33 import com.google.common.base.Charsets;
34 import com.google.common.io.Resources;
35 import com.google.gson.JsonIOException;
36 import com.google.gson.JsonObject;
37 import com.google.gson.JsonParser;
38 import com.google.gson.JsonSyntaxException;
39 import java.io.ByteArrayInputStream;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.io.InputStreamReader;
43 import java.net.URL;
44 import java.nio.charset.StandardCharsets;
45 import java.util.Arrays;
46 import java.util.Properties;
47 import java.util.Vector;
48 import org.junit.jupiter.api.Test;
49 import org.junit.jupiter.api.extension.ExtendWith;
50 import org.mockito.Mock;
51 import org.mockito.Spy;
52 import org.mockito.junit.jupiter.MockitoExtension;
53 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient;
54 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.EnvProperties;
55 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.ImmutableEnvProperties;
56 import org.oransc.policyagent.configuration.ApplicationConfig;
57 import org.oransc.policyagent.configuration.ApplicationConfigParser;
58 import org.oransc.policyagent.configuration.ImmutableRicConfig;
59 import org.oransc.policyagent.configuration.RicConfig;
60 import org.oransc.policyagent.utils.LoggingUtils;
61 import reactor.core.publisher.Flux;
62 import reactor.core.publisher.Mono;
63 import reactor.test.StepVerifier;
64
65 @ExtendWith(MockitoExtension.class)
66 public class RefreshConfigTaskTest {
67
68
69     private RefreshConfigTask refreshTaskUnderTest;
70
71     @Spy
72     ApplicationConfig appConfig;
73
74     @Mock
75     CbsClient cbsClient;
76
77     private static final String RIC_1_NAME = "ric1";
78     public static final ImmutableRicConfig CORRECT_RIC_CONIFG = ImmutableRicConfig.builder() //
79         .name(RIC_1_NAME) //
80         .baseUrl("http://localhost:8080/") //
81         .managedElementIds(new Vector<String>(Arrays.asList("kista_1", "kista_2"))) //
82         .build();
83
84     private static EnvProperties properties() {
85         return ImmutableEnvProperties.builder() //
86             .consulHost("host") //
87             .consulPort(123) //
88             .cbsName("cbsName") //
89             .appName("appName") //
90             .build();
91     }
92
93     @Test
94     public void whenTheConfigurationFits_thenConfiguredRicsArePutInRepository() throws Exception {
95         refreshTaskUnderTest = spy(new RefreshConfigTask(appConfig));
96         refreshTaskUnderTest.systemEnvironment = new Properties();
97         // When
98         doReturn(getCorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
99         doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
100         refreshTaskUnderTest.start();
101
102         // Then
103         verify(refreshTaskUnderTest, times(1)).loadConfigurationFromFile();
104
105         Iterable<RicConfig> ricConfigs = appConfig.getRicConfigs();
106         RicConfig ricConfig = ricConfigs.iterator().next();
107         assertThat(ricConfigs).isNotNull();
108         assertThat(ricConfig).isEqualTo(CORRECT_RIC_CONIFG);
109     }
110
111     @Test
112     public void whenFileExistsButJsonIsIncorrect_thenNoRicsArePutInRepository() throws Exception {
113         refreshTaskUnderTest = spy(new RefreshConfigTask(appConfig));
114         refreshTaskUnderTest.systemEnvironment = new Properties();
115
116         // When
117         doReturn(getIncorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
118         doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
119         refreshTaskUnderTest.loadConfigurationFromFile();
120
121         // Then
122         verify(refreshTaskUnderTest, times(1)).loadConfigurationFromFile();
123         assertThat(appConfig.getRicConfigs().size()).isEqualTo(0);
124     }
125
126     @Test
127     public void whenPeriodicConfigRefreshNoEnvironmentVariables_thenErrorIsLogged() {
128         refreshTaskUnderTest = spy(new RefreshConfigTask(appConfig));
129         refreshTaskUnderTest.systemEnvironment = new Properties();
130
131         final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class);
132         Flux<ApplicationConfig> task = refreshTaskUnderTest.createRefreshTask();
133
134         StepVerifier.create(task).expectSubscription().verifyComplete();
135
136         assertThat(logAppender.list.get(0).getLevel()).isEqualTo(Level.ERROR);
137         assertThat(logAppender.list.toString().contains("$CONSUL_HOST environment has not been defined")).isTrue();
138     }
139
140     @Test
141     public void whenPeriodicConfigRefreshNoConsul_thenErrorIsLogged() {
142         refreshTaskUnderTest = spy(new RefreshConfigTask(appConfig));
143         refreshTaskUnderTest.systemEnvironment = new Properties();
144
145         EnvProperties props = properties();
146         doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
147
148         doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
149         Flux<JsonObject> err = Flux.error(new IOException());
150         doReturn(err).when(cbsClient).updates(any(), any(), any());
151
152         final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class);
153         Flux<ApplicationConfig> task = refreshTaskUnderTest.createRefreshTask();
154
155         StepVerifier //
156             .create(task) //
157             .expectSubscription() //
158             .verifyComplete();
159
160         assertThat(logAppender.list.get(0).getLevel()).isEqualTo(Level.ERROR);
161         assertThat(
162             logAppender.list.toString().contains("Could not refresh application configuration. java.io.IOException"))
163                 .isTrue();
164     }
165
166     @Test
167     public void whenPeriodicConfigRefreshSuccess_thenNewConfigIsCreated() throws Exception {
168         refreshTaskUnderTest = spy(new RefreshConfigTask(appConfig));
169         refreshTaskUnderTest.systemEnvironment = new Properties();
170
171         EnvProperties props = properties();
172         doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
173         doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
174
175         JsonObject configAsJson = getJsonRootObject();
176         String newBaseUrl = "newBaseUrl";
177         modifyTheRicConfiguration(configAsJson, newBaseUrl);
178         Flux<JsonObject> json = Flux.just(configAsJson);
179         doReturn(json).when(cbsClient).updates(any(), any(), any());
180
181         Flux<ApplicationConfig> task = refreshTaskUnderTest.createRefreshTask();
182
183         StepVerifier //
184             .create(task) //
185             .expectSubscription() //
186             .expectNext(appConfig) //
187             .verifyComplete();
188
189         assertThat(appConfig.getRicConfigs()).isNotNull();
190         assertThat(appConfig.getRic(RIC_1_NAME).baseUrl()).isEqualTo(newBaseUrl);
191     }
192
193     private void modifyTheRicConfiguration(JsonObject configAsJson, String newBaseUrl) {
194         ((JsonObject) configAsJson.getAsJsonObject("config").getAsJsonArray("ric").get(0)).addProperty("baseUrl",
195             newBaseUrl);
196     }
197
198     private JsonObject getJsonRootObject() throws JsonIOException, JsonSyntaxException, IOException {
199         JsonObject rootObject = JsonParser.parseReader(new InputStreamReader(getCorrectJson())).getAsJsonObject();
200         return rootObject;
201     }
202
203     private static InputStream getCorrectJson() throws IOException {
204         URL url = ApplicationConfigParser.class.getClassLoader().getResource("test_application_configuration.json");
205         String string = Resources.toString(url, Charsets.UTF_8);
206         return new ByteArrayInputStream((string.getBytes(StandardCharsets.UTF_8)));
207     }
208
209     private static InputStream getIncorrectJson() {
210         String string = "{" + //
211             "    \"config\": {" + //
212             "        \"ric\": {"; //
213         return new ByteArrayInputStream((string.getBytes(StandardCharsets.UTF_8)));
214     }
215 }