Merge "App config path changed"
[nonrtric.git] / policy-agent / src / test / java / org / oransc / policyagent / tasks / RefreshConfigTaskTest.java
index f81962d..2b1d2a7 100644 (file)
@@ -23,6 +23,7 @@ package org.oransc.policyagent.tasks;
 import static ch.qos.logback.classic.Level.ERROR;
 import static ch.qos.logback.classic.Level.WARN;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
@@ -50,6 +51,7 @@ import java.nio.charset.StandardCharsets;
 import java.time.Duration;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.Properties;
 import java.util.Vector;
 
@@ -65,6 +67,8 @@ import org.oransc.policyagent.clients.A1ClientFactory;
 import org.oransc.policyagent.configuration.ApplicationConfig;
 import org.oransc.policyagent.configuration.ApplicationConfig.RicConfigUpdate.Type;
 import org.oransc.policyagent.configuration.ApplicationConfigParser;
+import org.oransc.policyagent.configuration.ApplicationConfigParser.ConfigParserResult;
+import org.oransc.policyagent.configuration.ImmutableConfigParserResult;
 import org.oransc.policyagent.configuration.ImmutableRicConfig;
 import org.oransc.policyagent.configuration.RicConfig;
 import org.oransc.policyagent.repository.ImmutablePolicy;
@@ -82,7 +86,7 @@ import reactor.core.publisher.Mono;
 import reactor.test.StepVerifier;
 
 @ExtendWith(MockitoExtension.class)
