00d2c99377849036fd2dc139503371afce01b2ec
[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 ch.qos.logback.classic.Level.ERROR;
24 import static ch.qos.logback.classic.Level.WARN;
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.mockito.ArgumentMatchers.any;
27 import static org.mockito.Mockito.doNothing;
28 import static org.mockito.Mockito.doReturn;
29 import static org.mockito.Mockito.spy;
30 import static org.mockito.Mockito.times;
31 import static org.mockito.Mockito.verify;
32 import static org.mockito.Mockito.when;
33
34 import ch.qos.logback.classic.spi.ILoggingEvent;
35 import ch.qos.logback.core.read.ListAppender;
36
37 import com.google.common.base.Charsets;
38 import com.google.common.io.Resources;
39 import com.google.gson.JsonIOException;
40 import com.google.gson.JsonObject;
41 import com.google.gson.JsonParser;
42 import com.google.gson.JsonSyntaxException;
43
44 import java.io.ByteArrayInputStream;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.io.InputStreamReader;
48 import java.net.URL;
49 import java.nio.charset.StandardCharsets;
50 import java.time.Duration;
51 import java.util.Arrays;
52 import java.util.Collections;
53 import java.util.HashMap;
54 import java.util.Properties;
55 import java.util.Vector;
56
57 import org.junit.jupiter.api.Test;
58 import org.junit.jupiter.api.extension.ExtendWith;
59 import org.mockito.Mock;
60 import org.mockito.Spy;
61 import org.mockito.junit.jupiter.MockitoExtension;
62 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient;
63 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.EnvProperties;
64 import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.ImmutableEnvProperties;
65 import org.oransc.policyagent.clients.A1ClientFactory;
66 import org.oransc.policyagent.configuration.ApplicationConfig;
67 import org.oransc.policyagent.configuration.ApplicationConfig.RicConfigUpdate.Type;
68 import org.oransc.policyagent.configuration.ApplicationConfigParser;
69 import org.oransc.policyagent.configuration.ApplicationConfigParser.ConfigParserResult;
70 import org.oransc.policyagent.configuration.ImmutableConfigParserResult;
71 import org.oransc.policyagent.configuration.ImmutableRicConfig;
72 import org.oransc.policyagent.configuration.RicConfig;
73 import org.oransc.policyagent.repository.ImmutablePolicy;
74 import org.oransc.policyagent.repository.ImmutablePolicyType;
75 import org.oransc.policyagent.repository.Policies;
76 import org.oransc.policyagent.repository.Policy;
77 import org.oransc.policyagent.repository.PolicyTypes;
78 import org.oransc.policyagent.repository.Ric;
79 import org.oransc.policyagent.repository.Rics;
80 import org.oransc.policyagent.repository.Services;
81 import org.oransc.policyagent.utils.LoggingUtils;
82
83 import reactor.core.publisher.Flux;
84 import reactor.core.publisher.Mono;
85 import reactor.test.StepVerifier;
86
87 @ExtendWith(MockitoExtension.class)
88 public class RefreshConfigTaskTest {
89
90     private static final boolean CONFIG_FILE_EXISTS = true;
91     private static final boolean CONFIG_FILE_DOES_NOT_EXIST = false;
92
93     private RefreshConfigTask refreshTaskUnderTest;
94
95     @Spy
96     ApplicationConfig appConfig;
97
98     @Mock
99     CbsClient cbsClient;
100
101     private static final String RIC_1_NAME = "ric1";
102     public static final ImmutableRicConfig CORRECT_RIC_CONIFG = ImmutableRicConfig.builder() //
103         .name(RIC_1_NAME) //
104         .baseUrl("http://localhost:8080/") //
105         .managedElementIds(new Vector<String>(Arrays.asList("kista_1", "kista_2"))) //
106         .controllerName("") //
107         .build();
108
109     private static EnvProperties properties() {
110         return ImmutableEnvProperties.builder() //
111             .consulHost("host") //
112             .consulPort(123) //
113             .cbsName("cbsName") //
114             .appName("appName") //
115             .build();
116     }
117
118     private RefreshConfigTask createTestObject(boolean configFileExists) {
119         return createTestObject(configFileExists, new Rics(), new Policies(), true);
120     }
121
122     private RefreshConfigTask createTestObject(boolean configFileExists, Rics rics, Policies policies,
123         boolean stubConfigFileExists) {
124         RefreshConfigTask obj = spy(new RefreshConfigTask(appConfig, rics, policies, new Services(), new PolicyTypes(),
125             new A1ClientFactory(appConfig)));
126         if (stubConfigFileExists) {
127             doReturn(configFileExists).when(obj).configFileExists();
128         }
129         return obj;
130     }
131
132     @Test
133     public void startWithStubbedRefresh_thenTerminationLogged() {
134         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
135         doReturn(Flux.empty()).when(refreshTaskUnderTest).createRefreshTask();
136
137         final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
138
139         refreshTaskUnderTest.start();
140
141         assertThat(logAppender.list.toString().contains("Configuration refresh terminated")).isTrue();
142     }
143
144     @Test
145     public void startWithStubbedRefreshReturnError_thenErrorAndTerminationLogged() {
146         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
147         doReturn(Flux.error(new Exception("Error"))).when(refreshTaskUnderTest).createRefreshTask();
148
149         final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
150
151         refreshTaskUnderTest.start();
152
153         ILoggingEvent event = logAppender.list.get(0);
154         assertThat(event.getLevel()).isEqualTo(ERROR);
155         assertThat(event.toString().contains("Configuration refresh terminated due to exception")).isTrue();
156     }
157
158     @Test
159     public void stop_thenTaskIsDisposed() throws Exception {
160         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
161         refreshTaskUnderTest.systemEnvironment = new Properties();
162
163         refreshTaskUnderTest.start();
164         refreshTaskUnderTest.stop();
165
166         assertThat(refreshTaskUnderTest.getRefreshTask().isDisposed()).isTrue();
167     }
168
169     @Test
170     public void whenTheConfigurationFits_thenConfiguredRicsArePutInRepository() throws Exception {
171         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_EXISTS);
172         refreshTaskUnderTest.systemEnvironment = new Properties();
173         // When
174         doReturn(getCorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
175         doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
176
177         StepVerifier.create(refreshTaskUnderTest.createRefreshTask()) //
178             .expectSubscription() //
179             .expectNext(Type.ADDED) //
180             .expectNext(Type.ADDED) //
181             .thenCancel() //
182             .verify();
183
184         // Then
185         verify(refreshTaskUnderTest).loadConfigurationFromFile();
186
187         verify(refreshTaskUnderTest, times(2)).runRicSynchronization(any(Ric.class));
188
189         Iterable<RicConfig> ricConfigs = appConfig.getRicConfigs();
190         RicConfig ricConfig = ricConfigs.iterator().next();
191         assertThat(ricConfigs).isNotNull();
192         assertThat(ricConfig).isEqualTo(CORRECT_RIC_CONIFG);
193     }
194
195     @Test
196     public void whenFileExistsButJsonIsIncorrect_thenNoRicsArePutInRepository() throws Exception {
197         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_EXISTS);
198         refreshTaskUnderTest.systemEnvironment = new Properties();
199
200         // When
201         doReturn(getIncorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
202         doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
203
204         StepVerifier.create(refreshTaskUnderTest.createRefreshTask()) //
205             .expectSubscription() //
206             .expectNoEvent(Duration.ofMillis(100)) //
207             .thenCancel() //
208             .verify();
209
210         // Then
211         verify(refreshTaskUnderTest).loadConfigurationFromFile();
212         assertThat(appConfig.getRicConfigs().size()).isEqualTo(0);
213     }
214
215     @Test
216     public void whenPeriodicConfigRefreshNoConsul_thenErrorIsLogged() {
217         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST);
218         refreshTaskUnderTest.systemEnvironment = new Properties();
219
220         EnvProperties props = properties();
221         doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
222
223         doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
224         when(cbsClient.get(any())).thenReturn(Mono.error(new IOException()));
225
226         final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, WARN);
227         Flux<Type> task = refreshTaskUnderTest.createRefreshTask();
228
229         StepVerifier //
230             .create(task) //
231             .expectSubscription() //
232             .expectNoEvent(Duration.ofMillis(1000)) //
233             .thenCancel() //
234             .verify();
235
236         assertThat(
237             logAppender.list.toString().contains("Could not refresh application configuration. java.io.IOException"))
238                 .isTrue();
239     }
240
241     @Test
242     public void whenPeriodicConfigRefreshSuccess_thenNewConfigIsCreatedAndRepositoryUpdated() throws Exception {
243         Rics rics = new Rics();
244         Policies policies = new Policies();
245         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, rics, policies, false);
246         refreshTaskUnderTest.systemEnvironment = new Properties();
247
248         RicConfig changedRicConfig = getRicConfig(RIC_1_NAME);
249         rics.put(new Ric(changedRicConfig));
250         RicConfig removedRicConfig = getRicConfig("removed");
251         Ric removedRic = new Ric(removedRicConfig);
252         rics.put(removedRic);
253         appConfig.setConfiguration(configParserResult(changedRicConfig, removedRicConfig));
254
255         Policy policy = getPolicy(removedRic);
256         policies.put(policy);
257
258         EnvProperties props = properties();
259         doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
260         doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
261
262         JsonObject configAsJson = getJsonRootObject();
263         String newBaseUrl = "newBaseUrl";
264         modifyTheRicConfiguration(configAsJson, newBaseUrl);
265         when(cbsClient.get(any())).thenReturn(Mono.just(configAsJson));
266         doNothing().when(refreshTaskUnderTest).runRicSynchronization(any(Ric.class));
267
268         Flux<Type> task = refreshTaskUnderTest.createRefreshTask();
269
270         StepVerifier //
271             .create(task) //
272             .expectSubscription() //
273             .expectNext(Type.CHANGED) //
274             .expectNext(Type.ADDED) //
275             .expectNext(Type.REMOVED) //
276             .thenCancel() //
277             .verify();
278
279         assertThat(appConfig.getRicConfigs().size()).isEqualTo(2);
280         assertThat(appConfig.getRic(RIC_1_NAME).baseUrl()).isEqualTo(newBaseUrl);
281         String ric2Name = "ric2";
282         assertThat(appConfig.getRic(ric2Name)).isNotNull();
283
284         assertThat(rics.size()).isEqualTo(2);
285         assertThat(rics.get(RIC_1_NAME).getConfig().baseUrl()).isEqualTo(newBaseUrl);
286         assertThat(rics.get(ric2Name)).isNotNull();
287
288         assertThat(policies.size()).isEqualTo(0);
289     }
290
291     private RicConfig getRicConfig(String name) {
292         RicConfig ricConfig = ImmutableRicConfig.builder() //
293             .name(name) //
294             .baseUrl("url") //
295             .managedElementIds(Collections.emptyList()) //
296             .controllerName("controllerName") //
297             .build();
298         return ricConfig;
299     }
300
301     private Policy getPolicy(Ric ric) {
302         ImmutablePolicyType type = ImmutablePolicyType.builder() //
303             .name("type") //
304             .schema("{}") //
305             .build();
306         Policy policy = ImmutablePolicy.builder() //
307             .id("id") //
308             .type(type) //
309             .lastModified("lastModified") //
310             .ric(ric) //
311             .json("{}") //
312             .ownerServiceName("ownerServiceName") //
313             .build();
314         return policy;
315     }
316
317     ConfigParserResult configParserResult(RicConfig... rics) {
318         return ImmutableConfigParserResult.builder() //
319             .ricConfigs(Arrays.asList(rics)) //
320             .dmaapConsumerConfig(new Properties()) //
321             .dmaapPublisherConfig(new Properties()) //
322             .controllerConfigs(new HashMap<>()) //
323             .build();
324     }
325
326     private void modifyTheRicConfiguration(JsonObject configAsJson, String newBaseUrl) {
327         ((JsonObject) configAsJson.getAsJsonObject("config") //
328             .getAsJsonArray("ric").get(0)) //
329                 .addProperty("baseUrl", newBaseUrl);
330     }
331
332     private JsonObject getJsonRootObject() throws JsonIOException, JsonSyntaxException, IOException {
333         JsonObject rootObject = JsonParser.parseReader(new InputStreamReader(getCorrectJson())).getAsJsonObject();
334         return rootObject;
335     }
336
337     private static InputStream getCorrectJson() throws IOException {
338         URL url = ApplicationConfigParser.class.getClassLoader().getResource("test_application_configuration.json");
339         String string = Resources.toString(url, Charsets.UTF_8);
340         return new ByteArrayInputStream((string.getBytes(StandardCharsets.UTF_8)));
341     }
342
343     private static InputStream getIncorrectJson() {
344         String string = "{" + //
345             "    \"config\": {" + //
346             "        \"ric\": {"; //
347         return new ByteArrayInputStream((string.getBytes(StandardCharsets.UTF_8)));
348     }
349 }