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