Improve tests/issues found in Sonar report - A1 Oslo/NewDelhi/Montreal/London- Part5 48/138848/3
authorraviteja.karumuri <raviteja.karumuri@est.tech>
Thu, 22 Aug 2024 18:46:05 +0000 (19:46 +0100)
committerRAVITEJA KARUMURI <raviteja.karumuri@est.tech>
Wed, 28 Aug 2024 14:47:01 +0000 (14:47 +0000)
Issue-ID: CCSDK-4037
Change-Id: I0d6194ea6453bdd2ed62bfb0209d3ee31f8feff5
Signed-off-by: Raviteja Karumuri <raviteja.karumuri@est.tech>
12 files changed:
a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactory.java
a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/authorization/AuthorizationResult.java
a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/authorization/PolicyAuthorizationRequest.java
a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/PolicyController.java
a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactoryTest.java
a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ApplicationTest.java
a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ConcurrencyTestRunnable.java
a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ConfigurationControllerTest.java
a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/LockTest.java
a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RefreshConfigTaskTest.java
a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/utils/MockA1Client.java
a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/utils/MockA1ClientFactory.java

index 9877ce5..7795759 100644 (file)
 
 package org.onap.ccsdk.oran.a1policymanagementservice.clients;
 
-import java.lang.invoke.MethodHandles;
-import java.lang.reflect.Constructor;
-
 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1Client.A1ProtocolType;
 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
-import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ControllerConfig;
 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
@@ -34,6 +30,9 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import reactor.core.publisher.Mono;
 
