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;
44 import java.io.ByteArrayInputStream;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.io.InputStreamReader;
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;
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;
83 import reactor.core.publisher.Flux;
84 import reactor.core.publisher.Mono;
85 import reactor.test.StepVerifier;
87 @ExtendWith(MockitoExtension.class)
88 public class RefreshConfigTaskTest {
90 private static final boolean CONFIG_FILE_EXISTS = true;
91 private static final boolean CONFIG_FILE_DOES_NOT_EXIST = false;
93 private RefreshConfigTask refreshTaskUnderTest;
96 ApplicationConfig appConfig;
101 private static final String RIC_1_NAME = "ric1";
102 public static final ImmutableRicConfig CORRECT_RIC_CONIFG = ImmutableRicConfig.builder() //
104 .baseUrl("http://localhost:8080/") //
105 .managedElementIds(new Vector<String>(Arrays.asList("kista_1", "kista_2"))) //
106 .controllerName("") //
109 private static EnvProperties properties() {
110 return ImmutableEnvProperties.builder() //
111 .consulHost("host") //
113 .cbsName("cbsName") //
114 .appName("appName") //
118 private RefreshConfigTask createTestObject(boolean configFileExists) {
119 return createTestObject(configFileExists, new Rics(), new Policies(), true);
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();
133 public void startWithStubbedRefresh_thenTerminationLogged() {
134 refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
135 doReturn(Flux.empty()).when(refreshTaskUnderTest).createRefreshTask();
137 final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
139 refreshTaskUnderTest.start();
141 assertThat(logAppender.list.toString().contains("Configuration refresh terminated")).isTrue();
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();
149 final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
151 refreshTaskUnderTest.start();
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();
159 public void stop_thenTaskIsDisposed() throws Exception {
160 refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
161 refreshTaskUnderTest.systemEnvironment = new Properties();
163 refreshTaskUnderTest.start();
164 refreshTaskUnderTest.stop();
166 assertThat(refreshTaskUnderTest.getRefreshTask().isDisposed()).isTrue();
170 public void whenTheConfigurationFits_thenConfiguredRicsArePutInRepository() throws Exception {
171 refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_EXISTS);
172 refreshTaskUnderTest.systemEnvironment = new Properties();
174 doReturn(getCorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
175 doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
177 StepVerifier.create(refreshTaskUnderTest.createRefreshTask()) //
178 .expectSubscription() //
179 .expectNext(Type.ADDED) //
180 .expectNext(Type.ADDED) //
185 verify(refreshTaskUnderTest).loadConfigurationFromFile();
187 verify(refreshTaskUnderTest, times(2)).runRicSynchronization(any(Ric.class));
189 Iterable<RicConfig> ricConfigs = appConfig.getRicConfigs();
190 RicConfig ricConfig = ricConfigs.iterator().next();
191 assertThat(ricConfigs).isNotNull();
192 assertThat(ricConfig).isEqualTo(CORRECT_RIC_CONIFG);
196 public void whenFileExistsButJsonIsIncorrect_thenNoRicsArePutInRepository() throws Exception {
197 refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_EXISTS);
198 refreshTaskUnderTest.systemEnvironment = new Properties();
201 doReturn(getIncorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
202 doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
204 StepVerifier.create(refreshTaskUnderTest.createRefreshTask()) //
205 .expectSubscription() //
206 .expectNoEvent(Duration.ofMillis(100)) //
211 verify(refreshTaskUnderTest).loadConfigurationFromFile();
212 assertThat(appConfig.getRicConfigs().size()).isEqualTo(0);
216 public void whenPeriodicConfigRefreshNoConsul_thenErrorIsLogged() {
217 refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST);
218 refreshTaskUnderTest.systemEnvironment = new Properties();
220 EnvProperties props = properties();
221 doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
223 doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
224 when(cbsClient.get(any())).thenReturn(Mono.error(new IOException()));
226 final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, WARN);
227 Flux<Type> task = refreshTaskUnderTest.createRefreshTask();
231 .expectSubscription() //
232 .expectNoEvent(Duration.ofMillis(1000)) //
237 logAppender.list.toString().contains("Could not refresh application configuration. java.io.IOException"))
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();
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));
255 Policy policy = getPolicy(removedRic);
256 policies.put(policy);
258 EnvProperties props = properties();
259 doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
260 doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
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));
268 Flux<Type> task = refreshTaskUnderTest.createRefreshTask();
272 .expectSubscription() //
273 .expectNext(Type.CHANGED) //
274 .expectNext(Type.ADDED) //
275 .expectNext(Type.REMOVED) //
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();
284 assertThat(rics.size()).isEqualTo(2);
285 assertThat(rics.get(RIC_1_NAME).getConfig().baseUrl()).isEqualTo(newBaseUrl);
286 assertThat(rics.get(ric2Name)).isNotNull();
288 assertThat(policies.size()).isEqualTo(0);
291 private RicConfig getRicConfig(String name) {
292 RicConfig ricConfig = ImmutableRicConfig.builder() //
295 .managedElementIds(Collections.emptyList()) //
296 .controllerName("controllerName") //
301 private Policy getPolicy(Ric ric) {
302 ImmutablePolicyType type = ImmutablePolicyType.builder() //
306 Policy policy = ImmutablePolicy.builder() //
309 .lastModified("lastModified") //
312 .ownerServiceName("ownerServiceName") //
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<>()) //
326 private void modifyTheRicConfiguration(JsonObject configAsJson, String newBaseUrl) {
327 ((JsonObject) configAsJson.getAsJsonObject("config") //
328 .getAsJsonArray("ric").get(0)) //
329 .addProperty("baseUrl", newBaseUrl);
332 private JsonObject getJsonRootObject() throws JsonIOException, JsonSyntaxException, IOException {
333 JsonObject rootObject = JsonParser.parseReader(new InputStreamReader(getCorrectJson())).getAsJsonObject();
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)));
343 private static InputStream getIncorrectJson() {
344 String string = "{" + //
345 " \"config\": {" + //
347 return new ByteArrayInputStream((string.getBytes(StandardCharsets.UTF_8)));