2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.oransc.policyagent.tasks;
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;
34 import ch.qos.logback.classic.spi.ILoggingEvent;
35 import ch.qos.logback.core.read.ListAppender;
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;
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;
84 @ExtendWith(MockitoExtension.class)
85 public class RefreshConfigTaskTest {
87 private static final boolean CONFIG_FILE_EXISTS = true;
88 private static final boolean CONFIG_FILE_DOES_NOT_EXIST = false;
90 private RefreshConfigTask refreshTaskUnderTest;
93 ApplicationConfig appConfig;
98 private static final String RIC_1_NAME = "ric1";
99 public static final ImmutableRicConfig CORRECT_RIC_CONIFG = ImmutableRicConfig.builder() //
101 .baseUrl("http://localhost:8080/") //
102 .managedElementIds(new Vector<String>(Arrays.asList("kista_1", "kista_2"))) //
103 .controllerName("") //
106 private static EnvProperties properties() {
107 return ImmutableEnvProperties.builder() //
108 .consulHost("host") //
110 .cbsName("cbsName") //
111 .appName("appName") //
115 private RefreshConfigTask createTestObject(boolean configFileExists) {
116 return createTestObject(configFileExists, new Rics(), new Policies(), true);
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();
130 public void startWithStubbedRefresh_thenTerminationLogged() {
131 refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
132 doReturn(Flux.empty()).when(refreshTaskUnderTest).createRefreshTask();
134 final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
136 refreshTaskUnderTest.start();
138 assertThat(logAppender.list.toString().contains("Configuration refresh terminated")).isTrue();
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();
146 final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
148 refreshTaskUnderTest.start();
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();
156 public void stop_thenTaskIsDisposed() throws Exception {
157 refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
158 refreshTaskUnderTest.systemEnvironment = new Properties();
160 refreshTaskUnderTest.start();
161 refreshTaskUnderTest.stop();
163 assertThat(refreshTaskUnderTest.getRefreshTask().isDisposed()).isTrue();
167 public void whenTheConfigurationFits_thenConfiguredRicsArePutInRepository() throws Exception {
168 refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_EXISTS);
169 refreshTaskUnderTest.systemEnvironment = new Properties();
171 doReturn(getCorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
172 doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
174 StepVerifier.create(refreshTaskUnderTest.createRefreshTask()) //
175 .expectSubscription() //
176 .expectNext(Type.ADDED) //
177 .expectNext(Type.ADDED) //
182 verify(refreshTaskUnderTest).loadConfigurationFromFile();
184 verify(refreshTaskUnderTest, times(2)).runRicSynchronization(any(Ric.class));
186 Iterable<RicConfig> ricConfigs = appConfig.getRicConfigs();
187 RicConfig ricConfig = ricConfigs.iterator().next();
188 assertThat(ricConfigs).isNotNull();
189 assertThat(ricConfig).isEqualTo(CORRECT_RIC_CONIFG);
193 public void whenFileExistsButJsonIsIncorrect_thenNoRicsArePutInRepository() throws Exception {
194 refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_EXISTS);
195 refreshTaskUnderTest.systemEnvironment = new Properties();
198 doReturn(getIncorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
199 doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
201 StepVerifier.create(refreshTaskUnderTest.createRefreshTask()) //
202 .expectSubscription() //
203 .expectNoEvent(Duration.ofMillis(100)) //
208 verify(refreshTaskUnderTest).loadConfigurationFromFile();
209 assertThat(appConfig.getRicConfigs().size()).isEqualTo(0);
213 public void whenPeriodicConfigRefreshNoConsul_thenErrorIsLogged() {
214 refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST);
215 refreshTaskUnderTest.systemEnvironment = new Properties();
217 EnvProperties props = properties();
218 doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
220 doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
221 when(cbsClient.updates(any(), any(), any())).thenReturn(Flux.error(new IOException()));
223 final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, WARN);
224 Flux<Type> task = refreshTaskUnderTest.createRefreshTask();
228 .expectSubscription() //
229 .expectNoEvent(Duration.ofMillis(100)) //
234 logAppender.list.toString().contains("Could not refresh application configuration. java.io.IOException"))
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();
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));
252 Policy policy = getPolicy(removedRic);
253 policies.put(policy);
255 EnvProperties props = properties();
256 doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
257 doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
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));
265 Flux<Type> task = refreshTaskUnderTest.createRefreshTask();
269 .expectSubscription() //
270 .expectNext(Type.CHANGED) //
271 .expectNext(Type.ADDED) //
272 .expectNext(Type.REMOVED) //
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();
281 assertThat(rics.size()).isEqualTo(2);
282 assertThat(rics.get(RIC_1_NAME).getConfig().baseUrl()).isEqualTo(newBaseUrl);
283 assertThat(rics.get(ric2Name)).isNotNull();
285 assertThat(policies.size()).isEqualTo(0);
288 private RicConfig getRicConfig(String name) {
289 RicConfig ricConfig = ImmutableRicConfig.builder() //
292 .managedElementIds(Collections.emptyList()) //
293 .controllerName("controllerName") //
298 private Policy getPolicy(Ric ric) {
299 ImmutablePolicyType type = ImmutablePolicyType.builder() //
303 Policy policy = ImmutablePolicy.builder() //
306 .lastModified("lastModified") //
309 .ownerServiceName("ownerServiceName") //
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<>()) //
323 private void modifyTheRicConfiguration(JsonObject configAsJson, String newBaseUrl) {
324 ((JsonObject) configAsJson.getAsJsonObject("config") //
325 .getAsJsonArray("ric").get(0)) //
326 .addProperty("baseUrl", newBaseUrl);
329 private JsonObject getJsonRootObject() throws JsonIOException, JsonSyntaxException, IOException {
330 JsonObject rootObject = JsonParser.parseReader(new InputStreamReader(getCorrectJson())).getAsJsonObject();
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)));
340 private static InputStream getIncorrectJson() {
341 String string = "{" + //
342 " \"config\": {" + //
344 return new ByteArrayInputStream((string.getBytes(StandardCharsets.UTF_8)));