diff options
author | waynedunican <wayne.dunican@est.tech> | 2024-08-20 08:27:23 +0100 |
---|---|---|
committer | waynedunican <wayne.dunican@est.tech> | 2024-09-03 16:03:15 +0100 |
commit | c780793359e31dac7d99731360cf1e575485f638 (patch) | |
tree | 897f61ba970728a80a75c35cac23033f68f941b4 | |
parent | 460b684f934776e9c4eefab00d1febb398e87bb1 (diff) |
Increase coverage in common
Issue-ID: POLICY-5106
Change-Id: I54dfcc2ab1100e959ee786ce7a9791ef3465686f
Signed-off-by: waynedunican <wayne.dunican@est.tech>
20 files changed, 1388 insertions, 3 deletions
diff --git a/common-parameters/pom.xml b/common-parameters/pom.xml index 2e0570f8..3257d3b3 100644 --- a/common-parameters/pom.xml +++ b/common-parameters/pom.xml @@ -62,5 +62,9 @@ <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + </dependency> </dependencies> </project> diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/ParameterGroupTest.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/ParameterGroupTest.java new file mode 100644 index 00000000..d90b13d4 --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/ParameterGroupTest.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation + * ================================================================================ + * 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.policy.common.parameters; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ParameterGroupTest { + + private ParameterGroup parameterGroup; + + @BeforeEach + void setUp() { + parameterGroup = new ParameterGroup() { + private String name; + private BeanValidationResult validationResult = new BeanValidationResult("testGroup", "testObject"); + + @Override + public String getName() { + return name; + } + + @Override + public void setName(final String name) { + this.name = name; + } + + @Override + public BeanValidationResult validate() { + return validationResult; + } + }; + } + + @Test + void testGetName() { + String testName = "TestGroupName"; + parameterGroup.setName(testName); + assertEquals(testName, parameterGroup.getName(), "The group name should match the one set"); + } + + @Test + void testSetName() { + String testName = "AnotherGroupName"; + parameterGroup.setName(testName); + assertEquals(testName, parameterGroup.getName(), "The group name should match the one set"); + } + + @Test + void testValidate() { + BeanValidationResult result = parameterGroup.validate(); + assertNotNull(result, "The validation result should not be null"); + assertEquals("testGroup", result.getName(), "The validation result should have the correct group name"); + } + + @Test + void testIsValid() { + BeanValidationResult mockValidationResult = mock(BeanValidationResult.class); + ValidationStatus mockStatus = mock(ValidationStatus.class); + + when(mockStatus.isValid()).thenReturn(true); + when(mockValidationResult.getStatus()).thenReturn(mockStatus); + + ParameterGroup mockedParameterGroup = spy(parameterGroup); + doReturn(mockValidationResult).when(mockedParameterGroup).validate(); + + assertTrue(mockedParameterGroup.isValid(), "The parameters should be valid"); + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/ParameterServiceTest.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/ParameterServiceTest.java new file mode 100644 index 00000000..7091f568 --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/ParameterServiceTest.java @@ -0,0 +1,161 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation + * ================================================================================ + * 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.policy.common.parameters; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ParameterServiceTest { + + private static class TestParameterGroup implements ParameterGroup { + private final String name; + + TestParameterGroup(String name) { + this.name = name; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public void setName(String name) { + // do nothing + } + + @Override + public BeanValidationResult validate() { + return null; + } + + @Override + public boolean isValid() { + return ParameterGroup.super.isValid(); + } + } + + @BeforeEach + void setUp() { + ParameterService.clear(); + } + + @Test + void testRegisterAndRetrieveParameterGroup() { + TestParameterGroup group = new TestParameterGroup("testGroup"); + + ParameterService.register(group); + ParameterGroup retrievedGroup = ParameterService.get("testGroup"); + + assertEquals(group, retrievedGroup, "The retrieved group should be the same as the registered group."); + } + + @Test + void testRegisterDuplicateParameterGroupThrowsException() { + TestParameterGroup group = new TestParameterGroup("testGroup"); + + ParameterService.register(group); + + TestParameterGroup testGroup = new TestParameterGroup("testGroup"); + assertThrows(ParameterRuntimeException.class, () -> { + ParameterService.register(testGroup); + }, "Registering a duplicate parameter group should throw an exception."); + } + + @Test + void testRegisterWithOverwrite() { + TestParameterGroup group1 = new TestParameterGroup("testGroup"); + TestParameterGroup group2 = new TestParameterGroup("testGroup"); + + ParameterService.register(group1); + ParameterService.register(group2, true); // Overwrite the existing group + + ParameterGroup retrievedGroup = ParameterService.get("testGroup"); + assertEquals(group2, retrievedGroup, + "The retrieved group should be the newly registered group after overwrite."); + } + + @Test + void testDeregisterParameterGroupByName() { + TestParameterGroup group = new TestParameterGroup("testGroup"); + + ParameterService.register(group); + ParameterService.deregister("testGroup"); + + assertThrows(ParameterRuntimeException.class, () -> { + ParameterService.get("testGroup"); + }, "Deregistering a parameter group should remove it from the service."); + } + + @Test + void testDeregisterParameterGroupByInstance() { + TestParameterGroup group = new TestParameterGroup("testGroup"); + + ParameterService.register(group); + ParameterService.deregister(group); + + assertThrows(ParameterRuntimeException.class, () -> { + ParameterService.get("testGroup"); + }, "Deregistering a parameter group by instance should remove it from the service."); + } + + @Test + void testContainsParameterGroup() { + TestParameterGroup group = new TestParameterGroup("testGroup"); + + ParameterService.register(group); + + assertTrue(ParameterService.contains("testGroup"), "The parameter group should be contained in the service."); + assertFalse(ParameterService.contains("nonExistentGroup"), + "A non-existent parameter group should not be contained in the service."); + } + + @Test + void testGetAllParameterGroups() { + TestParameterGroup group1 = new TestParameterGroup("group1"); + TestParameterGroup group2 = new TestParameterGroup("group2"); + + ParameterService.register(group1); + ParameterService.register(group2); + + Set<Map.Entry<String, ParameterGroup>> allGroups = ParameterService.getAll(); + assertEquals(2, allGroups.size(), "There should be exactly 2 parameter groups in the service."); + assertTrue(allGroups.stream().anyMatch(entry -> entry.getKey().equals("group1")), + "The service should contain group1."); + assertTrue(allGroups.stream().anyMatch(entry -> entry.getKey().equals("group2")), + "The service should contain group2."); + } + + @Test + void testClearParameterGroups() { + TestParameterGroup group = new TestParameterGroup("testGroup"); + + ParameterService.register(group); + ParameterService.clear(); + + assertFalse(ParameterService.contains("testGroup"), "All parameter groups should be cleared from the service."); + } +} diff --git a/common-parameters/src/test/java/org/onap/policy/common/parameters/validation/ParameterGroupValidatorTest.java b/common-parameters/src/test/java/org/onap/policy/common/parameters/validation/ParameterGroupValidatorTest.java new file mode 100644 index 00000000..0c7f29b7 --- /dev/null +++ b/common-parameters/src/test/java/org/onap/policy/common/parameters/validation/ParameterGroupValidatorTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation + * ================================================================================ + * 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.policy.common.parameters.validation; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import jakarta.validation.ConstraintValidatorContext; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.parameters.ParameterGroup; + +class ParameterGroupValidatorTest { + + private ParameterGroupValidator validator; + + @Mock + private ParameterGroup mockParameterGroup; + + @Mock + private BeanValidationResult mockBeanValidationResult; + + @Mock + private ConstraintValidatorContext mockContext; + + @Mock + private ConstraintValidatorContext.ConstraintViolationBuilder mockViolationBuilder; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + validator = new ParameterGroupValidator(); + } + + @Test + void testIsValid_NullValue() { + boolean result = validator.isValid(null, mockContext); + assertTrue(result, "Expected isValid to return true when value is null"); + } + + @Test + void testIsValid_ValidParameterGroup() { + when(mockParameterGroup.validate()).thenReturn(mockBeanValidationResult); + when(mockBeanValidationResult.isValid()).thenReturn(true); + + boolean result = validator.isValid(mockParameterGroup, mockContext); + assertTrue(result, "Expected isValid to return true when ParameterGroup is valid"); + + verify(mockContext, never()).buildConstraintViolationWithTemplate(anyString()); + } + + @Test + void testIsValid_InvalidParameterGroup() { + when(mockParameterGroup.validate()).thenReturn(mockBeanValidationResult); + when(mockBeanValidationResult.isValid()).thenReturn(false); + when(mockBeanValidationResult.getMessage()).thenReturn("Invalid parameters"); + when(mockContext.buildConstraintViolationWithTemplate(anyString())).thenReturn(mockViolationBuilder); + + boolean result = validator.isValid(mockParameterGroup, mockContext); + assertFalse(result, "Expected isValid to return false when ParameterGroup is invalid"); + + InOrder inOrder = inOrder(mockContext, mockViolationBuilder); + inOrder.verify(mockContext).buildConstraintViolationWithTemplate("Invalid parameters"); + inOrder.verify(mockViolationBuilder).addConstraintViolation(); + } +} diff --git a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxy.java b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxy.java index d9e55ddd..98fbbf0b 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxy.java +++ b/policy-endpoints/src/main/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxy.java @@ -45,7 +45,7 @@ import org.slf4j.LoggerFactory; * implementation(s). */ @Getter -class TopicEndpointProxy implements TopicEndpoint { +public class TopicEndpointProxy implements TopicEndpoint { /** * Logger. */ diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.java index 198cdc2c..a30904dd 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.java @@ -24,6 +24,7 @@ package org.onap.policy.common.endpoints.event.comm; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; @@ -35,6 +36,8 @@ import java.util.Properties; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.bus.KafkaTopicFactories; +import org.onap.policy.common.endpoints.event.comm.bus.KafkaTopicPropertyBuilder; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicFactories; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicPropertyBuilder; import org.onap.policy.common.endpoints.parameters.TopicParameterGroup; @@ -47,6 +50,9 @@ class TopicEndpointProxyTest { private static final String NOOP_SOURCE_TOPIC = "noop-source"; private static final String NOOP_SINK_TOPIC = "noop-sink"; + private static final String KAFKA_SOURCE_TOPIC = "kafka-source"; + private static final String KAFKA_SINK_TOPIC = "kafka-sink"; + private final Properties configuration = new Properties(); private final TopicParameterGroup group = new TopicParameterGroup(); @@ -104,6 +110,8 @@ class TopicEndpointProxyTest { public void tearDown() { NoopTopicFactories.getSinkFactory().destroy(); NoopTopicFactories.getSourceFactory().destroy(); + KafkaTopicFactories.getSinkFactory().destroy(); + KafkaTopicFactories.getSourceFactory().destroy(); } @Test @@ -126,6 +134,29 @@ class TopicEndpointProxyTest { assertTrue(allSources(sources)); assertFalse(anySink(sources)); + + sources = manager.addTopicSources(group.getTopicSources()); + assertSame(1, sources.size()); + assertTrue(allSources(sources)); + } + + @Test + void testAddTopicSourcesKafka() { + TopicEndpoint manager = new TopicEndpointProxy(); + + KafkaTopicPropertyBuilder kafkaTopicPropertyBuilder = + new KafkaTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_KAFKA_SOURCE_TOPICS) + .makeTopic(KAFKA_SOURCE_TOPIC); + + configuration.putAll(kafkaTopicPropertyBuilder.build()); + group.getTopicSources().add(kafkaTopicPropertyBuilder.getParams()); + List<TopicSource> sources = manager.addTopicSources(group.getTopicSources()); + assertSame(2, sources.size()); + + configuration.remove(KAFKA_SOURCE_TOPIC); + group.setTopicSources(new LinkedList<>()); + sources = manager.addTopicSources(group.getTopicSources()); + assertSame(0, sources.size()); } @Test @@ -151,6 +182,28 @@ class TopicEndpointProxyTest { } @Test + void testAddTopicSinksListOfTopicParametersKafka() { + TopicEndpoint manager = new TopicEndpointProxy(); + + List<TopicSink> sinks = manager.addTopicSinks(group.getTopicSinks()); + assertSame(1, sinks.size()); + + KafkaTopicPropertyBuilder kafkaTopicPropertyBuilder = + new KafkaTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_KAFKA_SINK_TOPICS) + .makeTopic(KAFKA_SINK_TOPIC); + + configuration.putAll(kafkaTopicPropertyBuilder.build()); + group.getTopicSources().add(kafkaTopicPropertyBuilder.getParams()); + sinks = manager.addTopicSinks(group.getTopicSources()); + assertSame(2, sinks.size()); + + configuration.remove(KAFKA_SOURCE_TOPIC); + group.setTopicSources(new LinkedList<>()); + sinks = manager.addTopicSinks(group.getTopicSources()); + assertSame(0, sinks.size()); + } + + @Test void testAddTopicSinksProperties() { TopicEndpoint manager = new TopicEndpointProxy(); @@ -220,6 +273,13 @@ class TopicEndpointProxyTest { assertTrue(allSources(sources)); assertFalse(anySink(sources)); + + assertThatThrownBy(() -> manager.getKafkaTopicSource("testTopic")) + .hasMessageContaining("KafkaTopiceSource for testTopic not found"); + + List<String> topicName = null; + assertThatThrownBy(() -> manager.getTopicSources(topicName)) + .hasMessageContaining("must provide a list of topics"); } @Test @@ -234,6 +294,20 @@ class TopicEndpointProxyTest { assertFalse(anySource(sinks)); assertTrue(allSinks(sinks)); + + final List<String> sinks2 = null; + assertThatThrownBy(() -> manager.getTopicSinks(sinks2)).hasMessageContaining("must provide a list of topics"); + + List<String> sinks3 = List.of(NOOP_SINK_TOPIC); + assertThatCode(() -> manager.getTopicSinks(sinks3)).doesNotThrowAnyException(); + + String sinkTest = null; + assertThatThrownBy(() -> manager.getTopicSinks(sinkTest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid parameter"); + + assertThatThrownBy(() -> manager.getKafkaTopicSink("testTopic")) + .hasMessageContaining("KafkaTopicSink for testTopic not found"); } @Test diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedKafkaTopicSourceFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedKafkaTopicSourceFactoryTest.java new file mode 100644 index 00000000..80229419 --- /dev/null +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/IndexedKafkaTopicSourceFactoryTest.java @@ -0,0 +1,74 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. + * ================================================================================ + * 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.policy.common.endpoints.event.comm.bus; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import org.apache.kafka.clients.ClientUtils; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; + +class IndexedKafkaTopicSourceFactoryTest { + + private IndexedKafkaTopicSourceFactory factory; + + @Mock + ClientUtils mockClientUtils; + + @Test + void testBuild() { + factory = new IndexedKafkaTopicSourceFactory(); + BusTopicParams params = new BusTopicParams(); + + // set servers to null + params.setServers(null); + assertThatThrownBy(() -> factory.build(params)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("KAFKA Server(s) must be provided"); + + // set servers to empty + params.setServers(List.of()); + assertThatThrownBy(() -> factory.build(params)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("KAFKA Server(s) must be provided"); + + List<String> servers = List.of("kafka:9092", "kafka:29092"); + params.setServers(servers); + + // set topic to null + params.setTopic(null); + assertThatThrownBy(() -> factory.build(params)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("A topic must be provided"); + + // set topic to empty + params.setTopic(""); + assertThatThrownBy(() -> factory.build(params)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("A topic must be provided"); + + params.setTopic("topic01"); + + assertThatThrownBy(() -> factory.build(servers, "topic1")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot create topic"); + } +} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/KafkaPublisherWrapperTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/KafkaPublisherWrapperTest.java new file mode 100644 index 00000000..1f7c2cf7 --- /dev/null +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/KafkaPublisherWrapperTest.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation + * ================================================================================ + * 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.policy.common.endpoints.event.comm.bus.internal; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.Properties; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.Producer; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; + +class KafkaPublisherWrapperTest { + + private BusPublisher.KafkaPublisherWrapper kafkaPublisherWrapper; + private Producer<String, String> mockProducer; + private BusTopicParams mockBusTopicParams; + + @BeforeEach + void setUp() { + mockProducer = mock(KafkaProducer.class); + mockBusTopicParams = mock(BusTopicParams.class); + + when(mockBusTopicParams.getTopic()).thenReturn("testTopic"); + when(mockBusTopicParams.getServers()).thenReturn(Collections.singletonList("localhost:9092")); + when(mockBusTopicParams.isTopicInvalid()).thenReturn(false); + when(mockBusTopicParams.isAdditionalPropsValid()).thenReturn(false); + when(mockBusTopicParams.isAllowTracing()).thenReturn(false); + + kafkaPublisherWrapper = new BusPublisher.KafkaPublisherWrapper(mockBusTopicParams) { + protected Producer<String, String> createProducer(Properties props) { // NOSONAR instance creation + return mockProducer; + } + }; + } + + @Test + void testConstructor() { + verify(mockBusTopicParams).getTopic(); + verify(mockBusTopicParams).getServers(); + verify(mockBusTopicParams).isTopicInvalid(); + verify(mockBusTopicParams).isAdditionalPropsValid(); + verify(mockBusTopicParams).isAllowTracing(); + } + + @Test + void testSendSuccess() { + when(mockProducer.send(ArgumentMatchers.any(ProducerRecord.class))).thenReturn(null); + assertTrue(kafkaPublisherWrapper.send("partitionId", "testMessage")); + } + + @Test + void testSendNullMessage() { + IllegalArgumentException thrown = assertThrows( + IllegalArgumentException.class, + () -> kafkaPublisherWrapper.send("partitionId", null), + "Expected send() to throw, but it didn't" + ); + assertEquals("No message provided", thrown.getMessage()); + } + + @Test + void testSendFailure() { + when(mockProducer.send(ArgumentMatchers.any(ProducerRecord.class))).thenThrow(RuntimeException.class); + assertTrue(kafkaPublisherWrapper.send("partitionId", "testMessage")); + } + + @Test + void testClose() { + assertThatCode(kafkaPublisherWrapper::close).doesNotThrowAnyException(); + } +} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/features/NetLoggerFeatureApiTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/features/NetLoggerFeatureApiTest.java new file mode 100644 index 00000000..2ea64239 --- /dev/null +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/features/NetLoggerFeatureApiTest.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. + * ================================================================================ + * 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.policy.common.endpoints.features; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType; +import org.slf4j.Logger; + +@ExtendWith(MockitoExtension.class) +class NetLoggerFeatureApiTest { + + @Mock + private Logger mockLogger; + + @Mock + private EventType mockEventType; + + @Mock + private CommInfrastructure mockCommInfrastructure; + + private NetLoggerFeatureApi featureApi; + + @BeforeEach + public void setUp() { + featureApi = new NetLoggerFeatureApi() { + @Override + public boolean beforeLog(Logger eventLogger, EventType type, CommInfrastructure protocol, String topic, + String message) { + return NetLoggerFeatureApi.super.beforeLog(eventLogger, type, protocol, topic, message); + } + + @Override + public boolean afterLog(Logger eventLogger, EventType type, CommInfrastructure protocol, String topic, + String message) { + return NetLoggerFeatureApi.super.afterLog(eventLogger, type, protocol, topic, message); + } + + @Override + public int getSequenceNumber() { + return 0; + } + + @Override + public String getName() { + return NetLoggerFeatureApi.super.getName(); + } + }; + } + + @Test + void testBeforeLogDefaultBehavior() { + boolean result = featureApi.beforeLog(mockLogger, mockEventType, mockCommInfrastructure, + "testTopic", "testMessage"); + assertFalse(result, "Expected beforeLog to return false by default"); + } + + @Test + void testAfterLogDefaultBehavior() { + boolean result = featureApi.afterLog(mockLogger, mockEventType, mockCommInfrastructure, + "testTopic", "testMessage"); + assertFalse(result, "Expected afterLog to return false by default"); + } +} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/AuthorizationFilterTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/AuthorizationFilterTest.java new file mode 100644 index 00000000..2ab3071f --- /dev/null +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/AuthorizationFilterTest.java @@ -0,0 +1,84 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. + * ================================================================================ + * 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.policy.common.endpoints.http.server.test; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.onap.policy.common.endpoints.http.server.AuthorizationFilter; + +class AuthorizationFilterTest { + + AuthorizationFilter filter; + + @Mock + ServletRequest request; + + @Mock + HttpServletRequest httpRequest; + + @Mock + HttpServletResponse httpResponse; + + @Mock + ServletResponse response; + + @Mock + FilterChain chain; + + @BeforeEach + void setUp() { + request = mock(ServletRequest.class); + response = mock(ServletResponse.class); + chain = mock(FilterChain.class); + httpRequest = mock(HttpServletRequest.class); + httpResponse = mock(HttpServletResponse.class); + + filter = new AuthorizationFilter() { + @Override + protected String getRole(HttpServletRequest request) { + return "testRole"; + } + }; + } + + @Test + void testAuthorizationFilter() { + assertThatThrownBy(() -> filter.doFilter(request, response, chain)) + .isInstanceOf(ServletException.class) + .hasMessageContaining("Not an HttpServletRequest instance"); + + assertThatThrownBy(() -> filter.doFilter(httpRequest, response, chain)) + .isInstanceOf(ServletException.class) + .hasMessageContaining("Not an HttpServletResponse instance"); + + assertThatCode(() -> filter.doFilter(httpRequest, httpResponse, chain)) + .doesNotThrowAnyException(); + } +} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/RestClientParametersTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/RestClientParametersTest.java new file mode 100644 index 00000000..6013ff2d --- /dev/null +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/RestClientParametersTest.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation + * ================================================================================ + * 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.policy.common.endpoints.parameters; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; + +class RestClientParametersTest { + + private RestClientParameters params; + + @BeforeEach + void setUp() { + params = new RestClientParameters(); + } + + @Test + void testValidate_ValidParameters() { + params.setHostname("localhost"); + params.setClientName("testClient"); + params.setPort(8080); + + BeanValidationResult result = params.validate(); + + assertEquals(ValidationStatus.CLEAN, result.getStatus(), "Expected the parameters to be valid"); + assertNull(result.getResult(), "Expected no validation errors"); + } + + @Test + void testValidate_InvalidHostname() { + params.setHostname(""); + params.setClientName("testClient"); + params.setPort(8080); + + BeanValidationResult result = params.validate(); + + assertEquals(ValidationStatus.INVALID, result.getStatus(), "Expected the parameters to be invalid"); + assertTrue(result.getResult().contains("hostname") && result.getResult().contains("is blank"), + "Expected invalid hostname error message"); + } + + @Test + void testValidate_InvalidClientName() { + params.setHostname("localhost"); + params.setClientName(""); + params.setPort(8080); + + BeanValidationResult result = params.validate(); + + assertEquals(ValidationStatus.INVALID, result.getStatus(), "Expected the parameters to be invalid"); + assertTrue(result.getResult().contains("clientName") && result.getResult().contains("is blank"), + "Expected invalid clientName error message"); + } + + @Test + void testValidate_InvalidPort() { + params.setHostname("localhost"); + params.setClientName("testClient"); + params.setPort(-1); + + BeanValidationResult result = params.validate(); + + assertEquals(ValidationStatus.INVALID, result.getStatus(), "Expected the parameters to be invalid"); + assertTrue(result.getResult().contains("port") && result.getResult().contains("is not valid"), + "Expected invalid port error message"); + } + + @Test + void testValidate_MultipleInvalidParameters() { + params.setHostname(""); + params.setClientName(""); + params.setPort(-1); + + BeanValidationResult result = params.validate(); + + assertEquals(ValidationStatus.INVALID, result.getStatus(), "Expected the parameters to be invalid"); + + assertTrue(result.getResult().contains("hostname") && result.getResult().contains("is blank"), + "Expected invalid hostname error message"); + + assertTrue(result.getResult().contains("clientName") && result.getResult().contains("is blank"), + "Expected invalid clientName error message"); + + assertTrue(result.getResult().contains("port") && result.getResult().contains("is not valid"), + "Expected invalid port error message"); + } + + @Test + void testGetAndSetName() { + String name = "testClient"; + params.setName(name); + assertEquals(name, params.getName(), "Expected the client name to be set and retrieved correctly"); + } +} diff --git a/spring-utils/src/test/java/org/onap/policy/common/spring/utils/CustomImplicitNamingStrategyTest.java b/spring-utils/src/test/java/org/onap/policy/common/spring/utils/CustomImplicitNamingStrategyTest.java new file mode 100644 index 00000000..e7c3ad5d --- /dev/null +++ b/spring-utils/src/test/java/org/onap/policy/common/spring/utils/CustomImplicitNamingStrategyTest.java @@ -0,0 +1,74 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. + * ================================================================================ + * 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.policy.common.spring.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.boot.model.naming.ImplicitJoinColumnNameSource; +import org.hibernate.boot.model.relational.Database; +import org.hibernate.boot.spi.InFlightMetadataCollector; +import org.hibernate.boot.spi.MetadataBuildingContext; +import org.hibernate.engine.jdbc.env.spi.IdentifierHelper; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; + +class CustomImplicitNamingStrategyTest { + + static CustomImplicitNamingStrategy strategy; + + @Mock + static ImplicitJoinColumnNameSource source; + + @BeforeAll + public static void setUpBeforeClass() { + strategy = new CustomImplicitNamingStrategy(); + source = mock(ImplicitJoinColumnNameSource.class); + } + + @Test + void testDetermineJoinColumnName() { + Identifier identifier = new Identifier("identifier", true); + + MetadataBuildingContext buildingContextMock = mock(MetadataBuildingContext.class); + InFlightMetadataCollector flightCollectorMock = mock(InFlightMetadataCollector.class); + Database databaseMock = mock(Database.class); + + when(flightCollectorMock.getDatabase()).thenReturn(databaseMock); + when(source.getReferencedColumnName()).thenReturn(identifier); + when(source.getBuildingContext()).thenReturn(buildingContextMock); + when(buildingContextMock.getMetadataCollector()).thenReturn(flightCollectorMock); + + JdbcEnvironment environmentMock = mock(JdbcEnvironment.class); + when(databaseMock.getJdbcEnvironment()).thenReturn(environmentMock); + + IdentifierHelper helperMock = mock(IdentifierHelper.class); + when(environmentMock.getIdentifierHelper()).thenReturn(helperMock); + when(helperMock.toIdentifier(anyString())).thenReturn(identifier); + + Identifier result = strategy.determineJoinColumnName(source); + assertEquals(identifier, result); + } + +} diff --git a/spring-utils/src/test/java/org/onap/policy/common/spring/utils/YamlHttpMessageConverterTest.java b/spring-utils/src/test/java/org/onap/policy/common/spring/utils/YamlHttpMessageConverterTest.java new file mode 100644 index 00000000..0c467412 --- /dev/null +++ b/spring-utils/src/test/java/org/onap/policy/common/spring/utils/YamlHttpMessageConverterTest.java @@ -0,0 +1,136 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2024 Nordix Foundation. + * ================================================================================ + * 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.policy.common.spring.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.converter.HttpMessageNotWritableException; + +class YamlHttpMessageConverterTest { + + private YamlHttpMessageConverter converter; + + @BeforeEach + void setUp() { + converter = new YamlHttpMessageConverter(); + } + + @Test + void testCanReadAndWriteYamlMediaType() { + MediaType mediaType = new MediaType("application", "yaml"); + assertTrue(converter.canRead(Object.class, mediaType)); + assertTrue(converter.canWrite(Object.class, mediaType)); + } + + @Test + void testReadInternal() throws IOException { + // YAML content representing a simple key-value pair as a map + String yamlContent = "key: value"; + + // Mocking HttpHeaders + HttpHeaders headers = mock(HttpHeaders.class); + when(headers.getContentType()).thenReturn(MediaType.APPLICATION_JSON); // Return JSON media type + + // Mocking HttpInputMessage + HttpInputMessage inputMessage = mock(HttpInputMessage.class); + when(inputMessage.getBody()).thenReturn(new ByteArrayInputStream(yamlContent.getBytes(StandardCharsets.UTF_8))); + when(inputMessage.getHeaders()).thenReturn(headers); + + // Now we call the converter's read method and assert the results + Map<String, String> result = (Map<String, String>) converter.read(Map.class, null, inputMessage); + + assertNotNull(result); + assertEquals("value", result.get("key")); + } + + + @Test + void testReadInternalWithException() throws IOException { + HttpInputMessage inputMessage = mock(HttpInputMessage.class); + when(inputMessage.getBody()).thenThrow(new IOException("IO Exception during reading")); + + assertThrows(HttpMessageNotReadableException.class, () -> converter.read(Map.class, null, inputMessage)); + } + + @Test + void testWriteInternal() throws IOException { + // Mocking HttpHeaders + HttpHeaders headers = mock(HttpHeaders.class); + when(headers.getContentType()).thenReturn(MediaType.APPLICATION_JSON); // Return JSON media type + when(headers.getAcceptCharset()).thenReturn(null); // Return null to use default charset + + // Mocking HttpOutputMessage + HttpOutputMessage outputMessage = mock(HttpOutputMessage.class); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + when(outputMessage.getBody()).thenReturn(outputStream); + when(outputMessage.getHeaders()).thenReturn(headers); + + // A simple map to be serialized into YAML + Map<String, String> map = new HashMap<>(); + map.put("key", "value"); + + // Calling the converter's write method + converter.write(map, null, outputMessage); + + // Verifying the output + String result = outputStream.toString(StandardCharsets.UTF_8); + assertTrue(result.contains("key: value")); + } + + + @Test + void testWriteInternalWithException() throws IOException { + // Mocking HttpHeaders + HttpHeaders headers = mock(HttpHeaders.class); + when(headers.getContentType()).thenReturn(MediaType.APPLICATION_JSON); // Return YAML media type + + // Mocking HttpOutputMessage to throw an IOException when getBody() is called + HttpOutputMessage outputMessage = mock(HttpOutputMessage.class); + when(outputMessage.getBody()).thenThrow(new IOException("IO Exception during writing")); + when(outputMessage.getHeaders()).thenReturn(headers); + + // A simple map to be serialized into YAML + Map<String, String> map = new HashMap<>(); + map.put("key", "value"); + + // We expect the write method to throw a HttpMessageNotWritableException + assertThrows(HttpMessageNotWritableException.class, () -> converter.write(map, null, outputMessage)); + } + +} diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java index 1af69cd0..108dedba 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java @@ -65,7 +65,7 @@ public class SelfSignedKeyStoreTest { } @Test - void testSelfSignedKeyStoreString() throws IOException, InterruptedException { + void testSelfSignedKeyStoreString() throws IOException { String relName = "target/my-keystore"; String altName = saveUserDir + "/" + relName; File altFile = new File(altName); diff --git a/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerMarkerFilterTest.java b/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerMarkerFilterTest.java new file mode 100644 index 00000000..64278a93 --- /dev/null +++ b/utils/src/test/java/org/onap/policy/common/utils/logging/LoggerMarkerFilterTest.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation + * ================================================================================ + * 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.policy.common.utils.logging; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.spi.FilterReply; +import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.policy.common.utils.logging.LoggerMarkerFilter.AuditLoggerMarkerFilter; +import org.onap.policy.common.utils.logging.LoggerMarkerFilter.MetricLoggerMarkerFilter; +import org.onap.policy.common.utils.logging.LoggerMarkerFilter.SecurityLoggerMarkerFilter; +import org.onap.policy.common.utils.logging.LoggerMarkerFilter.TransactionLoggerMarkerFilter; +import org.slf4j.Marker; + +class LoggerMarkerFilterTest { + + private ILoggingEvent mockEvent; + private Marker mockMarker; + + @BeforeEach + void setUp() { + mockEvent = mock(ILoggingEvent.class); + mockMarker = mock(Marker.class); + } + + @Test + void testDecideAcceptWithMetricMarker() { + MetricLoggerMarkerFilter filter = new MetricLoggerMarkerFilter(); + when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(LoggerUtils.METRIC_LOG_MARKER)); + filter.start(); + + FilterReply reply = filter.decide(mockEvent); + assertEquals(FilterReply.ACCEPT, reply, "The filter should accept the event with the METRIC_LOG_MARKER."); + } + + @Test + void testDecideDenyWithoutMetricMarker() { + MetricLoggerMarkerFilter filter = new MetricLoggerMarkerFilter(); + when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(mockMarker)); + filter.start(); + + FilterReply reply = filter.decide(mockEvent); + assertEquals(FilterReply.DENY, reply, "The filter should deny the event without the METRIC_LOG_MARKER."); + } + + @Test + void testDecideAcceptWithSecurityMarker() { + SecurityLoggerMarkerFilter filter = new SecurityLoggerMarkerFilter(); + when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(LoggerUtils.SECURITY_LOG_MARKER)); + filter.start(); + + FilterReply reply = filter.decide(mockEvent); + assertEquals(FilterReply.ACCEPT, reply, "The filter should accept the event with the SECURITY_LOG_MARKER."); + } + + @Test + void testDecideDenyWithoutSecurityMarker() { + SecurityLoggerMarkerFilter filter = new SecurityLoggerMarkerFilter(); + when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(mockMarker)); + filter.start(); + + FilterReply reply = filter.decide(mockEvent); + assertEquals(FilterReply.DENY, reply, "The filter should deny the event without the SECURITY_LOG_MARKER."); + } + + @Test + void testDecideAcceptWithAuditMarker() { + AuditLoggerMarkerFilter filter = new AuditLoggerMarkerFilter(); + when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(LoggerUtils.AUDIT_LOG_MARKER)); + filter.start(); + + FilterReply reply = filter.decide(mockEvent); + assertEquals(FilterReply.ACCEPT, reply, "The filter should accept the event with the AUDIT_LOG_MARKER."); + } + + @Test + void testDecideDenyWithoutAuditMarker() { + AuditLoggerMarkerFilter filter = new AuditLoggerMarkerFilter(); + when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(mockMarker)); + filter.start(); + + FilterReply reply = filter.decide(mockEvent); + assertEquals(FilterReply.DENY, reply, "The filter should deny the event without the AUDIT_LOG_MARKER."); + } + + @Test + void testDecideAcceptWithTransactionMarker() { + TransactionLoggerMarkerFilter filter = new TransactionLoggerMarkerFilter(); + when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(LoggerUtils.TRANSACTION_LOG_MARKER)); + filter.start(); + + FilterReply reply = filter.decide(mockEvent); + assertEquals(FilterReply.ACCEPT, reply, "The filter should accept the event with the TRANSACTION_LOG_MARKER."); + } + + @Test + void testDecideDenyWithoutTransactionMarker() { + TransactionLoggerMarkerFilter filter = new TransactionLoggerMarkerFilter(); + when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(mockMarker)); + filter.start(); + + FilterReply reply = filter.decide(mockEvent); + assertEquals(FilterReply.DENY, reply, "The filter should deny the event without the TRANSACTION_LOG_MARKER."); + } + + @Test + void testDecideDenyWhenNotStarted() { + MetricLoggerMarkerFilter filter = new MetricLoggerMarkerFilter(); + when(mockEvent.getMarkerList()).thenReturn(Collections.singletonList(LoggerUtils.METRIC_LOG_MARKER)); + // Filter is not started + + FilterReply reply = filter.decide(mockEvent); + assertEquals(FilterReply.DENY, reply, "The filter should deny the event if the filter is not started."); + } + + @Test + void testDecideDenyWithNullEvent() { + MetricLoggerMarkerFilter filter = new MetricLoggerMarkerFilter(); + filter.start(); + + FilterReply reply = filter.decide(null); + assertEquals(FilterReply.DENY, reply, "The filter should deny if the event is null."); + } + + @Test + void testDecideDenyWithNullMarkerList() { + MetricLoggerMarkerFilter filter = new MetricLoggerMarkerFilter(); + when(mockEvent.getMarkerList()).thenReturn(null); + filter.start(); + + FilterReply reply = filter.decide(mockEvent); + assertEquals(FilterReply.DENY, reply, "The filter should deny if the marker list is null."); + } +} diff --git a/utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java index b62fd1e4..06b4f74f 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java @@ -21,7 +21,6 @@ package org.onap.policy.common.utils.properties; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; diff --git a/utils/src/test/java/org/onap/policy/common/utils/resources/PrometheusUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/resources/PrometheusUtilsTest.java new file mode 100644 index 00000000..a60b599e --- /dev/null +++ b/utils/src/test/java/org/onap/policy/common/utils/resources/PrometheusUtilsTest.java @@ -0,0 +1,37 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. + * ================================================================================ + * 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.policy.common.utils.resources; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class PrometheusUtilsTest { + + @Test + void test() { + PrometheusUtils.PdpType pdpa = PrometheusUtils.PdpType.PDPA; + PrometheusUtils.PdpType pdpd = PrometheusUtils.PdpType.PDPD; + PrometheusUtils.PdpType pdpx = PrometheusUtils.PdpType.PDPX; + + assertEquals("pdpa", pdpa.getNamespace(), "pdpa constructor"); + assertEquals("pdpd", pdpd.getNamespace(), "pdpd constructor"); + assertEquals("pdpx", pdpx.getNamespace(), "pdpx constructor"); + } +} diff --git a/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java b/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java index 5f8b80ea..5eec8a74 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java @@ -21,10 +21,14 @@ package org.onap.policy.common.utils.security; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import javax.crypto.spec.SecretKeySpec; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,6 +46,12 @@ class CryptoUtilsTest { private static final String ENCRYPTED_MSG = "original value : {} encrypted value: {}"; @Test + void testConstructor() { + SecretKeySpec skspecMock = mock(SecretKeySpec.class); + assertThatCode(() -> new CryptoUtils(skspecMock)).doesNotThrowAnyException(); + } + + @Test void testEncrypt() { logger.info("testEncrypt:"); CryptoCoder cryptoUtils = new CryptoUtils(SECRET_KEY); @@ -49,6 +59,8 @@ class CryptoUtilsTest { logger.info(ENCRYPTED_MSG, PASS, encryptedValue); assertTrue(encryptedValue.startsWith("enc:")); + assertTrue(CryptoUtils.isEncrypted(encryptedValue)); + String decryptedValue = cryptoUtils.decrypt(encryptedValue); logger.info(DECRYPTED_MSG, encryptedValue, decryptedValue); assertEquals(PASS, decryptedValue); @@ -61,6 +73,7 @@ class CryptoUtilsTest { String decryptedValue = cryptoUtils.decrypt(ENCRYPTED_PASS); logger.info(DECRYPTED_MSG, ENCRYPTED_PASS, decryptedValue); assertEquals(PASS, decryptedValue); + assertFalse(CryptoUtils.isEncrypted(decryptedValue)); } @Test @@ -120,4 +133,20 @@ class CryptoUtilsTest { String decryptedAgain = CryptoUtils.decrypt(decryptedValue, SECRET_KEY); assertEquals(decryptedValue, decryptedAgain); } + + @Test + void testMain() { + SecretKeySpec skspecMock = mock(SecretKeySpec.class); + new CryptoUtils(skspecMock); + + String[] stringsForTesting = new String[1]; + stringsForTesting[0] = "dec"; + assertThatCode(() -> CryptoUtils.main(stringsForTesting)).doesNotThrowAnyException(); + + stringsForTesting[0] = "enc"; + assertThatCode(() -> CryptoUtils.main(stringsForTesting)).doesNotThrowAnyException(); + + stringsForTesting[0] = "abc"; + assertThatCode(() -> CryptoUtils.main(stringsForTesting)).doesNotThrowAnyException(); + } } diff --git a/utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceTest.java b/utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceTest.java new file mode 100644 index 00000000..adac7cb0 --- /dev/null +++ b/utils/src/test/java/org/onap/policy/common/utils/services/OrderedServiceTest.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. + * ================================================================================ + * 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.policy.common.utils.services; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class OrderedServiceTest { + + @Test + void testGetSequenceNumber() { + // Anonymous class implementation for testing + OrderedService service = () -> 5; // Returns 5 as the sequence number + + // Test getSequenceNumber + assertEquals(5, service.getSequenceNumber(), "The sequence number should be 5"); + } + + @Test + void testGetName() { + // Anonymous class implementation for testing + OrderedService service = () -> 5; + + // Test getName + assertEquals(service.getClass().getName(), service.getName(), "The name should match the class name"); + } + + @Test + void testGetNameWithCustomImplementation() { + // Custom implementation of OrderedService + class CustomOrderedService implements OrderedService { + @Override + public int getSequenceNumber() { + return 10; + } + } + + OrderedService service = new CustomOrderedService(); + + // Test getName for custom implementation + assertEquals(service.getClass().getName(), service.getName(), + "The name should match the custom implementation class name"); + } +} + diff --git a/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java b/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java index d7dc44fb..19023124 100644 --- a/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java +++ b/utils/src/test/java/org/onap/policy/common/utils/validation/VersionTest.java @@ -52,6 +52,19 @@ class VersionTest { } @Test + void testConstructor() { + Version versionTest = new Version("1.0.2"); + assertEquals(1, versionTest.getMajor()); + assertEquals(0, versionTest.getMinor()); + assertEquals(2, versionTest.getPatch()); + + versionTest = new Version("null"); + assertEquals(0, versionTest.getMajor()); + assertEquals(0, versionTest.getMinor()); + assertEquals(0, versionTest.getPatch()); + } + + @Test void testMakeVersion() { assertEquals("9.8.7", Version.makeVersion(TYPE, NAME, "9.8.7").toString()); assertEquals("9.0.0", Version.makeVersion(TYPE, NAME, "9").toString()); |