diff options
author | raviteja.karumuri <raviteja.karumuri@est.tech> | 2024-08-20 17:22:15 +0100 |
---|---|---|
committer | RAVITEJA KARUMURI <raviteja.karumuri@est.tech> | 2024-08-30 09:50:08 +0000 |
commit | c6e2c85fe7c024c56112869ed9231d7726a47d24 (patch) | |
tree | 73d64992099f099e3d5e42e51c06da6f8b7234c1 /a1-policy-management/src/test | |
parent | e1870f96ec0a0e731f82e0c158ae970409112046 (diff) |
Improve tests/issues found in Sonar report - A1 Oslo/NewDelhi/Montreal/London- Part1- Montreal
Issue-ID: CCSDK-4037
Change-Id: Ib7e6e62e2e922d3d483d95905e429aa9eac56c88
Signed-off-by: Raviteja Karumuri <raviteja.karumuri@est.tech>
Diffstat (limited to 'a1-policy-management/src/test')
10 files changed, 211 insertions, 50 deletions
diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactoryTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactoryTest.java index f50d5537..3a510102 100644 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactoryTest.java +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactoryTest.java @@ -22,6 +22,7 @@ package org.onap.ccsdk.oran.a1policymanagementservice.clients; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; @@ -128,20 +129,20 @@ 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(); + assertNotNull(client); 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(); + assertNotNull(client); 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(); + assertNotNull(client); assertEquals(client.getClass(), StdA1ClientVersion2.class); Exception e = Assertions.assertThrows(Exception.class, () -> { diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/MetersTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/MetersTest.java index 922d139d..c714268d 100644 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/MetersTest.java +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/configuration/MetersTest.java @@ -22,8 +22,8 @@ package org.onap.ccsdk.oran.a1policymanagementservice.configuration; import static org.assertj.core.api.Assertions.assertThat; -import io.micrometer.prometheus.PrometheusConfig; -import io.micrometer.prometheus.PrometheusMeterRegistry; +import io.micrometer.prometheusmetrics.PrometheusConfig; +import io.micrometer.prometheusmetrics.PrometheusMeterRegistry; import java.time.Instant; import java.util.Arrays; diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ApplicationTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ApplicationTest.java index daa3a1d8..960ab563 100644 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ApplicationTest.java +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ApplicationTest.java @@ -230,7 +230,6 @@ class ApplicationTest { } @Test - @SuppressWarnings("squid:S2925") // "Thread.sleep" should not be used in tests. @DisplayName("test ZZ Actuator") void testZZActuator() throws Exception { // The test must be run last, hence the "ZZ" in the name. All succeeding tests @@ -246,14 +245,9 @@ class ApplicationTest { client.post("/actuator/loggers/org.springframework.boot.actuate", "{\"configuredLevel\":\"trace\"}").block(); // This will stop the web server and all coming tests will fail. - client.post("/actuator/shutdown", "").block(); - - Thread.sleep(1000); - - StepVerifier.create(restClient().get("/rics")) // Any call - .expectSubscription() // - .expectErrorMatches(t -> t instanceof WebClientRequestException) // - .verify(); + ResponseEntity<String> entity = client.postForEntity("/actuator/shutdown", "").block(); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(((String) entity.getBody())).contains("Shutting down");; } @@ -270,16 +264,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); } } @@ -394,7 +388,7 @@ class ApplicationTest { @Test @DisplayName("test Get Rics") - void testGetRics() throws Exception { + void testGetRics() throws JsonProcessingException { addRic("ric1"); this.addPolicyType("type1", "ric1"); String url = "/rics?policytype_id=type1"; @@ -799,7 +793,7 @@ class ApplicationTest { @Test @DisplayName("test Get Policy Types") - void testGetPolicyTypes() throws Exception { + void testGetPolicyTypes() throws JsonProcessingException { 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"; @@ -1013,7 +1007,7 @@ class ApplicationTest { @Test @DisplayName("test Service Supervision") - void testServiceSupervision() throws Exception { + void testServiceSupervision() throws JsonProcessingException { putService("service1", 2, HttpStatus.CREATED); addPolicyType("type1", "ric1"); @@ -1186,7 +1180,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); diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ConcurrencyTestRunnable.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ConcurrencyTestRunnable.java index 888325b2..a42d034a 100644 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ConcurrencyTestRunnable.java +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ConcurrencyTestRunnable.java @@ -86,7 +86,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()); } } @@ -107,7 +107,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; } diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ConfigurationControllerTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ConfigurationControllerTest.java index 42e3b0c9..e46b8367 100644 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ConfigurationControllerTest.java +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/controllers/v2/ConfigurationControllerTest.java @@ -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. diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/datastore/S3ObjectStoreTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/datastore/S3ObjectStoreTest.java new file mode 100644 index 00000000..941b7770 --- /dev/null +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/datastore/S3ObjectStoreTest.java @@ -0,0 +1,134 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2024 OpenInfra Foundation Europe. All rights reserved. + * ====================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ========================LICENSE_END=================================== + */ + +package org.onap.ccsdk.oran.a1policymanagementservice.datastore; + +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig; +import org.reactivestreams.Publisher; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; +import org.testcontainers.containers.localstack.LocalStackContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; +import reactor.test.StepVerifier; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.function.Predicate; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@Testcontainers +@ExtendWith({MockitoExtension.class, OutputCaptureExtension.class}) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class S3ObjectStoreTest { + + static ApplicationConfig appConfig; + private static S3ObjectStore s3ObjectStore; + private static final String bucketName = "s3bucket"; + + @Container + private static final LocalStackContainer localstack = + new LocalStackContainer(DockerImageName.parse("localstack/localstack:0.11.3")) + .withServices(LocalStackContainer.Service.S3); + + @BeforeAll + static void init() { + appConfig = mock(ApplicationConfig.class); + when(appConfig.isS3Enabled()).thenReturn(Boolean.TRUE); + when(appConfig.getS3EndpointOverride()).thenReturn(localstack.getEndpoint().toString()); + when(appConfig.getS3AccessKeyId()).thenReturn(localstack.getAccessKey()); + when(appConfig.getS3SecretAccessKey()).thenReturn(localstack.getSecretKey()); + when(appConfig.getS3Bucket()).thenReturn(bucketName); + s3ObjectStore = new S3ObjectStore(appConfig, "location"); + } + @Test + @Order(1) + void testGetS3AsynchClient() { + assertNotNull(s3ObjectStore); + } + + @Test + @Order(2) + void testCreateAndDeleteS3BucketSuccess(CapturedOutput capturedOutput) { + + testSuccess(s3ObjectStore.createDataStore(), actual -> actual.equals(bucketName)); + assertFalse(capturedOutput.getOut().contains("Could not create S3 bucket:")); + + testSuccess(s3ObjectStore.deleteBucket(), actual -> actual.equals(bucketName)); + } + + @Test + @Order(3) + void testWriteAndReadAndDeleteObjectSuccess(CapturedOutput capturedOutput) { + + testSuccess(s3ObjectStore.createDataStore(), actual -> actual.equals(bucketName)); + byte[] fileData = "testData".getBytes(StandardCharsets.UTF_8); + new String(fileData); + testSuccess(s3ObjectStore.writeObject("test", fileData), + actual -> Arrays.equals(actual, fileData)); + assertFalse(capturedOutput.getOut().contains("Failed to store object")); + testSuccess(s3ObjectStore.readObject("test"), + actual -> Arrays.equals(actual, fileData)); + testSuccess(s3ObjectStore.deleteAllObjects(), actual -> actual.equals("OK")); + } + + @Test + @Order(4) + void testListObjectsSuccess() { + + s3ObjectStore.createDataStore().block(); + String objectName = "test"; + byte[] fileData = "testData".getBytes(StandardCharsets.UTF_8); + testSuccess(s3ObjectStore.writeObject(objectName, fileData), + actual -> Arrays.equals(actual, fileData)); + testSuccess(s3ObjectStore.listObjects(""), actual -> actual.equals(objectName)); + } + + @Test + @Order(5) + void testCreateAndDeleteS3BucketError(CapturedOutput capturedOutput) { + + when(appConfig.getS3Bucket()).thenReturn("S3Bucket"); + + testFailure(s3ObjectStore.createDataStore(), actual -> actual.equals("Not Created")); + + testFailure(s3ObjectStore.deleteBucket(), actual -> actual.equals("NOK")); + assertTrue(capturedOutput.getOut().contains("Could not delete bucket:")); + } + + <T> void testSuccess(Publisher<T> publisher, Predicate<T> equalityCheck) { + StepVerifier.create(publisher) + .expectNextMatches(equalityCheck) + .verifyComplete(); + } + + <T> void testFailure(Publisher<T> publisher, Predicate<T> equalityCheck) { + StepVerifier.create(publisher) + .expectNextMatches(equalityCheck) + .verifyComplete(); + } +} diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/LockTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/LockTest.java index e4d78599..ff818caf 100644 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/LockTest.java +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/repository/LockTest.java @@ -20,25 +20,22 @@ 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(); diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RefreshConfigTaskTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RefreshConfigTaskTest.java index 3b1ee8f7..dea228ec 100644 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RefreshConfigTaskTest.java +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/tasks/RefreshConfigTaskTest.java @@ -22,6 +22,7 @@ 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.ArgumentMatchers.anyString; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; @@ -74,11 +75,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(""); @@ -118,8 +119,30 @@ class RefreshConfigTaskTest { } @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 +171,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(); + } } diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/utils/MockA1Client.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/utils/MockA1Client.java index 91b762c5..0cd9db20 100644 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/utils/MockA1Client.java +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/utils/MockA1Client.java @@ -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); diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/utils/MockA1ClientFactory.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/utils/MockA1ClientFactory.java index be7dfcb3..974c3b08 100644 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/utils/MockA1ClientFactory.java +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/utils/MockA1ClientFactory.java @@ -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); |