-public class RefreshConfigTaskTest {
+class RefreshConfigTaskTest {
 
     private static final boolean CONFIG_FILE_EXISTS = true;
     private static final boolean CONFIG_FILE_DOES_NOT_EXIST = false;
@@ -96,10 +100,11 @@ public class RefreshConfigTaskTest {
     CbsClient cbsClient;
 
     private static final String RIC_1_NAME = "ric1";
-    public static final ImmutableRicConfig CORRECT_RIC_CONIFG = ImmutableRicConfig.builder() //
+    private static final ImmutableRicConfig CORRECT_RIC_CONIFG = ImmutableRicConfig.builder() //
         .name(RIC_1_NAME) //
         .baseUrl("http://localhost:8080/") //
         .managedElementIds(new Vector<String>(Arrays.asList("kista_1", "kista_2"))) //
+        .controllerName("") //
         .build();
 
     private static EnvProperties properties() {
@@ -120,13 +125,13 @@ public class RefreshConfigTaskTest {
         RefreshConfigTask obj = spy(new RefreshConfigTask(appConfig, rics, policies, new Services(), new PolicyTypes(),
             new A1ClientFactory(appConfig)));
         if (stubConfigFileExists) {
-            doReturn(configFileExists).when(obj).configFileExists();
+            doReturn(configFileExists).when(obj).fileExists(any());
         }
         return obj;
     }
 
     @Test
-    public void startWithStubbedRefresh_thenTerminationLogged() {
+    void startWithStubbedRefresh_thenTerminationLogged() {
         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
         doReturn(Flux.empty()).when(refreshTaskUnderTest).createRefreshTask();
 
@@ -134,43 +139,45 @@ public class RefreshConfigTaskTest {
 
         refreshTaskUnderTest.start();
 
-        assertThat(logAppender.list.toString().contains("Configuration refresh terminated")).isTrue();
+        assertThat(logAppender.list.get(0).getFormattedMessage()).isEqualTo("Configuration refresh terminated");
     }
 
     @Test
-    public void startWithStubbedRefreshReturnError_thenErrorAndTerminationLogged() {
+    void startWithStubbedRefreshReturnError_thenErrorAndTerminationLogged() {
         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
-        doReturn(Flux.error(new Exception("Error"))).when(refreshTaskUnderTest).createRefreshTask();
+        String errorMessage = "Error";
+        doReturn(Flux.error(new Exception(errorMessage))).when(refreshTaskUnderTest).createRefreshTask();
 
         final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
 
         refreshTaskUnderTest.start();
 
         ILoggingEvent event = logAppender.list.get(0);
-        assertThat(event.getThrowableProxy().getMessage()).isEqualTo("Error");
-        assertThat(event.toString().contains("Configuration refresh terminated due to exception")).isTrue();
+        assertThat(event.getFormattedMessage())
+            .isEqualTo("Configuration refresh terminated due to exception java.lang.Exception: " + errorMessage);
     }
 
     @Test
-    public void stop_thenTaskIsDisposed() throws Exception {
+    void stop_thenTaskIsDisposed() throws Exception {
         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, null, null, false);
         refreshTaskUnderTest.systemEnvironment = new Properties();
 
         refreshTaskUnderTest.start();
         refreshTaskUnderTest.stop();
 
-        assertThat(refreshTaskUnderTest.getRefreshTask().isDisposed()).isTrue();
+        assertThat(refreshTaskUnderTest.getRefreshTask().isDisposed()).as("Refresh task is disposed").isTrue();
     }
 
     @Test
-    public void whenTheConfigurationFits_thenConfiguredRicsArePutInRepository() throws Exception {
+    void whenTheConfigurationFits_thenConfiguredRicsArePutInRepository() throws Exception {
         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_EXISTS);
         refreshTaskUnderTest.systemEnvironment = new Properties();
         // When
         doReturn(getCorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
         doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
 
-        StepVerifier.create(refreshTaskUnderTest.createRefreshTask()) //
+        StepVerifier //
+            .create(refreshTaskUnderTest.createRefreshTask()) //
             .expectSubscription() //
             .expectNext(Type.ADDED) //
             .expectNext(Type.ADDED) //
@@ -189,7 +196,7 @@ public class RefreshConfigTaskTest {
     }
 
     @Test
-    public void whenFileExistsButJsonIsIncorrect_thenNoRicsArePutInRepository() throws Exception {
+    void whenFileExistsButJsonIsIncorrect_thenNoRicsArePutInRepositoryAndErrorIsLogged() throws Exception {
         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_EXISTS);
         refreshTaskUnderTest.systemEnvironment = new Properties();
 
@@ -197,7 +204,10 @@ public class RefreshConfigTaskTest {
         doReturn(getIncorrectJson()).when(refreshTaskUnderTest).createInputStream(any());
         doReturn("fileName").when(appConfig).getLocalConfigurationFilePath();
 
-        StepVerifier.create(refreshTaskUnderTest.createRefreshTask()) //
+        final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
+
+        StepVerifier //
+            .create(refreshTaskUnderTest.createRefreshTask()) //
             .expectSubscription() //
             .expectNoEvent(Duration.ofMillis(100)) //
             .thenCancel() //
@@ -206,10 +216,14 @@ public class RefreshConfigTaskTest {
         // Then
         verify(refreshTaskUnderTest).loadConfigurationFromFile();
         assertThat(appConfig.getRicConfigs().size()).isEqualTo(0);
+
+        await().until(() -> logAppender.list.size() > 0);
+        assertThat(logAppender.list.get(0).getFormattedMessage())
+            .startsWith("Local configuration file not loaded: fileName, ");
     }
 
     @Test
-    public void whenPeriodicConfigRefreshNoConsul_thenErrorIsLogged() {
+    void whenPeriodicConfigRefreshNoConsul_thenErrorIsLogged() {
         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST);
         refreshTaskUnderTest.systemEnvironment = new Properties();
 
@@ -217,25 +231,24 @@ public class RefreshConfigTaskTest {
         doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
 
         doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
-        when(cbsClient.updates(any(), any(), any())).thenReturn(Flux.error(new IOException()));
+        when(cbsClient.get(any())).thenReturn(Mono.error(new IOException()));
 
         final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, WARN);
-        Flux<Type> task = refreshTaskUnderTest.createRefreshTask();
 
         StepVerifier //
-            .create(task) //
+            .create(refreshTaskUnderTest.createRefreshTask()) //
             .expectSubscription() //
-            .expectNoEvent(Duration.ofMillis(100)) //
+            .expectNoEvent(Duration.ofMillis(1000)) //
             .thenCancel() //
             .verify();
 
-        assertThat(
-            logAppender.list.toString().contains("Could not refresh application configuration. java.io.IOException"))
-                .isTrue();
+        await().until(() -> logAppender.list.size() > 0);
+        assertThat(logAppender.list.get(0).getFormattedMessage())
+            .isEqualTo("Could not refresh application configuration. java.io.IOException");
     }
 
     @Test
-    public void whenPeriodicConfigRefreshSuccess_thenNewConfigIsCreatedAndRepositoryUpdated() throws Exception {
+    void whenPeriodicConfigRefreshSuccess_thenNewConfigIsCreatedAndRepositoryUpdated() throws Exception {
         Rics rics = new Rics();
         Policies policies = new Policies();
         refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, rics, policies, false);
@@ -246,7 +259,7 @@ public class RefreshConfigTaskTest {
         RicConfig removedRicConfig = getRicConfig("removed");
         Ric removedRic = new Ric(removedRicConfig);
         rics.put(removedRic);
-        appConfig.setConfiguration(Arrays.asList(changedRicConfig, removedRicConfig), null, null);
+        appConfig.setConfiguration(configParserResult(changedRicConfig, removedRicConfig));
 
         Policy policy = getPolicy(removedRic);
         policies.put(policy);
@@ -255,16 +268,14 @@ public class RefreshConfigTaskTest {
         doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
         doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
 
-        JsonObject configAsJson = getJsonRootObject();
+        JsonObject configAsJson = getJsonRootObject(true);
         String newBaseUrl = "newBaseUrl";
         modifyTheRicConfiguration(configAsJson, newBaseUrl);
-        when(cbsClient.updates(any(), any(), any())).thenReturn(Flux.just(configAsJson));
+        when(cbsClient.get(any())).thenReturn(Mono.just(configAsJson));
         doNothing().when(refreshTaskUnderTest).runRicSynchronization(any(Ric.class));
 
-        Flux<Type> task = refreshTaskUnderTest.createRefreshTask();
-
         StepVerifier //
-            .create(task) //
+            .create(refreshTaskUnderTest.createRefreshTask()) //
             .expectSubscription() //
             .expectNext(Type.CHANGED) //
             .expectNext(Type.ADDED) //
@@ -284,11 +295,42 @@ public class RefreshConfigTaskTest {
         assertThat(policies.size()).isEqualTo(0);
     }
 
+    @Test
+    void whenPeriodicConfigRefreshInvalidJson_thenErrorIsLogged() throws Exception {
+        Rics rics = new Rics();
+        Policies policies = new Policies();
+        refreshTaskUnderTest = this.createTestObject(CONFIG_FILE_DOES_NOT_EXIST, rics, policies, false);
+        refreshTaskUnderTest.systemEnvironment = new Properties();
+
+        appConfig.setConfiguration(configParserResult());
+
+        EnvProperties props = properties();
+        doReturn(Mono.just(props)).when(refreshTaskUnderTest).getEnvironment(any());
+        doReturn(Mono.just(cbsClient)).when(refreshTaskUnderTest).createCbsClient(props);
+
+        JsonObject configAsJson = getJsonRootObject(false);
+        when(cbsClient.get(any())).thenReturn(Mono.just(configAsJson));
+
+        final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RefreshConfigTask.class, ERROR);
+
+        StepVerifier //
+            .create(refreshTaskUnderTest.createRefreshTask()) //
+            .expectSubscription() //
+            .expectNoEvent(Duration.ofMillis(1000)) //
+            .thenCancel() //
+            .verify();
+
+        await().until(() -> logAppender.list.size() > 0);
+        assertThat(logAppender.list.get(0).getFormattedMessage())
+            .startsWith("Could not parse configuration org.oransc.policyagent.exceptions.ServiceException: ");
+    }
+
     private RicConfig getRicConfig(String name) {
         RicConfig ricConfig = ImmutableRicConfig.builder() //
             .name(name) //
             .baseUrl("url") //
             .managedElementIds(Collections.emptyList()) //
+            .controllerName("controllerName") //
             .build();
         return ricConfig;
     }
@@ -305,17 +347,29 @@ public class RefreshConfigTaskTest {
             .ric(ric) //
             .json("{}") //
             .ownerServiceName("ownerServiceName") //
+            .isTransient(false) //
             .build();
         return policy;
     }
 
+    ConfigParserResult configParserResult(RicConfig... rics) {
+        return ImmutableConfigParserResult.builder() //
+            .ricConfigs(Arrays.asList(rics)) //
+            .dmaapConsumerConfig(new Properties()) //
+            .dmaapPublisherConfig(new Properties()) //
+            .controllerConfigs(new HashMap<>()) //
+            .build();
+    }
+
     private void modifyTheRicConfiguration(JsonObject configAsJson, String newBaseUrl) {
-        ((JsonObject) configAsJson.getAsJsonObject("config").getAsJsonArray("ric").get(0)).addProperty("baseUrl",
-            newBaseUrl);
+        ((JsonObject) configAsJson.getAsJsonObject("config") //
+            .getAsJsonArray("ric").get(0)) //
+                .addProperty("baseUrl", newBaseUrl);
     }
 
-    private JsonObject getJsonRootObject() throws JsonIOException, JsonSyntaxException, IOException {
-        JsonObject rootObject = JsonParser.parseReader(new InputStreamReader(getCorrectJson())).getAsJsonObject();
+    private JsonObject getJsonRootObject(boolean valid) throws JsonIOException, JsonSyntaxException, IOException {
+        JsonObject rootObject = JsonParser
+            .parseReader(new InputStreamReader(valid ? getCorrectJson() : getIncorrectJson())).getAsJsonObject();
         return rootObject;
     }
 
@@ -326,9 +380,7 @@ public class RefreshConfigTaskTest {
     }
 
     private static InputStream getIncorrectJson() {
-        String string = "{" + //
-            "    \"config\": {" + //
-            "        \"ric\": {"; //
+        String string = "{}"; //
         return new ByteArrayInputStream((string.getBytes(StandardCharsets.UTF_8)));
     }
 }