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