+import java.lang.invoke.MethodHandles;
+import java.lang.reflect.Constructor;
+
 
 /**
  * Factory for A1 clients that supports four different protocol versions of the
@@ -92,15 +91,6 @@ public class A1ClientFactory {
         }
     }
 
-    private ControllerConfig getControllerConfig(Ric ric) throws ServiceException {
-        ControllerConfig controllerConfig = ric.getConfig().getControllerConfig();
-        if (controllerConfig == null) {
-            ric.setProtocolVersion(A1ProtocolType.UNKNOWN);
-            throw new ServiceException("No controller configured for Near-RT RIC: " + ric.id());
-        }
-        return controllerConfig;
-    }
-
     private A1Client createCustomAdapter(Ric ric) throws ServiceException {
         try {
             Class<?> clazz = Class.forName(ric.getConfig().getCustomAdapterClass());
index 796c44e..dc717d3 100644 (file)
@@ -32,7 +32,7 @@ import lombok.Getter;
 @Builder
 public class AuthorizationResult {
 
-    @Schema(name = "result", description = "If true, the access is granted", required = true)
+    @Schema(name = "result", description = "If true, the access is granted", requiredMode = Schema.RequiredMode.REQUIRED)
     @JsonProperty(value = "result", required = true)
     @SerializedName("result")
     @Getter
index 8dd4e7b..cb93006 100644 (file)
@@ -51,25 +51,25 @@ public class PolicyAuthorizationRequest {
             READ, WRITE, DELETE
         }
 
-        @Schema(name = "access_type", description = "Access type", required = true)
+        @Schema(name = "access_type", description = "Access type", requiredMode = Schema.RequiredMode.REQUIRED)
         @JsonProperty(value = "access_type", required = true)
         @SerializedName("access_type")
         @Getter
         private AccessType accessType;
 
-        @Schema(name = "policy_type_id", description = "Policy type identifier", required = true)
+        @Schema(name = "policy_type_id", description = "Policy type identifier", requiredMode = Schema.RequiredMode.REQUIRED)
         @SerializedName("policy_type_id")
         @JsonProperty(value = "policy_type_id", required = true)
         private String policyTypeId;
 
-        @Schema(name = "auth_token", description = "Authorization token", required = true)
+        @Schema(name = "auth_token", description = "Authorization token", requiredMode = Schema.RequiredMode.REQUIRED)
         @SerializedName("auth_token")
         @JsonProperty(value = "auth_token", required = true)
         private String authToken;
 
     }
 
-    @Schema(name = "input", description = "Input", required = true)
+    @Schema(name = "input", description = "Input", requiredMode = Schema.RequiredMode.REQUIRED)
     @JsonProperty(value = "input", required = true)
     @SerializedName("input")
     private Input input;
index 6f624d0..f471806 100644 (file)
@@ -377,7 +377,7 @@ public class PolicyController {
                 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage())) //
                 .onErrorResume(e -> Mono.empty()) //
                 .collectList() //
-                .map(authPolicies -> policiesToJson(authPolicies)) //
+                .map(this::policiesToJson) //
                 .map(str -> new ResponseEntity<>(str, HttpStatus.OK));
     }
 
@@ -419,7 +419,7 @@ public class PolicyController {
                 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage())) //
                 .onErrorResume(e -> Mono.empty()) //
                 .collectList() //
-                .map(authPolicies -> toPolicyIdsJson(authPolicies)) //
+                .map(this::toPolicyIdsJson) //
                 .map(policyIdsJson -> new ResponseEntity<>(policyIdsJson, HttpStatus.OK));
     }
 
index f50d553..0484acc 100644 (file)
@@ -128,20 +128,23 @@ class A1ClientFactoryTest {
     @DisplayName("test Custom Adapter Creation")
     void testCustomAdapterCreation() {
 
-        Ric ric = new Ric(ricConfig("", CustomA1AdapterFactory.class.getName()));
-        A1Client client = factoryUnderTest.createA1Client(ric).block();
+        Ric ricLocal = new Ric(ricConfig("", CustomA1AdapterFactory.class.getName()));
+        A1Client client = factoryUnderTest.createA1Client(ricLocal).block();
 
+        assert client != null;
         assertEquals(client.getClass(), StdA1ClientVersion2.class);
 
-        ric = new Ric(ricConfig("", "org.onap.ccsdk.oran.a1policymanagementservice.clients.StdA1ClientVersion2"));
-        client = factoryUnderTest.createA1Client(ric).block();
+        ricLocal = new Ric(ricConfig("", "org.onap.ccsdk.oran.a1policymanagementservice.clients.StdA1ClientVersion2"));
+        client = factoryUnderTest.createA1Client(ricLocal).block();
 
+        assert client != null;
         assertEquals(client.getClass(), StdA1ClientVersion2.class);
 
-        ric = new Ric(
+        ricLocal = new Ric(
                 ricConfig("", "org.onap.ccsdk.oran.a1policymanagementservice.clients.StdA1ClientVersion2$Factory"));
-        client = factoryUnderTest.createA1Client(ric).block();
+        client = factoryUnderTest.createA1Client(ricLocal).block();
 
+        assert client != null;
         assertEquals(client.getClass(), StdA1ClientVersion2.class);
 
         Exception e = Assertions.assertThrows(Exception.class, () -> {
index b0255bf..63b5af8 100644 (file)
@@ -269,16 +269,16 @@ class ApplicationTest {
         waitforS3();
 
         {
-            Policies policies = new Policies(this.applicationConfig);
-            policies.restoreFromDatabase(ric, this.policyTypes).blockLast();
-            assertThat(policies.size()).isEqualTo(noOfPolicies);
+            Policies policiesLocal = new Policies(this.applicationConfig);
+            policiesLocal.restoreFromDatabase(ric, this.policyTypes).blockLast();
+            assertThat(policiesLocal.size()).isEqualTo(noOfPolicies);
         }
 
         {
             restClient().delete("/policies/id2").block();
-            Policies policies = new Policies(this.applicationConfig);
-            policies.restoreFromDatabase(ric, this.policyTypes).blockLast();
-            assertThat(policies.size()).isEqualTo(noOfPolicies - 1);
+            Policies policiesAfterDelete = new Policies(this.applicationConfig);
+            policiesAfterDelete.restoreFromDatabase(ric, this.policyTypes).blockLast();
+            assertThat(policiesAfterDelete.size()).isEqualTo(noOfPolicies - 1);
         }
     }
 
@@ -393,7 +393,7 @@ class ApplicationTest {
 
     @Test
     @DisplayName("test Get Rics")
-    void testGetRics() throws Exception {
+    void testGetRics() {
         addRic("ric1");
         this.addPolicyType("type1", "ric1");
         String url = "/rics?policytype_id=type1";
@@ -786,7 +786,7 @@ class ApplicationTest {
 
     @Test
     @DisplayName("test Get Policy Types")
-    void testGetPolicyTypes() throws Exception {
+    void testGetPolicyTypes() {
         String TYPE_ID_1 = "A_type1_1.9.0";
         String TYPE_ID_2 = "A_type1_2.0.0";
         String TYPE_ID_3 = "A_type1_1.5.0";
@@ -1002,7 +1002,7 @@ class ApplicationTest {
 
     @Test
     @DisplayName("test Service Supervision")
-    void testServiceSupervision() throws Exception {
+    void testServiceSupervision() {
         putService("service1", 1, HttpStatus.CREATED);
         addPolicyType("type1", "ric1");
 
@@ -1044,7 +1044,7 @@ class ApplicationTest {
 
     @Test
     @DisplayName("test Get Service Status")
-    void testGetServiceStatus() throws Exception {
+    void testGetServiceStatus() {
         String url = "/status";
         String rsp = restClient().get(url).block();
         assertThat(rsp).contains("success");
@@ -1167,7 +1167,7 @@ class ApplicationTest {
             assertThat(test.isFailed()).isFalse();
         }
         assertThat(policies.size()).isZero();
-        logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
+        logger.info("Concurrency test took: {}", Duration.between(startTime, Instant.now()));
 
         assertThat(nonRespondingRic.getState()).isEqualTo(RicState.UNAVAILABLE);
         nonRespondingRic.setState(RicState.AVAILABLE);
@@ -1243,7 +1243,7 @@ class ApplicationTest {
         return true;
     }
 
-    private MockA1Client getA1Client(String ricId) throws ServiceException {
+    private MockA1Client getA1Client(String ricId) {
         return a1ClientFactory.getOrCreateA1Client(ricId);
     }
 
index 0bf212a..abcc70d 100644 (file)
@@ -78,7 +78,7 @@ class ConcurrencyTestRunnable implements Runnable {
             System.out.println(Thread.currentThread() + result.getBody());
 
         } catch (Exception e) {
-            logger.error(Thread.currentThread() + "Concurrency test printStatusInfo exception " + e.toString());
+            logger.error("{} Concurrency test printStatusInfo exception {}", Thread.currentThread(), e.toString());
         }
     }
 
@@ -99,7 +99,7 @@ class ConcurrencyTestRunnable implements Runnable {
                 deletePolicy(name + "-");
             }
         } catch (Exception e) {
-            logger.error("Concurrency test exception " + e.toString());
+            logger.error("Concurrency test exception {}", e.toString());
             printStatusInfo();
             failed = true;
         }
index 42e3b0c..e46b836 100644 (file)
@@ -134,14 +134,14 @@ class ConfigurationControllerTest {
     }
 
     private String configAsString() throws Exception {
-        File configFile =
+        File configFileLocal =
                 new File(getClass().getClassLoader().getResource("test_application_configuration.json").getFile());
-        return FileUtils.readFileToString(configFile, "UTF-8");
+        return FileUtils.readFileToString(configFileLocal, "UTF-8");
     }
 
     @Test
     @DisplayName("put Invalid Configuration should Return Error 400")
-    void putInvalidConfiguration_shouldReturnError400() throws Exception {
+    void putInvalidConfiguration_shouldReturnError400() {
         String url = "a1-policy/v2/configuration";
 
         // Valid JSON but invalid configuration.
index e4d7859..ff818ca 100644 (file)
 
 package org.onap.ccsdk.oran.a1policymanagementservice.repository;
 
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.awaitility.Awaitility.await;
-
-import java.io.IOException;
-import java.lang.invoke.MethodHandles;
-
 import org.junit.jupiter.api.DisplayName;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
 import org.mockito.junit.jupiter.MockitoExtension;
-import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
 import reactor.core.publisher.Flux;
 import reactor.core.publisher.Mono;
 import reactor.test.StepVerifier;
 
+import java.lang.invoke.MethodHandles;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+
 @ExtendWith(MockitoExtension.class)
 class LockTest {
 
@@ -66,7 +63,7 @@ class LockTest {
 
     @Test
     @DisplayName("test Lock")
-    void testLock() throws IOException, ServiceException {
+    void testLock() {
         Lock lock = new Lock("l1");
         Lock.Grant grant = lock.lockBlocking(LockType.SHARED, "test");
         grant.unlockBlocking();
index 3b1ee8f..c2db815 100644 (file)
 
 package org.onap.ccsdk.oran.a1policymanagementservice.tasks;
 
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 import com.google.common.base.Charsets;
 import com.google.common.io.Resources;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParser;
-
-import java.io.IOException;
-import java.net.URL;
-import java.time.Duration;
-import java.util.Arrays;
-import java.util.Optional;
-import java.util.Properties;
-
 import org.junit.jupiter.api.DisplayName;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
@@ -55,14 +38,20 @@ import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationCo
 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfigParser.ConfigParserResult;
 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ConfigurationFile;
 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
-import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
-import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
-import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
-import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
-import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
-
+import org.onap.ccsdk.oran.a1policymanagementservice.repository.*;
 import reactor.test.StepVerifier;
 
+import java.io.IOException;
+import java.net.URL;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Optional;
+import java.util.Properties;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
 @ExtendWith(MockitoExtension.class)
 class RefreshConfigTaskTest {
 
@@ -74,11 +63,11 @@ class RefreshConfigTaskTest {
     @Mock
     ConfigurationFile configurationFileMock;
 
-    private RefreshConfigTask createTestObject(boolean configFileExists) {
-        return createTestObject(configFileExists, spy(new Rics()), new Policies(appConfig), true);
+    private RefreshConfigTask createTestObject(boolean stubConfigFileExists) {
+        return createTestObject(spy(new Rics()), new Policies(appConfig), stubConfigFileExists);
     }
 
-    private RefreshConfigTask createTestObject(boolean configFileExists, Rics rics, Policies policies,
+    private RefreshConfigTask createTestObject(Rics rics, Policies policies,
             boolean stubConfigFileExists) {
         SecurityContext secContext = new SecurityContext("");
 
@@ -117,9 +106,31 @@ class RefreshConfigTaskTest {
         assertThat(ricConfigs).isNotNull().hasSize(2);
     }
 
+    @Test
+    @DisplayName("test handle updated ric config method with type removed")
+    void testHandleUpdatedRicConfigRemoved() {
+
+        String ricId = "ric1";
+        refreshTaskUnderTest = this.createTestObject(false);
+        refreshTaskUnderTest.handleUpdatedRicConfig(buildRicConfigUpdate(ricId, "ric_baseurl_removed",
+                Type.REMOVED));
+        verify(refreshTaskUnderTest.rics, times(1)).remove(anyString());
+    }
+
+    @Test
+    @DisplayName("test handle updated ric config method with type changed and no ric available before")
+    void testHandleUpdatedRicConfigNullRicChanged() {
+
+        String ricId = "ric1";
+        refreshTaskUnderTest = this.createTestObject(false);
+        refreshTaskUnderTest.handleUpdatedRicConfig(buildRicConfigUpdate(ricId, "ric_baseurl_changed",
+                Type.CHANGED));
+        verify(refreshTaskUnderTest.rics, times(1)).put(any(Ric.class));
+    }
+
     @Test
     @DisplayName("test when File Exists But Json Is Incorrect then No Rics Are Put In Repository")
-    void whenFileExistsButJsonIsIncorrect_thenNoRicsArePutInRepository() throws Exception {
+    void whenFileExistsButJsonIsIncorrect_thenNoRicsArePutInRepository() {
         refreshTaskUnderTest = this.createTestObject(true);
 
         // When
@@ -148,4 +159,16 @@ class RefreshConfigTaskTest {
         String string = Resources.toString(url, Charsets.UTF_8);
         return Optional.of(JsonParser.parseString(string).getAsJsonObject());
     }
+
+    private ApplicationConfig.RicConfigUpdate buildRicConfigUpdate(String ricID, String baseUrl,
+                                                                   Type event) {
+        return new ApplicationConfig.RicConfigUpdate(buildRicConfig(ricID, baseUrl), event);
+    }
+
+    private RicConfig buildRicConfig(String ricID, String baseUrl) {
+        return RicConfig.builder()
+                .ricId(ricID)
+                .baseUrl(baseUrl)
+                .build();
+    }
 }
index 91b762c..0cd9db2 100644 (file)
@@ -54,7 +54,7 @@ public class MockA1Client implements A1Client {
     @Setter
     private String errorInject;
 
-    public MockA1Client(String ricId, ApplicationConfig appConfig, PolicyTypes policyTypes, Duration asynchDelay) {
+    public MockA1Client(ApplicationConfig appConfig, PolicyTypes policyTypes, Duration asynchDelay) {
         this.policyTypes = policyTypes;
         this.asynchDelay = asynchDelay;
         ApplicationConfig cfg = spy(appConfig);
index be7dfcb..974c3b0 100644 (file)
@@ -59,7 +59,7 @@ public class MockA1ClientFactory extends A1ClientFactory {
     public MockA1Client getOrCreateA1Client(String ricId) {
         if (!clients.containsKey(ricId)) {
             logger.debug("Creating client for RIC: {}", ricId);
-            MockA1Client client = spy(new MockA1Client(ricId, appConfig, policyTypes, asynchDelay));
+            MockA1Client client = spy(new MockA1Client(appConfig, policyTypes, asynchDelay));
             clients.put(ricId, client);
         }
         return clients.get(ricId);