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