diff options
Diffstat (limited to 'policy-endpoints/src/test/java/org/onap')
67 files changed, 617 insertions, 6689 deletions
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 deleted file mode 100644 index e47b2665..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/TopicEndpointProxyTest.java +++ /dev/null @@ -1,473 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. 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.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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import org.junit.After; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicFactories; -import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicPropertyBuilder; -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.event.comm.bus.UebTopicFactories; -import org.onap.policy.common.endpoints.event.comm.bus.UebTopicPropertyBuilder; -import org.onap.policy.common.endpoints.parameters.TopicParameterGroup; -import org.onap.policy.common.endpoints.parameters.TopicParameters; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; -import org.onap.policy.common.utils.gson.GsonTestUtils; - -public class TopicEndpointProxyTest { - - private static final String NOOP_SOURCE_TOPIC = "noop-source"; - private static final String NOOP_SINK_TOPIC = "noop-sink"; - - private static final String UEB_SOURCE_TOPIC = "ueb-source"; - private static final String UEB_SINK_TOPIC = "ueb-sink"; - - private static final String DMAAP_SOURCE_TOPIC = "dmaap-source"; - private static final String DMAAP_SINK_TOPIC = "dmaap-sink"; - - private Properties configuration = new Properties(); - private TopicParameterGroup group = new TopicParameterGroup(); - - /** - * Constructor. - */ - public TopicEndpointProxyTest() { - group.setTopicSinks(new LinkedList<>()); - group.setTopicSources(new LinkedList<>()); - - NoopTopicPropertyBuilder noopSourceBuilder = - new NoopTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_NOOP_SOURCE_TOPICS) - .makeTopic(NOOP_SOURCE_TOPIC); - configuration.putAll(noopSourceBuilder.build()); - group.getTopicSources().add(noopSourceBuilder.getParams()); - - NoopTopicPropertyBuilder noopSinkBuilder = - new NoopTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS) - .makeTopic(NOOP_SINK_TOPIC); - configuration.putAll(noopSinkBuilder.build()); - group.getTopicSinks().add(noopSinkBuilder.getParams()); - - UebTopicPropertyBuilder uebSourceBuilder = - new UebTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS) - .makeTopic(UEB_SOURCE_TOPIC); - configuration.putAll(uebSourceBuilder.build()); - group.getTopicSources().add(uebSourceBuilder.getParams()); - - UebTopicPropertyBuilder uebSinkBuilder = - new UebTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS) - .makeTopic(UEB_SINK_TOPIC); - configuration.putAll(uebSinkBuilder.build()); - group.getTopicSinks().add(uebSinkBuilder.getParams()); - - DmaapTopicPropertyBuilder dmaapSourceBuilder = - new DmaapTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS) - .makeTopic(DMAAP_SOURCE_TOPIC); - configuration.putAll(dmaapSourceBuilder.build()); - group.getTopicSources().add(dmaapSourceBuilder.getParams()); - - DmaapTopicPropertyBuilder dmaapSinkBuilder = - new DmaapTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS) - .makeTopic(DMAAP_SINK_TOPIC); - configuration.putAll(dmaapSinkBuilder.build()); - group.getTopicSinks().add(dmaapSinkBuilder.getParams()); - - TopicParameters invalidCommInfraParams = - new NoopTopicPropertyBuilder(PolicyEndPointProperties.PROPERTY_NOOP_SOURCE_TOPICS) - .makeTopic(NOOP_SOURCE_TOPIC).getParams(); - invalidCommInfraParams.setTopicCommInfrastructure(Topic.CommInfrastructure.REST.name()); - group.getTopicSources().add(invalidCommInfraParams); - group.getTopicSinks().add(invalidCommInfraParams); - } - - private <T extends Topic> boolean exists(List<T> topics, String topicName) { - return topics.stream().map(Topic::getTopic).anyMatch(topicName::equals); - } - - private <T extends Topic> boolean allSources(List<T> topics) { - return exists(topics, NOOP_SOURCE_TOPIC) && exists(topics, UEB_SOURCE_TOPIC) - && exists(topics, DMAAP_SOURCE_TOPIC); - } - - private <T extends Topic> boolean allSinks(List<T> topics) { - return exists(topics, NOOP_SINK_TOPIC) && exists(topics, UEB_SINK_TOPIC) && exists(topics, DMAAP_SINK_TOPIC); - } - - private <T extends Topic> boolean anySource(List<T> topics) { - return exists(topics, NOOP_SOURCE_TOPIC) || exists(topics, UEB_SOURCE_TOPIC) - || exists(topics, DMAAP_SOURCE_TOPIC); - } - - private <T extends Topic> boolean anySink(List<T> topics) { - return exists(topics, NOOP_SINK_TOPIC) || exists(topics, UEB_SINK_TOPIC) || exists(topics, DMAAP_SINK_TOPIC); - } - - /** - * Destroys all managed topics. - */ - @After - public void tearDown() { - NoopTopicFactories.getSinkFactory().destroy(); - NoopTopicFactories.getSourceFactory().destroy(); - - UebTopicFactories.getSinkFactory().destroy(); - UebTopicFactories.getSourceFactory().destroy(); - - DmaapTopicFactories.getSinkFactory().destroy(); - DmaapTopicFactories.getSourceFactory().destroy(); - } - - @Test - public void testSerialize() { - TopicEndpoint manager = new TopicEndpointProxy(); - - manager.addTopicSources(configuration); - manager.addTopicSinks(configuration); - - assertThatCode(() -> new GsonTestUtils().compareGson(manager, TopicEndpointProxyTest.class)) - .doesNotThrowAnyException(); - } - - @Test - public void testAddTopicSourcesListOfTopicParameters() { - TopicEndpoint manager = new TopicEndpointProxy(); - - List<TopicSource> sources = manager.addTopicSources(group.getTopicSources()); - assertSame(3, sources.size()); - - assertTrue(allSources(sources)); - assertFalse(anySink(sources)); - } - - @Test - public void testAddTopicSourcesProperties() { - TopicEndpoint manager = new TopicEndpointProxy(); - - List<TopicSource> sources = manager.addTopicSources(configuration); - assertSame(3, sources.size()); - - assertTrue(allSources(sources)); - assertFalse(anySink(sources)); - } - - @Test - public void testAddTopicSinksListOfTopicParameters() { - TopicEndpoint manager = new TopicEndpointProxy(); - - List<TopicSink> sinks = manager.addTopicSinks(group.getTopicSinks()); - assertSame(3, sinks.size()); - - assertFalse(anySource(sinks)); - assertTrue(allSinks(sinks)); - } - - @Test - public void testAddTopicSinksProperties() { - TopicEndpoint manager = new TopicEndpointProxy(); - - List<TopicSink> sinks = manager.addTopicSinks(configuration); - assertSame(3, sinks.size()); - - assertFalse(anySource(sinks)); - assertTrue(allSinks(sinks)); - } - - @Test - public void testAddTopicsProperties() { - TopicEndpoint manager = new TopicEndpointProxy(); - - List<Topic> topics = manager.addTopics(configuration); - assertSame(6, topics.size()); - - assertTrue(allSources(topics)); - assertTrue(allSinks(topics)); - } - - @Test - public void testAddTopicsTopicParameterGroup() { - TopicEndpoint manager = new TopicEndpointProxy(); - - List<Topic> topics = manager.addTopics(group); - assertSame(6, topics.size()); - - assertTrue(allSources(topics)); - assertTrue(allSinks(topics)); - } - - @Test - public void testAddTopicsTopicParameterGroupNull() { - TopicEndpoint manager = new TopicEndpointProxy(); - - List<Topic> topics = manager.addTopics(new TopicParameterGroup()); - assertEquals(0, topics.size()); - } - - @Test - public void testLockSinks_lockSources_locked() { - TopicEndpoint manager = new TopicEndpointProxy(); - manager.lock(); - for (Topic topic : manager.addTopics(group)) { - assertTrue(topic.isLocked()); - } - } - - @Test - public void testLockSinks_lockSources_unlocked() { - TopicEndpoint manager = new TopicEndpointProxy(); - for (Topic topic : manager.addTopics(group)) { - assertFalse(topic.isLocked()); - } - } - - @Test - public void testGetTopicSources() { - TopicEndpoint manager = new TopicEndpointProxy(); - - manager.addTopicSources(configuration); - manager.addTopicSinks(configuration); - - List<TopicSource> sources = manager.getTopicSources(); - assertSame(3, sources.size()); - - assertTrue(allSources(sources)); - assertFalse(anySink(sources)); - } - - @Test - public void testGetTopicSinks() { - TopicEndpoint manager = new TopicEndpointProxy(); - - manager.addTopicSources(configuration); - manager.addTopicSinks(configuration); - - List<TopicSink> sinks = manager.getTopicSinks(); - assertSame(3, sinks.size()); - - assertFalse(anySource(sinks)); - assertTrue(allSinks(sinks)); - } - - @Test - public void testGetUebTopicSources() { - TopicEndpoint manager = new TopicEndpointProxy(); - - manager.addTopicSources(configuration); - assertSame(1, manager.getUebTopicSources().size()); - } - - @Test - public void testGetDmaapTopicSources() { - TopicEndpoint manager = new TopicEndpointProxy(); - - manager.addTopicSources(configuration); - assertSame(1, manager.getDmaapTopicSources().size()); - } - - @Test - public void testGetNoopTopicSources() { - TopicEndpoint manager = new TopicEndpointProxy(); - - manager.addTopicSources(configuration); - assertSame(1, manager.getNoopTopicSources().size()); - } - - @Test - public void testGetUebTopicSinks() { - TopicEndpoint manager = new TopicEndpointProxy(); - - manager.addTopicSinks(configuration); - assertSame(1, manager.getUebTopicSinks().size()); - } - - @Test - public void testGetDmaapTopicSinks() { - TopicEndpoint manager = new TopicEndpointProxy(); - - manager.addTopicSinks(configuration); - assertSame(1, manager.getDmaapTopicSinks().size()); - } - - @Test - public void testGetNoopTopicSinks() { - TopicEndpoint manager = new TopicEndpointProxy(); - - manager.addTopicSinks(configuration); - assertSame(1, manager.getNoopTopicSinks().size()); - } - - @Test - public void testLifecycle() { - TopicEndpoint manager = new TopicEndpointProxy(); - - assertTrue(manager.start()); - assertTrue(manager.isAlive()); - - assertTrue(manager.stop()); - assertFalse(manager.isAlive()); - - assertTrue(manager.start()); - assertTrue(manager.isAlive()); - - manager.shutdown(); - assertFalse(manager.isAlive()); - } - - @Test - public void testLock() { - TopicEndpoint manager = new TopicEndpointProxy(); - - manager.lock(); - assertTrue(manager.isLocked()); - - manager.unlock(); - assertFalse(manager.isLocked()); - } - - @Test - public void testGetTopicSource() { - TopicEndpoint manager = new TopicEndpointProxy(); - manager.addTopicSources(configuration); - - assertSame(NOOP_SOURCE_TOPIC, manager.getTopicSource(CommInfrastructure.NOOP, NOOP_SOURCE_TOPIC).getTopic()); - assertSame(UEB_SOURCE_TOPIC, manager.getTopicSource(CommInfrastructure.UEB, UEB_SOURCE_TOPIC).getTopic()); - assertSame(DMAAP_SOURCE_TOPIC, manager.getTopicSource(CommInfrastructure.DMAAP, DMAAP_SOURCE_TOPIC).getTopic()); - - assertThatIllegalStateException() - .isThrownBy(() -> manager.getTopicSource(CommInfrastructure.NOOP, NOOP_SINK_TOPIC)); - assertThatIllegalStateException() - .isThrownBy(() -> manager.getTopicSource(CommInfrastructure.UEB, UEB_SINK_TOPIC)); - assertThatIllegalStateException() - .isThrownBy(() -> manager.getTopicSource(CommInfrastructure.DMAAP, DMAAP_SINK_TOPIC)); - } - - @Test - public void testGetTopicSink() { - TopicEndpoint manager = new TopicEndpointProxy(); - manager.addTopicSinks(configuration); - - assertSame(NOOP_SINK_TOPIC, manager.getTopicSink(CommInfrastructure.NOOP, NOOP_SINK_TOPIC).getTopic()); - assertSame(UEB_SINK_TOPIC, manager.getTopicSink(CommInfrastructure.UEB, UEB_SINK_TOPIC).getTopic()); - assertSame(DMAAP_SINK_TOPIC, manager.getTopicSink(CommInfrastructure.DMAAP, DMAAP_SINK_TOPIC).getTopic()); - - assertThatIllegalStateException() - .isThrownBy(() -> manager.getTopicSink(CommInfrastructure.NOOP, NOOP_SOURCE_TOPIC)); - assertThatIllegalStateException() - .isThrownBy(() -> manager.getTopicSink(CommInfrastructure.UEB, UEB_SOURCE_TOPIC)); - assertThatIllegalStateException() - .isThrownBy(() -> manager.getTopicSink(CommInfrastructure.DMAAP, DMAAP_SOURCE_TOPIC)); - } - - @Test - public void testGetUebTopicSource() { - TopicEndpoint manager = new TopicEndpointProxy(); - manager.addTopicSources(configuration); - - assertSame(UEB_SOURCE_TOPIC, manager.getUebTopicSource(UEB_SOURCE_TOPIC).getTopic()); - - assertThatIllegalStateException().isThrownBy(() -> manager.getUebTopicSource(NOOP_SOURCE_TOPIC)); - assertThatIllegalStateException().isThrownBy(() -> manager.getUebTopicSource(DMAAP_SOURCE_TOPIC)); - - assertThatIllegalArgumentException().isThrownBy(() -> manager.getUebTopicSource(null)); - assertThatIllegalArgumentException().isThrownBy(() -> manager.getUebTopicSource("")); - } - - @Test - public void testGetUebTopicSink() { - TopicEndpoint manager = new TopicEndpointProxy(); - manager.addTopicSinks(configuration); - - assertSame(UEB_SINK_TOPIC, manager.getUebTopicSink(UEB_SINK_TOPIC).getTopic()); - - assertThatIllegalStateException().isThrownBy(() -> manager.getUebTopicSink(NOOP_SINK_TOPIC)); - assertThatIllegalStateException().isThrownBy(() -> manager.getUebTopicSink(DMAAP_SINK_TOPIC)); - - assertThatIllegalArgumentException().isThrownBy(() -> manager.getUebTopicSink(null)); - assertThatIllegalArgumentException().isThrownBy(() -> manager.getUebTopicSink("")); - } - - @Test - public void testGetDmaapTopicSource() { - TopicEndpoint manager = new TopicEndpointProxy(); - manager.addTopicSources(configuration); - - assertSame(DMAAP_SOURCE_TOPIC, manager.getDmaapTopicSource(DMAAP_SOURCE_TOPIC).getTopic()); - - assertThatIllegalStateException().isThrownBy(() -> manager.getDmaapTopicSource(NOOP_SOURCE_TOPIC)); - assertThatIllegalStateException().isThrownBy(() -> manager.getDmaapTopicSource(UEB_SOURCE_TOPIC)); - - assertThatIllegalArgumentException().isThrownBy(() -> manager.getDmaapTopicSource(null)); - assertThatIllegalArgumentException().isThrownBy(() -> manager.getDmaapTopicSource("")); - } - - @Test - public void testGetDmaapTopicSink() { - TopicEndpoint manager = new TopicEndpointProxy(); - manager.addTopicSinks(configuration); - - assertSame(DMAAP_SINK_TOPIC, manager.getDmaapTopicSink(DMAAP_SINK_TOPIC).getTopic()); - - assertThatIllegalStateException().isThrownBy(() -> manager.getDmaapTopicSink(NOOP_SINK_TOPIC)); - assertThatIllegalStateException().isThrownBy(() -> manager.getDmaapTopicSink(UEB_SINK_TOPIC)); - - assertThatIllegalArgumentException().isThrownBy(() -> manager.getDmaapTopicSink(null)); - assertThatIllegalArgumentException().isThrownBy(() -> manager.getDmaapTopicSink("")); - } - - @Test - public void testGetNoopTopicSource() { - TopicEndpoint manager = new TopicEndpointProxy(); - manager.addTopicSources(configuration); - - assertSame(NOOP_SOURCE_TOPIC, manager.getNoopTopicSource(NOOP_SOURCE_TOPIC).getTopic()); - - assertThatIllegalStateException().isThrownBy(() -> manager.getNoopTopicSource(DMAAP_SOURCE_TOPIC)); - assertThatIllegalStateException().isThrownBy(() -> manager.getNoopTopicSource(UEB_SOURCE_TOPIC)); - - assertThatIllegalArgumentException().isThrownBy(() -> manager.getNoopTopicSource(null)); - assertThatIllegalArgumentException().isThrownBy(() -> manager.getNoopTopicSource("")); - } - - @Test - public void testGetNoopTopicSink() { - TopicEndpoint manager = new TopicEndpointProxy(); - manager.addTopicSinks(configuration); - - assertSame(NOOP_SINK_TOPIC, manager.getNoopTopicSink(NOOP_SINK_TOPIC).getTopic()); - - assertThatIllegalStateException().isThrownBy(() -> manager.getNoopTopicSink(DMAAP_SINK_TOPIC)); - assertThatIllegalStateException().isThrownBy(() -> manager.getNoopTopicSink(UEB_SINK_TOPIC)); - - assertThatIllegalArgumentException().isThrownBy(() -> manager.getNoopTopicSink(null)); - assertThatIllegalArgumentException().isThrownBy(() -> manager.getNoopTopicSink("")); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java deleted file mode 100644 index 7a819e0d..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/BusTopicFactoryTestBase.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX; - -import java.util.Arrays; -import java.util.List; -import java.util.Properties; -import java.util.function.Predicate; -import org.onap.policy.common.endpoints.event.comm.Topic; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; - -/** - * Base class for Topic Factory tests that use BusTopicParams. - * - * @param <T> type of topic managed by the factory - */ -public abstract class BusTopicFactoryTestBase<T extends Topic> extends TopicFactoryTestBase<T> { - - /** - * Builds a topic. - * - * @param params the parameters used to configure the topic - * @return a new topic - */ - protected abstract T buildTopic(BusTopicParams params); - - /** - * Builds a topic. - * - * @param servers list of servers - * @param topic the topic name - * @return a new topic - */ - protected abstract T buildTopic(List<String> servers, String topic); - - /** - * Gets the parameters used to build the most recent topic. - * - * @return the most recent topic's parameters - */ - protected abstract BusTopicParams getLastParams(); - - /** - * Tests building a topic using BusTopicParams. - */ - public void testBuildBusTopicParams() { - initFactory(); - - // two unmanaged topics - T item = buildTopic(makeBuilder().managed(false).effectiveTopic(null).build()); - T item2 = buildTopic(makeBuilder().managed(false).topic(TOPIC2).build()); - assertNotNull(item); - assertNotNull(item2); - assertEquals(item.getTopic(), item.getEffectiveTopic()); - assertNotEquals(item2.getTopic(), item2.getEffectiveTopic()); - assertNotSame(item, item2); - - // duplicate topics, but since they aren't managed, they should be different - T item3 = buildTopic(makeBuilder().managed(false).build()); - T item4 = buildTopic(makeBuilder().managed(false).effectiveTopic(TOPIC2).build()); - assertNotNull(item3); - assertNotNull(item4); - assertEquals(MY_TOPIC, item4.getTopic()); - assertEquals(TOPIC2, item4.getEffectiveTopic()); - assertNotSame(item, item3); - assertNotSame(item, item4); - assertNotSame(item3, item4); - - // two managed topics - T item5 = buildTopic(makeBuilder().build()); - T item6 = buildTopic(makeBuilder().topic(TOPIC2).build()); - assertNotNull(item5); - assertNotNull(item6); - - // re-build same managed topics - should get exact same objects - assertSame(item5, buildTopic(makeBuilder().topic(MY_TOPIC).build())); - assertSame(item6, buildTopic(makeBuilder().topic(TOPIC2).build())); - } - - /** - * Tests exception cases when building a topic using BusTopicParams. - */ - public void testBuildBusTopicParams_Ex() { - // null topic - assertThatIllegalArgumentException().isThrownBy(() -> buildTopic(makeBuilder().topic(null).build())); - - // empty topic - assertThatIllegalArgumentException().isThrownBy(() -> buildTopic(makeBuilder().topic("").build())); - } - - /** - * Tests building a topic using a list of servers and a topic. - */ - public void testBuildListOfStringString() { - initFactory(); - - T item1 = buildTopic(servers, MY_TOPIC); - assertNotNull(item1); - - // check parameters that were used - BusTopicParams params = getLastParams(); - assertEquals(servers, params.getServers()); - assertEquals(MY_TOPIC, params.getTopic()); - assertEquals(true, params.isManaged()); - assertEquals(false, params.isUseHttps()); - - T item2 = buildTopic(servers, TOPIC2); - assertNotNull(item2); - assertNotSame(item1, item2); - - // duplicate - should be the same, as these topics are managed - T item3 = buildTopic(servers, TOPIC2); - assertSame(item2, item3); - } - - /** - * Tests building a topic using Properties. Verifies parameters specific to Bus - * topics. - */ - public void testBuildProperties() { - initFactory(); - - List<T> topics = buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build()); - assertEquals(1, topics.size()); - assertEquals(MY_TOPIC, topics.get(0).getTopic()); - assertEquals(MY_EFFECTIVE_TOPIC, topics.get(0).getEffectiveTopic()); - - BusTopicParams params = getLastParams(); - assertEquals(true, params.isManaged()); - assertEquals(true, params.isUseHttps()); - assertEquals(true, params.isAllowSelfSignedCerts()); - assertEquals(MY_API_KEY, params.getApiKey()); - assertEquals(MY_API_SECRET, params.getApiSecret()); - assertEquals(Arrays.asList(SERVER), params.getServers()); - assertEquals(MY_TOPIC, params.getTopic()); - assertEquals(MY_EFFECTIVE_TOPIC, params.getEffectiveTopic()); - - List<T> topics2 = buildTopics(makePropBuilder().makeTopic(TOPIC3) - .removeTopicProperty(PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX).build()); - assertEquals(1, topics2.size()); - assertEquals(TOPIC3, topics2.get(0).getTopic()); - assertEquals(topics2.get(0).getTopic(), topics2.get(0).getEffectiveTopic()); - } - - @Override - public void testBuildProperties_Variations() { - super.testBuildProperties_Variations(); - - // check boolean properties that default to true - checkDefault(PROPERTY_MANAGED_SUFFIX, BusTopicParams::isManaged); - - // check boolean properties that default to false - checkDefault(PROPERTY_HTTP_HTTPS_SUFFIX, params -> !params.isUseHttps()); - checkDefault(PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX, params -> !params.isAllowSelfSignedCerts()); - } - - /** - * Verifies that a parameter has the correct default, if the original builder property - * is not provided. - * - * @param builderName name of the builder property - * @param validate function to test the validity of the property - * @param values the values to which the property should be set, defaults to - * {@code null} and "" - */ - protected void checkDefault(String builderName, Predicate<BusTopicParams> validate, Object... values) { - Object[] values2 = (values.length > 0 ? values : new Object[] {null, ""}); - - for (Object value : values2) { - // always start with a fresh factory - initFactory(); - - TopicPropertyBuilder builder = makePropBuilder().makeTopic(MY_TOPIC); - - if (value == null) { - builder.removeTopicProperty(builderName); - - } else { - builder.setTopicProperty(builderName, value.toString()); - } - - assertEquals("size for default " + value, 1, buildTopics(builder.build()).size()); - assertTrue("default for " + value, validate.test(getLastParams())); - } - } - - /** - * Verifies that an "additional" property does not exist, if the original builder - * property is not provided. - * - * @param builderName name of the builder property - * @param addName name of the "additional" property - */ - protected void expectNullAddProp(String builderName, String addName) { - - // remove the property - initFactory(); - Properties props = makePropBuilder().makeTopic(MY_TOPIC).removeTopicProperty(builderName).build(); - assertEquals(1, buildTopics(props).size()); - assertFalse(getLastParams().getAdditionalProps().containsKey(addName)); - - - // repeat, this time using an empty string instead of null - initFactory(); - props = makePropBuilder().makeTopic(MY_TOPIC).setTopicProperty(builderName, "").build(); - assertEquals(1, buildTopics(props).size()); - assertFalse(getLastParams().getAdditionalProps().containsKey(addName)); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicFactoryTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicFactoryTestBase.java deleted file mode 100644 index 92d5a865..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicFactoryTestBase.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_VERSION_SUFFIX; - -import java.util.Map; -import org.onap.policy.common.endpoints.event.comm.Topic; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; - -/** - * Base class for DmaapTopicXxxFactory tests. - * - * @param <T> type of topic managed by the factory - */ -public abstract class DmaapTopicFactoryTestBase<T extends Topic> extends BusTopicFactoryTestBase<T> { - - public static final String MY_CONN_TIMEOUT = "200"; - public static final String MY_READ_TIMEOUT = "201"; - public static final String MY_ROUNDTRIP_TIMEOUT = "202"; - public static final String MY_STICKINESS = "true"; - public static final String MY_SUBCONTEXT = "my-subcontext"; - public static final String MY_DME_VERSION = "my-version"; - - @Override - public void testBuildProperties() { - - super.testBuildProperties(); - - // check properties specific to DMaaP/DME2 - initFactory(); - - assertEquals(1, buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build()).size()); - - BusTopicParams params = getLastParams(); - assertEquals(MY_ENV, params.getEnvironment()); - assertEquals(MY_LAT, params.getLatitude()); - assertEquals(MY_LONG, params.getLongitude()); - assertEquals(MY_PARTNER, params.getPartner()); - - Map<String, String> add = params.getAdditionalProps(); - assertEquals(MY_CONN_TIMEOUT, add.get(PolicyEndPointProperties.DME2_EP_CONN_TIMEOUT_PROPERTY)); - assertEquals(MY_READ_TIMEOUT, add.get(PolicyEndPointProperties.DME2_READ_TIMEOUT_PROPERTY)); - assertEquals(MY_ROUNDTRIP_TIMEOUT, add.get(PolicyEndPointProperties.DME2_ROUNDTRIP_TIMEOUT_PROPERTY)); - assertEquals(MY_ROUTE, add.get(PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY)); - assertEquals(MY_STICKINESS, add.get(PolicyEndPointProperties.DME2_SESSION_STICKINESS_REQUIRED_PROPERTY)); - assertEquals(MY_SUBCONTEXT, add.get(PolicyEndPointProperties.DME2_SUBCONTEXT_PATH_PROPERTY)); - assertEquals(MY_DME_VERSION, add.get(PolicyEndPointProperties.DME2_VERSION_PROPERTY)); - } - - @Override - public void testBuildProperties_Variations() { - super.testBuildProperties_Variations(); - - // check "additional" properties - expectNullAddProp(PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX, - PolicyEndPointProperties.DME2_EP_CONN_TIMEOUT_PROPERTY); - - expectNullAddProp(PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX, - PolicyEndPointProperties.DME2_READ_TIMEOUT_PROPERTY); - - expectNullAddProp(PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX, - PolicyEndPointProperties.DME2_ROUNDTRIP_TIMEOUT_PROPERTY); - - expectNullAddProp(PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX, PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY); - - expectNullAddProp(PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX, - PolicyEndPointProperties.DME2_SESSION_STICKINESS_REQUIRED_PROPERTY); - - expectNullAddProp(PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX, - PolicyEndPointProperties.DME2_SUBCONTEXT_PATH_PROPERTY); - - expectNullAddProp(PROPERTY_DMAAP_DME2_VERSION_SUFFIX, PolicyEndPointProperties.DME2_VERSION_PROPERTY); - } - - @Override - public void testBuildListOfStringString() { - super.testBuildListOfStringString(); - - // check parameters that were used - BusTopicParams params = getLastParams(); - assertEquals(false, params.isAllowSelfSignedCerts()); - } - - /** - * Tests exception cases with get(topic). DMaaP topics are special in that they - * throw IllegalArgumentException, even for an unknown topic name; all of the - * other Topic Factory classes throw IllegalStateException, thus we override - * the default test method. - */ - @Override - public void testGet_Ex() { - // null topic - assertThatIllegalArgumentException().as("null topic").isThrownBy(() -> getTopic(null)); - - // empty topic - assertThatIllegalArgumentException().as("empty topic").isThrownBy(() -> getTopic("")); - - // unknown topic - initFactory(); - buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build()); - - assertThatIllegalStateException().as("unknown topic").isThrownBy(() -> getTopic(TOPIC2)); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicPropertyBuilder.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicPropertyBuilder.java deleted file mode 100644 index 2e9a6cd7..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicPropertyBuilder.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_AFT_ENV; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_API_KEY; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_API_SECRET; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_CONS_GROUP; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_CONS_INST; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_EFFECTIVE_TOPIC; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_ENV; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_FETCH_LIMIT; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_FETCH_TIMEOUT; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_LAT; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_LONG; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_PARTITION; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_PARTNER; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_ROUTE; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_VERSION_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_API_KEY_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_API_SECRET_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX; - -import java.util.Arrays; -import lombok.Getter; -import org.onap.policy.common.endpoints.parameters.TopicParameters; - -public class DmaapTopicPropertyBuilder extends TopicPropertyBuilder { - - public static final String SERVER = "my-server"; - public static final String TOPIC2 = "my-topic-2"; - - public static final String MY_CONN_TIMEOUT = "200"; - public static final String MY_READ_TIMEOUT = "201"; - public static final String MY_ROUNDTRIP_TIMEOUT = "202"; - public static final String MY_STICKINESS = "true"; - public static final String MY_SUBCONTEXT = "my-subcontext"; - public static final String MY_DME_VERSION = "my-version"; - public static final String MY_AAF_MECHID = "my-aaf-mechid"; - public static final String MY_AAF_PASS = "my-aaf-passwd"; - - @Getter - private TopicParameters params = new TopicParameters(); - - /** - * Constructs the object. - * - * @param prefix the prefix for the properties to be built - */ - public DmaapTopicPropertyBuilder(String prefix) { - super(prefix); - } - - /** - * Adds a topic and configures it's properties with default values. - * - * @param topic the topic to be added - * @return this builder - */ - public DmaapTopicPropertyBuilder makeTopic(String topic) { - addTopic(topic); - - setTopicProperty(PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX, MY_EFFECTIVE_TOPIC); - setTopicProperty(PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX, MY_CONS_GROUP); - setTopicProperty(PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX, MY_CONS_INST); - setTopicProperty(PROPERTY_MANAGED_SUFFIX, "true"); - setTopicProperty(PROPERTY_HTTP_HTTPS_SUFFIX, "true"); - setTopicProperty(PROPERTY_TOPIC_AAF_MECHID_SUFFIX, MY_AAF_MECHID); - setTopicProperty(PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX, MY_AAF_PASS); - setTopicProperty(PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX, MY_AFT_ENV); - setTopicProperty(PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX, "true"); - setTopicProperty(PROPERTY_TOPIC_API_KEY_SUFFIX, MY_API_KEY); - setTopicProperty(PROPERTY_TOPIC_API_SECRET_SUFFIX, MY_API_SECRET); - setTopicProperty(PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX, MY_FETCH_LIMIT); - setTopicProperty(PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX, MY_FETCH_TIMEOUT); - setTopicProperty(PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX, MY_CONN_TIMEOUT); - setTopicProperty(PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX, MY_ENV); - setTopicProperty(PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX, MY_LAT); - setTopicProperty(PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX, MY_LONG); - setTopicProperty(PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX, MY_PARTITION); - setTopicProperty(PROPERTY_DMAAP_DME2_PARTNER_SUFFIX, MY_PARTNER); - setTopicProperty(PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX, MY_READ_TIMEOUT); - setTopicProperty(PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX, MY_ROUNDTRIP_TIMEOUT); - setTopicProperty(PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX, MY_ROUTE); - setTopicProperty(PROPERTY_TOPIC_SERVERS_SUFFIX, SERVER); - setTopicProperty(PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX, MY_STICKINESS); - setTopicProperty(PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX, MY_SUBCONTEXT); - setTopicProperty(PROPERTY_DMAAP_DME2_VERSION_SUFFIX, MY_DME_VERSION); - - params.setTopicCommInfrastructure("dmaap"); - params.setTopic(topic); - params.setEffectiveTopic(MY_EFFECTIVE_TOPIC); - params.setConsumerGroup(MY_CONS_GROUP); - params.setConsumerInstance(MY_CONS_INST); - params.setManaged(true); - params.setUseHttps(true); - params.setUserName(MY_AAF_MECHID); - params.setPassword(MY_AAF_PASS); - params.setAftEnvironment(MY_AFT_ENV); - params.setAllowSelfSignedCerts(true); - params.setApiKey(MY_API_KEY); - params.setApiSecret(MY_API_SECRET); - params.setFetchLimit(MY_FETCH_LIMIT); - params.setFetchTimeout(MY_FETCH_TIMEOUT); - params.setEnvironment(MY_ENV); - params.setLatitude(MY_LAT); - params.setLongitude(MY_LONG); - params.setPartitionId(MY_PARTITION); - params.setPartner(MY_PARTNER); - params.setServers(Arrays.asList(SERVER)); - - return this; - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java deleted file mode 100644 index 6c9dfcbd..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkFactoryTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS; - -import java.util.Deque; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; - -public class DmaapTopicSinkFactoryTest extends DmaapTopicFactoryTestBase<DmaapTopicSink> { - - private SinkFactory factory; - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - factory = new SinkFactory(); - } - - @After - public void tearDown() { - factory.destroy(); - } - - @Test - @Override - public void testBuildBusTopicParams() { - super.testBuildBusTopicParams(); - super.testBuildBusTopicParams_Ex(); - } - - @Test - @Override - public void testBuildListOfStringString() { - super.testBuildListOfStringString(); - } - - @Test - @Override - public void testBuildProperties() { - super.testBuildProperties(); - super.testBuildProperties_Variations(); - super.testBuildProperties_Multiple(); - - // check sink-specific parameters that were used - BusTopicParams params = factory.params.getFirst(); - assertEquals(MY_PARTITION, params.getPartitionId()); - } - - @Test - @Override - public void testDestroyString_testGet_testInventory() { - super.testDestroyString_testGet_testInventory(); - super.testDestroyString_Ex(); - } - - @Test - @Override - public void testDestroy() { - super.testDestroy(); - } - - @Test - public void testGet() { - super.testGet_Ex(); - } - - @Test - public void testToString() { - assertTrue(factory.toString().startsWith("IndexedDmaapTopicSinkFactory [")); - } - - @Override - protected void initFactory() { - if (factory != null) { - factory.destroy(); - } - - factory = new SinkFactory(); - } - - @Override - protected List<DmaapTopicSink> buildTopics(Properties properties) { - return factory.build(properties); - } - - @Override - protected DmaapTopicSink buildTopic(BusTopicParams params) { - return factory.build(params); - } - - @Override - protected DmaapTopicSink buildTopic(List<String> servers, String topic) { - return factory.build(servers, topic); - } - - @Override - protected void destroyFactory() { - factory.destroy(); - } - - @Override - protected void destroyTopic(String topic) { - factory.destroy(topic); - } - - @Override - protected List<DmaapTopicSink> getInventory() { - return factory.inventory(); - } - - @Override - protected DmaapTopicSink getTopic(String topic) { - return factory.get(topic); - } - - @Override - protected BusTopicParams getLastParams() { - return factory.params.getLast(); - } - - @Override - protected TopicPropertyBuilder makePropBuilder() { - return new DmaapTopicPropertyBuilder(PROPERTY_DMAAP_SINK_TOPICS); - } - - /** - * Factory that records the parameters of all of the sinks it creates. - */ - private static class SinkFactory extends IndexedDmaapTopicSinkFactory { - private Deque<BusTopicParams> params = new LinkedList<>(); - - @Override - protected DmaapTopicSink makeSink(BusTopicParams busTopicParams) { - params.add(busTopicParams); - return super.makeSink(busTopicParams); - } - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkTest.java deleted file mode 100644 index 9136108a..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSinkTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP Policy Engine - Common Modules - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -public class DmaapTopicSinkTest { - - @Test - public void test() { - assertNotNull(DmaapTopicFactories.getSinkFactory()); - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java deleted file mode 100644 index b4c2f758..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceFactoryTest.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP Policy Engine - Common Modules - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX; - -import java.util.Deque; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; - -public class DmaapTopicSourceFactoryTest extends DmaapTopicFactoryTestBase<DmaapTopicSource> { - - private SourceFactory factory; - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - factory = new SourceFactory(); - } - - @After - public void tearDown() { - factory.destroy(); - } - - @Test - @Override - public void testBuildBusTopicParams() { - super.testBuildBusTopicParams(); - super.testBuildBusTopicParams_Ex(); - } - - @Test - @Override - public void testBuildProperties() { - super.testBuildProperties(); - - // check source-specific parameters that were used - BusTopicParams params = factory.params.getFirst(); - assertEquals(MY_CONS_GROUP, params.getConsumerGroup()); - assertEquals(MY_CONS_INST, params.getConsumerInstance()); - assertEquals(MY_FETCH_LIMIT, params.getFetchLimit()); - assertEquals(MY_FETCH_TIMEOUT, params.getFetchTimeout()); - - super.testBuildProperties_Variations(); - super.testBuildProperties_Multiple(); - - // check default values for source-specific parameters - checkDefault(PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX, - params2 -> params2.getFetchLimit() == PolicyEndPointProperties.DEFAULT_LIMIT_FETCH, - null, "", "invalid-limit-number"); - - checkDefault(PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX, - params2 -> params2.getFetchTimeout() == PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH, - null, "", "invalid-timeout-number"); - } - - @Test - public void testBuildListOfStringStringStringString() { - DmaapTopicSource source1 = factory.build(servers, MY_TOPIC, MY_API_KEY, MY_API_SECRET); - assertNotNull(source1); - - // check source-specific parameters that were used - BusTopicParams params = factory.params.getFirst(); - assertEquals(MY_API_KEY, params.getApiKey()); - assertEquals(MY_API_SECRET, params.getApiSecret()); - assertEquals(PolicyEndPointProperties.DEFAULT_LIMIT_FETCH, params.getFetchLimit()); - assertEquals(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH, params.getFetchTimeout()); - } - - @Test - @Override - public void testBuildListOfStringString() { - super.testBuildListOfStringString(); - - // check source-specific parameters that were used - BusTopicParams params = factory.params.getFirst(); - assertEquals(null, params.getApiKey()); - assertEquals(null, params.getApiSecret()); - assertEquals(PolicyEndPointProperties.DEFAULT_LIMIT_FETCH, params.getFetchLimit()); - assertEquals(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH, params.getFetchTimeout()); - } - - @Test - @Override - public void testDestroyString_testGet_testInventory() { - super.testDestroyString_testGet_testInventory(); - super.testDestroyString_Ex(); - } - - @Test - @Override - public void testDestroy() { - super.testDestroy(); - } - - @Test - public void testGet() { - super.testGet_Ex(); - } - - @Test - public void testToString() { - assertTrue(factory.toString().startsWith("IndexedDmaapTopicSourceFactory [")); - } - - @Override - protected void initFactory() { - if (factory != null) { - factory.destroy(); - } - - factory = new SourceFactory(); - } - - @Override - protected List<DmaapTopicSource> buildTopics(Properties properties) { - return factory.build(properties); - } - - @Override - protected DmaapTopicSource buildTopic(BusTopicParams params) { - return factory.build(params); - } - - @Override - protected DmaapTopicSource buildTopic(List<String> servers, String topic) { - return factory.build(servers, topic); - } - - @Override - protected void destroyFactory() { - factory.destroy(); - } - - @Override - protected void destroyTopic(String topic) { - factory.destroy(topic); - } - - @Override - protected List<DmaapTopicSource> getInventory() { - return factory.inventory(); - } - - @Override - protected DmaapTopicSource getTopic(String topic) { - return factory.get(topic); - } - - @Override - protected BusTopicParams getLastParams() { - return factory.params.getLast(); - } - - @Override - protected TopicPropertyBuilder makePropBuilder() { - return new DmaapTopicPropertyBuilder(PROPERTY_DMAAP_SOURCE_TOPICS); - } - - /** - * Factory that records the parameters of all of the sources it creates. - */ - private static class SourceFactory extends IndexedDmaapTopicSourceFactory { - private Deque<BusTopicParams> params = new LinkedList<>(); - - @Override - protected DmaapTopicSource makeSource(BusTopicParams busTopicParams) { - params.add(busTopicParams); - return super.makeSource(busTopicParams); - } - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceTest.java deleted file mode 100644 index 1735e2ee..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/DmaapTopicSourceTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP Policy Engine - Common Modules - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -public class DmaapTopicSourceTest { - - @Test - public void test() { - assertNotNull(DmaapTopicFactories.getSourceFactory()); - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpointTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpointTest.java deleted file mode 100644 index 6cdb628a..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicEndpointTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import java.util.Arrays; -import java.util.Collections; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicListener; - -public abstract class NoopTopicEndpointTest<F extends NoopTopicFactory<T>, T extends NoopTopicEndpoint> - extends TopicTestBase { - - protected final F factory; - protected T endpoint; - - public NoopTopicEndpointTest(F factory) { - this.factory = factory; - } - - protected abstract boolean io(String message); - - @Before - @Override - public void setUp() { - super.setUp(); - this.endpoint = this.factory.build(servers, MY_TOPIC); - } - - @Test - public void testIo() { - TopicListener listener = mock(TopicListener.class); - this.endpoint.register(listener); - this.endpoint.start(); - - assertTrue(io(MY_MESSAGE)); - assertSame(MY_MESSAGE, this.endpoint.getRecentEvents()[0]); - assertEquals(Collections.singletonList(MY_MESSAGE), Arrays.asList(this.endpoint.getRecentEvents())); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE); - - this.endpoint.unregister(listener); - } - - @Test(expected = IllegalArgumentException.class) - public void testIoNullMessage() { - io(null); - } - - @Test(expected = IllegalArgumentException.class) - public void testIoEmptyMessage() { - io(""); - } - - @Test(expected = IllegalStateException.class) - public void testOfferNotStarted() { - io(MY_MESSAGE); - } - - @Test - public void testGetTopicCommInfrastructure() { - assertEquals(CommInfrastructure.NOOP, this.endpoint.getTopicCommInfrastructure()); - } - - @Test - public void testStart_testStop_testShutdown() { - this.endpoint.start(); - assertTrue(this.endpoint.isAlive()); - - // start again - this.endpoint.start(); - assertTrue(this.endpoint.isAlive()); - - // stop - this.endpoint.stop(); - assertFalse(this.endpoint.isAlive()); - - // re-start again - this.endpoint.start(); - assertTrue(this.endpoint.isAlive()); - - // shutdown - this.endpoint.shutdown(); - assertFalse(this.endpoint.isAlive()); - } - - @Test(expected = IllegalStateException.class) - public void testStart_Locked() { - this.endpoint.lock(); - this.endpoint.start(); - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactoryTest.java deleted file mode 100644 index af7a4b29..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicFactoryTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; - -public abstract class NoopTopicFactoryTest<F extends NoopTopicFactory<T>, T extends NoopTopicEndpoint> - extends TopicFactoryTestBase<T> { - - private static final List<String> NOOP_SERVERS = Arrays.asList(CommInfrastructure.NOOP.toString()); - private F factory = null; - - protected abstract F buildFactory(); - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - initFactory(); - } - - @After - public void tearDown() { - factory.destroy(); - } - - @Test - public void testBuildBusTopicParams() { - initFactory(); - - T item1 = buildTopic(makeParams(servers, MY_TOPIC, true)); - assertNotNull(item1); - - assertEquals(servers, item1.getServers()); - assertEquals(MY_TOPIC, item1.getTopic()); - } - - @Test - public void testBuildListOfStringStringBoolean() { - initFactory(); - - T item1 = buildTopic(servers, MY_TOPIC, true); - assertNotNull(item1); - - assertEquals(servers, item1.getServers()); - assertEquals(MY_TOPIC, item1.getTopic()); - - // managed topic - should not build a new one - assertEquals(item1, buildTopic(servers, MY_TOPIC, true)); - - T item2 = buildTopic(servers, TOPIC2, true); - assertNotNull(item2); - assertNotSame(item1, item2); - - // duplicate - should be the same, as these topics are managed - List<String> randomServers = new ArrayList<>(); - randomServers.add(RandomStringUtils.randomAlphanumeric(8)); - T item3 = buildTopic(randomServers, TOPIC2, true); - assertSame(item2, item3); - - T item4 = buildTopic(Collections.emptyList(), TOPIC2, true); - assertSame(item3, item4); - - // null server list - initFactory(); - assertEquals(NOOP_SERVERS, buildTopic(null, MY_TOPIC, true).getServers()); - - // empty server list - initFactory(); - assertEquals(NOOP_SERVERS, buildTopic(Collections.emptyList(), MY_TOPIC, true).getServers()); - - // unmanaged topic - initFactory(); - item1 = buildTopic(servers, MY_TOPIC, false); - assertNotSame(item1, buildTopic(servers, MY_TOPIC, false)); - } - - @Test(expected = IllegalArgumentException.class) - public void testBuildListOfStringStringBoolean_NullTopic() { - buildTopic(servers, null, true); - } - - @Test(expected = IllegalArgumentException.class) - public void testBuildListOfStringStringBoolean_EmptyTopic() { - buildTopic(servers, "", true); - } - - @Test - public void testBuildProperties() { - // managed topic - initFactory(); - assertEquals(1, buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build()).size()); - assertNotNull(factory.get(MY_TOPIC)); - - // unmanaged topic - get() will throw an exception - initFactory(); - assertEquals(1, buildTopics(makePropBuilder().makeTopic(MY_TOPIC) - .setTopicProperty(PROPERTY_MANAGED_SUFFIX, "false").build()).size()); - assertThatIllegalStateException().isThrownBy(() -> factory.get(MY_TOPIC)); - - // managed undefined - default to true - initFactory(); - assertEquals(1, buildTopics( - makePropBuilder().makeTopic(MY_TOPIC).removeTopicProperty(PROPERTY_MANAGED_SUFFIX).build()) - .size()); - assertNotNull(factory.get(MY_TOPIC)); - - // managed empty - default to true - initFactory(); - assertEquals(1, buildTopics( - makePropBuilder().makeTopic(MY_TOPIC).setTopicProperty(PROPERTY_MANAGED_SUFFIX, "").build()) - .size()); - assertNotNull(factory.get(MY_TOPIC)); - - initFactory(); - - // null topic list - assertTrue(buildTopics(makePropBuilder().build()).isEmpty()); - - // empty topic list - assertTrue(buildTopics(makePropBuilder().addTopic("").build()).isEmpty()); - - // null server list - initFactory(); - T endpoint = buildTopics(makePropBuilder().makeTopic(MY_TOPIC) - .removeTopicProperty(PROPERTY_TOPIC_SERVERS_SUFFIX).build()).get(0); - assertEquals(NOOP_SERVERS, endpoint.getServers()); - - // empty server list - initFactory(); - endpoint = buildTopics(makePropBuilder().makeTopic(MY_TOPIC).setTopicProperty(PROPERTY_TOPIC_SERVERS_SUFFIX, "") - .build()).get(0); - assertEquals(NOOP_SERVERS, endpoint.getServers()); - - // test other options - super.testBuildProperties_Multiple(); - } - - @Test - @Override - public void testDestroyString_testGet_testInventory() { - super.testDestroyString_testGet_testInventory(); - super.testDestroyString_Ex(); - } - - @Test - @Override - public void testDestroy() { - super.testDestroy(); - } - - @Test - public void testGet() { - super.testGet_Ex(); - } - - @Override - protected void initFactory() { - if (factory != null) { - factory.destroy(); - } - - factory = buildFactory(); - } - - @Override - protected List<T> buildTopics(Properties properties) { - return factory.build(properties); - } - - protected T buildTopic(BusTopicParams param) { - return factory.build(param); - } - - protected T buildTopic(List<String> servers, String topic, boolean managed) { - return factory.build(servers, topic, managed); - } - - @Override - protected void destroyFactory() { - factory.destroy(); - } - - @Override - protected void destroyTopic(String topic) { - factory.destroy(topic); - } - - @Override - protected List<T> getInventory() { - return factory.inventory(); - } - - @Override - protected T getTopic(String topic) { - return factory.get(topic); - } - - @Override - protected TopicPropertyBuilder makePropBuilder() { - return new NoopTopicPropertyBuilder(factory.getTopicsPropertyName()); - } - - private BusTopicParams makeParams(List<String> servers, String topic, boolean managed) { - BusTopicParams params = new BusTopicParams(); - - params.setServers(servers); - params.setTopic(topic); - params.setManaged(managed); - - return params; - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicPropertyBuilder.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicPropertyBuilder.java deleted file mode 100644 index 3f0553f8..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicPropertyBuilder.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_EFFECTIVE_TOPIC; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; - -import java.util.Arrays; -import lombok.Getter; -import org.onap.policy.common.endpoints.parameters.TopicParameters; - -public class NoopTopicPropertyBuilder extends TopicPropertyBuilder { - - public static final String SERVER = "my-server"; - public static final String TOPIC2 = "my-topic-2"; - - @Getter - private TopicParameters params = new TopicParameters(); - - /** - * Constructs the object. - * - * @param prefix the prefix for the properties to be built - */ - public NoopTopicPropertyBuilder(String prefix) { - super(prefix); - } - - /** - * Adds a topic and configures it's properties with default values. - * - * @param topic the topic to be added - * @return this builder - */ - public NoopTopicPropertyBuilder makeTopic(String topic) { - addTopic(topic); - - setTopicProperty(PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX, MY_EFFECTIVE_TOPIC); - setTopicProperty(PROPERTY_MANAGED_SUFFIX, "true"); - setTopicProperty(PROPERTY_HTTP_HTTPS_SUFFIX, "true"); - setTopicProperty(PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX, "true"); - setTopicProperty(PROPERTY_TOPIC_SERVERS_SUFFIX, SERVER); - - params.setTopicCommInfrastructure("noop"); - params.setTopic(topic); - params.setEffectiveTopic(MY_EFFECTIVE_TOPIC); - params.setManaged(true); - params.setUseHttps(true); - params.setAllowSelfSignedCerts(true); - params.setServers(Arrays.asList(SERVER)); - - return this; - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSinkFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSinkFactoryTest.java deleted file mode 100644 index b4ab54fa..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSinkFactoryTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class NoopTopicSinkFactoryTest extends NoopTopicFactoryTest<NoopTopicSinkFactory, NoopTopicSink> { - - @Override - protected NoopTopicSinkFactory buildFactory() { - return new NoopTopicSinkFactory(); - } - - @Test - public void testToString() { - assertTrue(new NoopTopicSinkFactory().toString().startsWith("NoopTopicSinkFactory [")); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSinkTest.java deleted file mode 100644 index 02478367..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSinkTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; - -import org.junit.Test; - -public class NoopTopicSinkTest extends NoopTopicEndpointTest<NoopTopicSinkFactory, NoopTopicSink> { - - public NoopTopicSinkTest() { - super(new NoopTopicSinkFactory()); - } - - @Override - protected boolean io(String message) { - return endpoint.send(message); - } - - @Test - public void testToString() { - assertThat(endpoint.toString()).startsWith("NoopTopicSink"); - } - - @Test - public void testSend() { - NoopTopicSink sink = new NoopTopicSink(servers, MY_TOPIC) { - @Override - protected boolean broadcast(String message) { - throw new RuntimeException(EXPECTED); - } - - }; - - sink.start(); - assertFalse(sink.send(MY_MESSAGE)); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSourceFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSourceFactoryTest.java deleted file mode 100644 index e16174fd..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSourceFactoryTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class NoopTopicSourceFactoryTest extends NoopTopicFactoryTest<NoopTopicSourceFactory, NoopTopicSource> { - - @Override - protected NoopTopicSourceFactory buildFactory() { - return new NoopTopicSourceFactory(); - } - - @Test - public void testToString() { - assertTrue(new NoopTopicSourceFactory().toString().startsWith("NoopTopicSourceFactory [")); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSourceTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSourceTest.java deleted file mode 100644 index 22ccb9a8..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/NoopTopicSourceTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class NoopTopicSourceTest extends NoopTopicEndpointTest<NoopTopicSourceFactory, NoopTopicSource> { - - public NoopTopicSourceTest() { - super(new NoopTopicSourceFactory()); - } - - @Override - protected boolean io(String message) { - return this.endpoint.offer(message); - } - - @Test - public void testToString() { - assertTrue(this.endpoint.toString().startsWith("NoopTopicSource")); - } - - @Test - public void testOffer() { - NoopTopicSource source = new NoopTopicSource(servers, MY_TOPIC) { - @Override - protected boolean broadcast(String message) { - throw new RuntimeException(EXPECTED); - } - - }; - - source.start(); - assertFalse(source.offer(MY_MESSAGE)); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicFactoryTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicFactoryTestBase.java deleted file mode 100644 index 9795fd30..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicFactoryTestBase.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; - -import java.util.List; -import java.util.Properties; -import org.onap.policy.common.endpoints.event.comm.Topic; - -/** - * Base class for XxxTopicFactory tests. - * - * @param <T> type of topic managed by the factory - */ -public abstract class TopicFactoryTestBase<T extends Topic> extends TopicTestBase { - - public static final String SERVER = "my-server"; - public static final String TOPIC2 = "my-topic-2"; - public static final String TOPIC3 = "my-topic-3"; - - /** - * Initializes a new factory. - */ - protected abstract void initFactory(); - - /** - * Makes a property builder. - * - * @return a new property builder - */ - protected abstract TopicPropertyBuilder makePropBuilder(); - - /** - * Builds a set of topics. - * - * @param properties the properties used to configure the topics - * @return a list of new topics - */ - protected abstract List<T> buildTopics(Properties properties); - - /** - * Destroys the factory. - */ - protected abstract void destroyFactory(); - - /** - * Destroys a topic within the factory. - * - * @param topic the topic to destroy - */ - protected abstract void destroyTopic(String topic); - - /** - * Gets the list of topics from the factory. - * - * @return the topic inventory - */ - protected abstract List<T> getInventory(); - - /** - * Gets a topic from the factory. - * - * @param topic the topic name - * @return the topic - */ - protected abstract T getTopic(String topic); - - - /** - * Tests building a topic using varied Properties. - */ - public void testBuildProperties_Variations() { - initFactory(); - - // null topic list - assertTrue(buildTopics(makePropBuilder().build()).isEmpty()); - - // empty topic list - assertTrue(buildTopics(makePropBuilder().addTopic("").build()).isEmpty()); - - // null servers - assertTrue(buildTopics(makePropBuilder().makeTopic(MY_TOPIC).removeTopicProperty(PROPERTY_TOPIC_SERVERS_SUFFIX) - .build()).isEmpty()); - - // empty servers - assertTrue(buildTopics(makePropBuilder().makeTopic(MY_TOPIC).setTopicProperty(PROPERTY_TOPIC_SERVERS_SUFFIX, "") - .build()).isEmpty()); - } - - /** - * Tests building multiple topics using Properties. - */ - public void testBuildProperties_Multiple() { - initFactory(); - - // make two fully-defined topics, and add two duplicate topic names to the list - TopicPropertyBuilder builder = - makePropBuilder().makeTopic(MY_TOPIC).makeTopic(TOPIC2).addTopic(MY_TOPIC).addTopic(MY_TOPIC); - - List<T> lst = buildTopics(builder.build()); - assertEquals(4, lst.size()); - - int index = 0; - T item = lst.get(index++); - assertNotSame(item, lst.get(index++)); - assertSame(item, lst.get(index++)); - assertSame(item, lst.get(index++)); - } - - /** - * Tests destroy(topic), get(topic), and inventory() methods. - */ - public void testDestroyString_testGet_testInventory() { - initFactory(); - - List<T> lst = buildTopics(makePropBuilder().makeTopic(MY_TOPIC).makeTopic(TOPIC2).build()); - - int index = 0; - T item1 = lst.get(index++); - T item2 = lst.get(index++); - - assertEquals(2, getInventory().size()); - assertTrue(getInventory().contains(item1)); - assertTrue(getInventory().contains(item2)); - - item1.start(); - item2.start(); - - assertEquals(item1, getTopic(MY_TOPIC)); - assertEquals(item2, getTopic(TOPIC2)); - - destroyTopic(MY_TOPIC); - assertFalse(item1.isAlive()); - assertTrue(item2.isAlive()); - assertEquals(item2, getTopic(TOPIC2)); - assertEquals(1, getInventory().size()); - assertTrue(getInventory().contains(item2)); - - // repeat - destroyTopic(MY_TOPIC); - assertFalse(item1.isAlive()); - assertTrue(item2.isAlive()); - - // with other topic - destroyTopic(TOPIC2); - assertFalse(item1.isAlive()); - assertFalse(item2.isAlive()); - assertEquals(0, getInventory().size()); - } - - /** - * Tests exception cases with destroy(topic). - */ - public void testDestroyString_Ex() { - // null topic - assertThatIllegalArgumentException().as("null topic").isThrownBy(() -> destroyTopic(null)); - - // empty topic - assertThatIllegalArgumentException().as("empty topic").isThrownBy(() -> destroyTopic("")); - } - - /** - * Tests the destroy() method. - */ - public void testDestroy() { - initFactory(); - - List<T> lst = buildTopics(makePropBuilder().makeTopic(MY_TOPIC).makeTopic(TOPIC2).build()); - - int index = 0; - T item1 = lst.get(index++); - T item2 = lst.get(index++); - - item1.start(); - item2.start(); - - destroyFactory(); - - assertFalse(item1.isAlive()); - assertFalse(item2.isAlive()); - assertEquals(0, getInventory().size()); - } - - /** - * Tests exception cases with get(topic). - */ - public void testGet_Ex() { - // null topic - assertThatIllegalArgumentException().as("null topic").isThrownBy(() -> getTopic(null)); - - // empty topic - assertThatIllegalArgumentException().as("empty topic").isThrownBy(() -> getTopic("")); - - // unknown topic - initFactory(); - buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build()); - - assertThatIllegalStateException().as("unknown topic").isThrownBy(() -> getTopic(TOPIC2)); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicPropertyBuilder.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicPropertyBuilder.java deleted file mode 100644 index e8031c1a..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicPropertyBuilder.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP Policy Engine - Common Modules - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import java.util.Properties; - -/** - * Builder of properties used when configuring topics. - */ -public abstract class TopicPropertyBuilder { - private final Properties properties = new Properties(); - private final String prefix; - private String topicPrefix; - - /** - * Constructs the object. - * - * @param prefix the prefix for the properties to be built - */ - public TopicPropertyBuilder(String prefix) { - this.prefix = prefix; - } - - /** - * Constructs the properties from the builder. - * - * @return a copy of the properties - */ - public Properties build() { - Properties props = new Properties(); - props.putAll(properties); - - return props; - } - - /** - * Adds a topic to the list of topics, configuring all of its properties with default - * values. - * - * @param topic the topic to be added - * @return this builder - */ - public abstract TopicPropertyBuilder makeTopic(String topic); - - /** - * Adds a topic to the list of topics. Also sets the current topic so that subsequent - * invocations of property methods will manipulate the topic's properties. - * - * @param topic the topic to be added - * @return this builder - */ - public TopicPropertyBuilder addTopic(String topic) { - // add topic to the list of topics - String topicList = properties.getProperty(prefix); - if (topicList == null || topicList.isEmpty()) { - topicList = topic; - } else { - topicList += "," + topic; - } - - properties.setProperty(prefix, topicList); - - setTopic(topic); - - return this; - } - - /** - * Sets the topic for which subsequent properties will be managed. - * - * @param topic the topic - * @return this builder - */ - public TopicPropertyBuilder setTopic(String topic) { - this.topicPrefix = prefix + "." + topic; - return this; - } - - /** - * Sets a topic's property. - * - * @param name name of the property - * @param value value to which the property should be set - * @return this builder - */ - public TopicPropertyBuilder setTopicProperty(String name, Object value) { - properties.setProperty(topicPrefix + name, value.toString()); - return this; - } - - /** - * Removes a topic's property. - * - * @param name name of the property - * @return this builder - */ - public TopicPropertyBuilder removeTopicProperty(String name) { - properties.remove(topicPrefix + name); - return this; - } -} - diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicTestBase.java deleted file mode 100644 index 8b75fa35..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/TopicTestBase.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder; - -/** - * Base class for Topic Test classes. - */ -public class TopicTestBase { - - public static final String MY_AFT_ENV = "my-aft-env"; - public static final String MY_API_KEY = "my-api-key"; - public static final String MY_API_SECRET = "my-api-secret"; - public static final String MY_BASE_PATH = "my-base"; - public static final String MY_CLIENT_NAME = "my-client"; - public static final String MY_CONS_GROUP = "my-cons-group"; - public static final String MY_CONS_INST = "my-cons-inst"; - public static final String MY_ENV = "my-env"; - public static final int MY_FETCH_LIMIT = 100; - public static final int MY_FETCH_TIMEOUT = 101; - public static final String MY_HOST = "my-host"; - public static final String MY_LAT = "my-lat"; - public static final String MY_LONG = "my-long"; - public static final String MY_PARTNER = "my-partner"; - public static final String MY_PASS = "my-pass"; - public static final int MY_PORT = 102; - public static final String MY_TOPIC = "my-topic"; - public static final String MY_EFFECTIVE_TOPIC = "my-effective-topic"; - public static final String MY_USERNAME = "my-user"; - - public static final String MY_MESSAGE = "my-message"; - public static final String MY_PARTITION = "my-partition"; - public static final String MY_MESSAGE2 = "my-message-2"; - public static final String MY_PARTITION2 = "my-partition-2"; - - public static final String ROUTE_PROP = "routeOffer"; - public static final String MY_ROUTE = "my-route"; - - /** - * Message used within exceptions that are expected. - */ - public static final String EXPECTED = "expected exception"; - - /** - * Additional properties to be added to the parameter builder. - */ - protected Map<String, String> addProps; - - /** - * Servers to be added to the parameter builder. - */ - protected List<String> servers; - - /** - * Parameter builder used to build topic parameters. - */ - protected TopicParamsBuilder builder; - - /** - * Initializes {@link #addProps}, {@link #servers}, and {@link #builder}. - */ - public void setUp() { - addProps = new TreeMap<>(); - addProps.put("my-key-A", "my-value-A"); - addProps.put("my-key-B", "my-value-B"); - - servers = Arrays.asList("svra", "svrb"); - - builder = makeBuilder(); - } - - /** - * Makes a fully populated parameter builder. - * - * @return a new parameter builder - */ - public TopicParamsBuilder makeBuilder() { - return makeBuilder(addProps, servers); - } - - /** - * Makes a fully populated parameter builder. - * - * @param addProps additional properties to be added to the builder - * @param servers servers to be added to the builder - * @return a new parameter builder - */ - public TopicParamsBuilder makeBuilder(Map<String, String> addProps, List<String> servers) { - - return BusTopicParams.builder().additionalProps(addProps).aftEnvironment(MY_AFT_ENV).allowSelfSignedCerts(true) - .apiKey(MY_API_KEY).apiSecret(MY_API_SECRET).basePath(MY_BASE_PATH).clientName(MY_CLIENT_NAME) - .consumerGroup(MY_CONS_GROUP).consumerInstance(MY_CONS_INST).environment(MY_ENV) - .fetchLimit(MY_FETCH_LIMIT).fetchTimeout(MY_FETCH_TIMEOUT).hostname(MY_HOST).latitude(MY_LAT) - .longitude(MY_LONG).managed(true).partitionId(MY_PARTITION).partner(MY_PARTNER) - .password(MY_PASS).port(MY_PORT).servers(servers).topic(MY_TOPIC) - .effectiveTopic(MY_EFFECTIVE_TOPIC).useHttps(true).userName(MY_USERNAME); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicFactoryTestBase.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicFactoryTestBase.java deleted file mode 100644 index 41dbac8c..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicFactoryTestBase.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -import java.util.Collections; -import org.onap.policy.common.endpoints.event.comm.Topic; - -/** - * Base class for UebTopicXxxFactory tests. - * - * @param <T> type of topic managed by the factory - */ -public abstract class UebTopicFactoryTestBase<T extends Topic> extends BusTopicFactoryTestBase<T> { - - @Override - public void testBuildBusTopicParams_Ex() { - - super.testBuildBusTopicParams_Ex(); - - // null servers - assertThatIllegalArgumentException().as("null servers") - .isThrownBy(() -> buildTopic(makeBuilder().servers(null).build())); - - // empty servers - assertThatIllegalArgumentException().as("empty servers") - .isThrownBy(() -> buildTopic(makeBuilder().servers(Collections.emptyList()).build())); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicPropertyBuilder.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicPropertyBuilder.java deleted file mode 100644 index cb5507e5..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicPropertyBuilder.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_AFT_ENV; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_API_KEY; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_API_SECRET; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_CONS_GROUP; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_CONS_INST; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_EFFECTIVE_TOPIC; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_FETCH_LIMIT; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_FETCH_TIMEOUT; -import static org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase.MY_PARTITION; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_API_KEY_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_API_SECRET_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX; - -import java.util.Arrays; -import lombok.Getter; -import org.onap.policy.common.endpoints.parameters.TopicParameters; - -public class UebTopicPropertyBuilder extends TopicPropertyBuilder { - - public static final String SERVER = "my-server"; - public static final String TOPIC2 = "my-topic-2"; - - public static final String MY_AAF_MECHID = "my-aaf-mechid"; - public static final String MY_AAF_PASS = "my-aaf-passwd"; - - @Getter - private TopicParameters params = new TopicParameters(); - - /** - * Constructs the object. - * - * @param prefix the prefix for the properties to be built - */ - public UebTopicPropertyBuilder(String prefix) { - super(prefix); - } - - /** - * Adds a topic and configures it's properties with default values. - * - * @param topic the topic to be added - * @return this builder - */ - public UebTopicPropertyBuilder makeTopic(String topic) { - addTopic(topic); - - setTopicProperty(PROPERTY_TOPIC_EFFECTIVE_TOPIC_SUFFIX, MY_EFFECTIVE_TOPIC); - setTopicProperty(PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX, MY_CONS_GROUP); - setTopicProperty(PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX, MY_CONS_INST); - setTopicProperty(PROPERTY_MANAGED_SUFFIX, "true"); - setTopicProperty(PROPERTY_HTTP_HTTPS_SUFFIX, "true"); - setTopicProperty(PROPERTY_TOPIC_AAF_MECHID_SUFFIX, MY_AAF_MECHID); - setTopicProperty(PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX, MY_AAF_PASS); - setTopicProperty(PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX, MY_AFT_ENV); - setTopicProperty(PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX, "true"); - setTopicProperty(PROPERTY_TOPIC_API_KEY_SUFFIX, MY_API_KEY); - setTopicProperty(PROPERTY_TOPIC_API_SECRET_SUFFIX, MY_API_SECRET); - setTopicProperty(PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX, MY_FETCH_LIMIT); - setTopicProperty(PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX, MY_FETCH_TIMEOUT); - setTopicProperty(PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX, MY_PARTITION); - setTopicProperty(PROPERTY_TOPIC_SERVERS_SUFFIX, SERVER); - - params.setTopicCommInfrastructure("ueb"); - params.setTopic(topic); - params.setEffectiveTopic(MY_EFFECTIVE_TOPIC); - params.setConsumerGroup(MY_CONS_GROUP); - params.setConsumerInstance(MY_CONS_INST); - params.setManaged(true); - params.setUseHttps(true); - params.setUserName(MY_AAF_MECHID); - params.setPassword(MY_AAF_PASS); - params.setAftEnvironment(MY_AFT_ENV); - params.setAllowSelfSignedCerts(true); - params.setApiKey(MY_API_KEY); - params.setApiSecret(MY_API_SECRET); - params.setFetchLimit(MY_FETCH_LIMIT); - params.setFetchTimeout(MY_FETCH_TIMEOUT); - params.setPartitionId(MY_PARTITION); - params.setServers(Arrays.asList(SERVER)); - - return this; - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSinkFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSinkFactoryTest.java deleted file mode 100644 index 4896a9df..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSinkFactoryTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS; - -import java.util.Deque; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; - -public class UebTopicSinkFactoryTest extends UebTopicFactoryTestBase<UebTopicSink> { - - private SinkFactory factory; - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - factory = new SinkFactory(); - } - - @After - public void tearDown() { - factory.destroy(); - } - - @Test - @Override - public void testBuildBusTopicParams() { - super.testBuildBusTopicParams(); - super.testBuildBusTopicParams_Ex(); - } - - @Test - @Override - public void testBuildListOfStringString() { - super.testBuildListOfStringString(); - - // check parameters that were used - BusTopicParams params = getLastParams(); - assertEquals(false, params.isAllowSelfSignedCerts()); - } - - @Test - @Override - public void testBuildProperties() { - super.testBuildProperties(); - super.testBuildProperties_Variations(); - super.testBuildProperties_Multiple(); - - initFactory(); - - assertEquals(1, buildTopics(makePropBuilder().makeTopic(MY_TOPIC).build()).size()); - - BusTopicParams params = getLastParams(); - assertEquals(MY_PARTITION, params.getPartitionId()); - } - - @Test - @Override - public void testDestroyString_testGet_testInventory() { - super.testDestroyString_testGet_testInventory(); - super.testDestroyString_Ex(); - } - - @Test - @Override - public void testDestroy() { - super.testDestroy(); - } - - @Test - public void testGet() { - super.testGet_Ex(); - } - - @Test - public void testToString() { - assertTrue(factory.toString().startsWith("IndexedUebTopicSinkFactory [")); - } - - @Override - protected void initFactory() { - if (factory != null) { - factory.destroy(); - } - - factory = new SinkFactory(); - } - - @Override - protected List<UebTopicSink> buildTopics(Properties properties) { - return factory.build(properties); - } - - @Override - protected UebTopicSink buildTopic(BusTopicParams params) { - return factory.build(params); - } - - @Override - protected UebTopicSink buildTopic(List<String> servers, String topic) { - return factory.build(servers, topic); - } - - @Override - protected void destroyFactory() { - factory.destroy(); - } - - @Override - protected void destroyTopic(String topic) { - factory.destroy(topic); - } - - @Override - protected List<UebTopicSink> getInventory() { - return factory.inventory(); - } - - @Override - protected UebTopicSink getTopic(String topic) { - return factory.get(topic); - } - - @Override - protected BusTopicParams getLastParams() { - return factory.params.getLast(); - } - - @Override - protected TopicPropertyBuilder makePropBuilder() { - return new UebTopicPropertyBuilder(PROPERTY_UEB_SINK_TOPICS); - } - - /** - * Factory that records the parameters of all of the sinks it creates. - */ - private static class SinkFactory extends IndexedUebTopicSinkFactory { - private Deque<BusTopicParams> params = new LinkedList<>(); - - @Override - protected UebTopicSink makeSink(BusTopicParams busTopicParams) { - params.add(busTopicParams); - return super.makeSink(busTopicParams); - } - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSinkTest.java deleted file mode 100644 index 77452604..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSinkTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP Policy Engine - Common Modules - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -public class UebTopicSinkTest { - - @Test - public void test() { - assertNotNull(UebTopicFactories.getSinkFactory()); - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSourceFactoryTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSourceFactoryTest.java deleted file mode 100644 index 81e30756..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSourceFactoryTest.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP Policy Engine - Common Modules - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX; -import static org.onap.policy.common.endpoints.properties.PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS; - -import java.util.Deque; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; - -public class UebTopicSourceFactoryTest extends UebTopicFactoryTestBase<UebTopicSource> { - - private SourceFactory factory; - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - factory = new SourceFactory(); - } - - @After - public void tearDown() { - factory.destroy(); - } - - @Test - @Override - public void testBuildBusTopicParams() { - super.testBuildBusTopicParams(); - super.testBuildBusTopicParams_Ex(); - } - - @Test - @Override - public void testBuildProperties() { - - super.testBuildProperties(); - - // check source-specific parameters that were used - BusTopicParams params = factory.params.getFirst(); - assertEquals(MY_CONS_GROUP, params.getConsumerGroup()); - assertEquals(MY_CONS_INST, params.getConsumerInstance()); - assertEquals(MY_FETCH_LIMIT, params.getFetchLimit()); - assertEquals(MY_FETCH_TIMEOUT, params.getFetchTimeout()); - - super.testBuildProperties_Variations(); - super.testBuildProperties_Multiple(); - - // check default values for source-specific parameters - checkDefault(PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX, - params2 -> params2.getFetchLimit() == PolicyEndPointProperties.DEFAULT_LIMIT_FETCH, - null, "", "invalid-limit-number"); - - checkDefault(PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX, - params2 -> params2.getFetchTimeout() == PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH, - null, "", "invalid-timeout-number"); - } - - @Test - public void testBuildListOfStringStringStringString() { - UebTopicSource source1 = factory.build(servers, MY_TOPIC, MY_API_KEY, MY_API_SECRET); - assertNotNull(source1); - - // check source-specific parameters that were used - BusTopicParams params = factory.params.getFirst(); - assertEquals(MY_API_KEY, params.getApiKey()); - assertEquals(MY_API_SECRET, params.getApiSecret()); - assertEquals(PolicyEndPointProperties.DEFAULT_LIMIT_FETCH, params.getFetchLimit()); - assertEquals(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH, params.getFetchTimeout()); - } - - @Test - @Override - public void testBuildListOfStringString() { - super.testBuildListOfStringString(); - - // check source-specific parameters that were used - BusTopicParams params = factory.params.getFirst(); - assertEquals(null, params.getApiKey()); - assertEquals(null, params.getApiSecret()); - assertEquals(PolicyEndPointProperties.DEFAULT_LIMIT_FETCH, params.getFetchLimit()); - assertEquals(PolicyEndPointProperties.DEFAULT_TIMEOUT_MS_FETCH, params.getFetchTimeout()); - - assertEquals(true, params.isAllowSelfSignedCerts()); - } - - @Test - @Override - public void testDestroyString_testGet_testInventory() { - super.testDestroyString_testGet_testInventory(); - super.testDestroyString_Ex(); - } - - @Test - @Override - public void testDestroy() { - super.testDestroy(); - } - - @Test - public void testGet() { - super.testGet_Ex(); - } - - @Test - public void testToString() { - assertTrue(factory.toString().startsWith("IndexedUebTopicSourceFactory [")); - } - - @Override - protected void initFactory() { - if (factory != null) { - factory.destroy(); - } - - factory = new SourceFactory(); - } - - @Override - protected List<UebTopicSource> buildTopics(Properties properties) { - return factory.build(properties); - } - - @Override - protected UebTopicSource buildTopic(BusTopicParams params) { - return factory.build(params); - } - - @Override - protected UebTopicSource buildTopic(List<String> servers, String topic) { - return factory.build(servers, topic); - } - - @Override - protected void destroyFactory() { - factory.destroy(); - } - - @Override - protected void destroyTopic(String topic) { - factory.destroy(topic); - } - - @Override - protected List<UebTopicSource> getInventory() { - return factory.inventory(); - } - - @Override - protected UebTopicSource getTopic(String topic) { - return factory.get(topic); - } - - @Override - protected BusTopicParams getLastParams() { - return factory.params.getLast(); - } - - @Override - protected TopicPropertyBuilder makePropBuilder() { - return new UebTopicPropertyBuilder(PROPERTY_UEB_SOURCE_TOPICS); - } - - /** - * Factory that records the parameters of all of the sources it creates. - */ - private static class SourceFactory extends IndexedUebTopicSourceFactory { - private Deque<BusTopicParams> params = new LinkedList<>(); - - @Override - protected UebTopicSource makeSource(BusTopicParams busTopicParams) { - params.add(busTopicParams); - return super.makeSource(busTopicParams); - } - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSourceTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSourceTest.java deleted file mode 100644 index 9ef8af84..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/UebTopicSourceTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP Policy Engine - Common Modules - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -public class UebTopicSourceTest { - - @Test - public void test() { - assertNotNull(UebTopicFactories.getSourceFactory()); - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java deleted file mode 100644 index 5264b2f4..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusConsumerTest.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.att.nsa.cambria.client.CambriaConsumer; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.apache.commons.collections4.IteratorUtils; -import org.junit.Before; -import org.junit.Test; -import org.onap.dmaap.mr.client.impl.MRConsumerImpl; -import org.onap.dmaap.mr.client.response.MRConsumerResponse; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.CambriaConsumerWrapper; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.DmaapAafConsumerWrapper; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.DmaapConsumerWrapper; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.DmaapDmeConsumerWrapper; -import org.powermock.reflect.Whitebox; - -public class BusConsumerTest extends TopicTestBase { - - @Before - @Override - public void setUp() { - super.setUp(); - } - - @Test - public void testCambriaConsumerWrapper() { - // verify that different wrappers can be built - new CambriaConsumerWrapper(makeBuilder().build()); - new CambriaConsumerWrapper(makeBuilder().useHttps(false).build()); - new CambriaConsumerWrapper(makeBuilder().useHttps(true).build()); - new CambriaConsumerWrapper(makeBuilder().useHttps(true).allowSelfSignedCerts(false).build()); - new CambriaConsumerWrapper(makeBuilder().useHttps(true).allowSelfSignedCerts(true).build()); - new CambriaConsumerWrapper(makeBuilder().apiKey(null).build()); - new CambriaConsumerWrapper(makeBuilder().apiSecret(null).build()); - new CambriaConsumerWrapper(makeBuilder().apiKey(null).apiSecret(null).build()); - new CambriaConsumerWrapper(makeBuilder().userName(null).build()); - new CambriaConsumerWrapper(makeBuilder().password(null).build()); - - assertThatCode(() -> new CambriaConsumerWrapper(makeBuilder().userName(null).password(null).build())) - .doesNotThrowAnyException(); - } - - @Test - public void testCambriaConsumerWrapperFetch() throws Exception { - CambriaConsumer inner = mock(CambriaConsumer.class); - List<String> lst = Arrays.asList(MY_MESSAGE, MY_MESSAGE2); - when(inner.fetch()).thenReturn(lst); - - CambriaConsumerWrapper cons = new CambriaConsumerWrapper(builder.build()); - Whitebox.setInternalState(cons, "consumer", inner); - - assertEquals(lst, IteratorUtils.toList(cons.fetch().iterator())); - - // arrange to throw exception next time fetch is called - IOException ex = new IOException(EXPECTED); - when(inner.fetch()).thenThrow(ex); - - cons.fetchTimeout = 10; - - try { - cons.fetch(); - fail("missing exception"); - - } catch (IOException e) { - assertEquals(ex, e); - } - } - - @Test - public void testCambriaConsumerWrapperClose() { - CambriaConsumerWrapper cons = new CambriaConsumerWrapper(builder.build()); - - // set filter several times to cause different branches of close() to be executed - for (int count = 0; count < 3; ++count) { - cons.close(); - final int count2 = count; - assertThatCode(() -> cons.setFilter("close=" + count2)).doesNotThrowAnyException(); - } - } - - @Test - public void testCambriaConsumerWrapperSetFilter() { - // set filter several times to cause different branches to be executed - CambriaConsumerWrapper cons = new CambriaConsumerWrapper(builder.build()); - for (int count = 0; count < 3; ++count) { - final int count2 = count; - assertThatCode(() -> cons.setFilter("set-filter=" + count2)).doesNotThrowAnyException(); - } - } - - @Test - public void testCambriaConsumerWrapperToString() { - assertNotNull(new CambriaConsumerWrapper(makeBuilder().build()).toString()); - } - - @Test - public void testDmaapConsumerWrapper() throws Exception { - // verify that different wrappers can be built - assertThatCode(() -> new DmaapAafConsumerWrapper(makeBuilder().build())).doesNotThrowAnyException(); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapConsumerWrapper_InvalidTopic() throws Exception { - new DmaapAafConsumerWrapper(makeBuilder().topic(null).build()); - } - - @Test - public void testDmaapConsumerWrapperFetch() throws Exception { - DmaapAafConsumerWrapper dmaap = new DmaapAafConsumerWrapper(makeBuilder().build()); - MRConsumerImpl cons = mock(MRConsumerImpl.class); - - dmaap.fetchTimeout = 5; - dmaap.consumer = cons; - - // null return - when(cons.fetchWithReturnConsumerResponse()).thenReturn(null); - assertFalse(dmaap.fetch().iterator().hasNext()); - - // with messages, 200 - List<String> lst = Arrays.asList(MY_MESSAGE, MY_MESSAGE2); - MRConsumerResponse resp = new MRConsumerResponse(); - resp.setResponseCode("200"); - resp.setActualMessages(lst); - when(cons.fetchWithReturnConsumerResponse()).thenReturn(resp); - - assertEquals(lst, IteratorUtils.toList(dmaap.fetch().iterator())); - - // null messages - resp.setActualMessages(null); - when(cons.fetchWithReturnConsumerResponse()).thenReturn(resp); - - assertFalse(dmaap.fetch().iterator().hasNext()); - - // with messages, NOT 200 - resp.setResponseCode("400"); - resp.setActualMessages(lst); - when(cons.fetchWithReturnConsumerResponse()).thenReturn(resp); - - assertEquals(lst, IteratorUtils.toList(dmaap.fetch().iterator())); - } - - @Test - public void testDmaapConsumerWrapperClose() throws Exception { - assertThatCode(() -> new DmaapAafConsumerWrapper(makeBuilder().build()).close()).doesNotThrowAnyException(); - } - - @Test - public void testDmaapConsumerWrapperToString() throws Exception { - assertNotNull(new DmaapConsumerWrapper(makeBuilder().build()) {}.toString()); - } - - @Test - public void testDmaapAafConsumerWrapper() throws Exception { - // verify that different wrappers can be built - new DmaapAafConsumerWrapper(makeBuilder().useHttps(true).build()); - assertThatCode(() -> new DmaapAafConsumerWrapper(makeBuilder().useHttps(false).build())) - .doesNotThrowAnyException(); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapAafConsumerWrapper_InvalidServers() throws Exception { - /* - * Unfortunately, the MR code intercepts this and throws an exception before the - * wrapper gets a chance to check it, thus this test does not improve the coverage - * for the constructor. - */ - new DmaapAafConsumerWrapper(makeBuilder().servers(Collections.emptyList()).build()); - } - - @Test - public void testDmaapAafConsumerWrapperToString() throws Exception { - assertNotNull(new DmaapAafConsumerWrapper(makeBuilder().build()).toString()); - } - - @Test - public void testDmaapDmeConsumerWrapper() throws Exception { - // verify that different wrappers can be built - new DmaapDmeConsumerWrapper(makeBuilder().build()); - new DmaapDmeConsumerWrapper(makeBuilder().useHttps(true).build()); - new DmaapDmeConsumerWrapper(makeBuilder().useHttps(false).build()); - new DmaapDmeConsumerWrapper(makeBuilder().additionalProps(null).build()); - - addProps.put(ROUTE_PROP, MY_ROUTE); - new DmaapDmeConsumerWrapper(makeBuilder().build()); - assertThatCode(() -> new DmaapDmeConsumerWrapper(makeBuilder().partner(null).build())) - .doesNotThrowAnyException(); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapDmeConsumerWrapper_InvalidEnvironment() throws Exception { - new DmaapDmeConsumerWrapper(makeBuilder().environment(null).build()); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapDmeConsumerWrapper_InvalidAft() throws Exception { - new DmaapDmeConsumerWrapper(makeBuilder().aftEnvironment(null).build()); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapDmeConsumerWrapper_InvalidLat() throws Exception { - new DmaapDmeConsumerWrapper(makeBuilder().latitude(null).build()); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapDmeConsumerWrapper_InvalidLong() throws Exception { - new DmaapDmeConsumerWrapper(makeBuilder().longitude(null).build()); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapDmeConsumerWrapper_InvalidPartner() throws Exception { - new DmaapDmeConsumerWrapper(makeBuilder().partner(null).build()); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java deleted file mode 100644 index 513673bd..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusPublisherTest.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import java.io.IOException; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; -import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher; -import org.onap.dmaap.mr.client.response.MRPublisherResponse; -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusPublisher.CambriaPublisherWrapper; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusPublisher.DmaapAafPublisherWrapper; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusPublisher.DmaapDmePublisherWrapper; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusPublisher.DmaapPublisherWrapper; - -public class BusPublisherTest extends TopicTestBase { - - @Before - @Override - public void setUp() { - super.setUp(); - } - - @Test - public void testCambriaPublisherWrapper() { - // verify that different wrappers can be built - new CambriaPublisherWrapper(makeBuilder().build()); - new CambriaPublisherWrapper(makeBuilder().useHttps(false).build()); - new CambriaPublisherWrapper(makeBuilder().useHttps(true).build()); - new CambriaPublisherWrapper(makeBuilder().useHttps(true).allowSelfSignedCerts(false).build()); - new CambriaPublisherWrapper(makeBuilder().useHttps(true).allowSelfSignedCerts(true).build()); - new CambriaPublisherWrapper(makeBuilder().apiKey(null).build()); - new CambriaPublisherWrapper(makeBuilder().apiSecret(null).build()); - new CambriaPublisherWrapper(makeBuilder().apiKey(null).apiSecret(null).build()); - new CambriaPublisherWrapper(makeBuilder().userName(null).build()); - new CambriaPublisherWrapper(makeBuilder().password(null).build()); - assertThatCode(() -> new CambriaPublisherWrapper(makeBuilder().userName(null).password(null).build())) - .doesNotThrowAnyException(); - } - - @Test - public void testCambriaPublisherWrapperSend() throws Exception { - CambriaBatchingPublisher pub = mock(CambriaBatchingPublisher.class); - CambriaPublisherWrapper cambria = new CambriaPublisherWrapper(makeBuilder().build()); - cambria.publisher = pub; - - assertTrue(cambria.send(MY_PARTITION, MY_MESSAGE)); - - // publisher exception - when(pub.send(anyString(), anyString())).thenThrow(new IOException(EXPECTED)); - assertFalse(cambria.send(MY_PARTITION2, MY_MESSAGE2)); - } - - @Test(expected = IllegalArgumentException.class) - public void testCambriaPublisherWrapperSend_InvalidMsg() { - CambriaPublisherWrapper cambria = new CambriaPublisherWrapper(makeBuilder().build()); - cambria.publisher = mock(CambriaBatchingPublisher.class); - - cambria.send(MY_PARTITION, null); - } - - @Test - public void testCambriaPublisherWrapperClose() { - CambriaBatchingPublisher pub = mock(CambriaBatchingPublisher.class); - CambriaPublisherWrapper cambria = new CambriaPublisherWrapper(makeBuilder().build()); - cambria.publisher = pub; - - cambria.close(); - verify(pub).close(); - - // try again, this time with an exception - doThrow(new RuntimeException(EXPECTED)).when(pub).close(); - cambria.close(); - } - - @Test - public void testDmaapPublisherWrapper() { - // verify with different constructor arguments - new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASS, true); - new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASS, false); - assertThatCode(() -> new DmaapPublisherWrapper(ProtocolTypeConstants.DME2, servers, MY_TOPIC, MY_USERNAME, - MY_PASS, true) {}).doesNotThrowAnyException(); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapPublisherWrapper_InvalidTopic() { - new DmaapPublisherWrapper(ProtocolTypeConstants.DME2, servers, "", MY_USERNAME, MY_PASS, true) {}; - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapPublisherWrapper_Aaf_NullServers() { - new DmaapAafPublisherWrapper(null, MY_TOPIC, MY_USERNAME, MY_PASS, true); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapPublisherWrapper_Aaf_NoServers() { - new DmaapAafPublisherWrapper(Collections.emptyList(), MY_TOPIC, MY_USERNAME, MY_PASS, true); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapPublisherWrapper_InvalidProtocol() { - new DmaapPublisherWrapper(ProtocolTypeConstants.HTTPNOAUTH, servers, MY_TOPIC, MY_USERNAME, MY_PASS, true) {}; - } - - @Test - public void testDmaapPublisherWrapperClose() throws Exception { - MRSimplerBatchPublisher pub = mock(MRSimplerBatchPublisher.class); - DmaapPublisherWrapper dmaap = new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASS, true); - dmaap.publisher = pub; - - dmaap.close(); - verify(pub).close(anyLong(), any(TimeUnit.class)); - - // close, but with exception from publisher - doThrow(new IOException(EXPECTED)).when(pub).close(anyLong(), any(TimeUnit.class)); - dmaap.close(); - } - - @Test - public void testDmaapPublisherWrapperSend() { - MRSimplerBatchPublisher pub = mock(MRSimplerBatchPublisher.class); - DmaapPublisherWrapper dmaap = new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASS, true); - dmaap.publisher = pub; - - // null response - assertTrue(dmaap.send(MY_PARTITION, MY_MESSAGE)); - verify(pub).setPubResponse(any(MRPublisherResponse.class)); - verify(pub).send(MY_PARTITION, MY_MESSAGE); - - // with response - pub = mock(MRSimplerBatchPublisher.class); - dmaap.publisher = pub; - - MRPublisherResponse resp = new MRPublisherResponse(); - when(pub.sendBatchWithResponse()).thenReturn(resp); - assertTrue(dmaap.send(MY_PARTITION, MY_MESSAGE)); - verify(pub).setPubResponse(any(MRPublisherResponse.class)); - verify(pub).send(MY_PARTITION, MY_MESSAGE); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapPublisherWrapperSend_NullMessage() { - MRSimplerBatchPublisher pub = mock(MRSimplerBatchPublisher.class); - DmaapPublisherWrapper dmaap = new DmaapAafPublisherWrapper(servers, MY_TOPIC, MY_USERNAME, MY_PASS, true); - dmaap.publisher = pub; - - dmaap.send(MY_PARTITION, null); - } - - @Test - public void testDmaapDmePublisherWrapper() { - // verify with different parameters - new DmaapDmePublisherWrapper(makeBuilder().build()); - new DmaapDmePublisherWrapper(makeBuilder().additionalProps(null).build()); - - addProps.put(ROUTE_PROP, MY_ROUTE); - new DmaapDmePublisherWrapper(makeBuilder().build()); - new DmaapDmePublisherWrapper(makeBuilder().partner(null).build()); - - addProps.put("null-value", null); - assertThatCode(() -> new DmaapDmePublisherWrapper(makeBuilder().build())).doesNotThrowAnyException(); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapDmePublisherWrapper_InvalidEnv() { - new DmaapDmePublisherWrapper(makeBuilder().environment(null).build()); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapDmePublisherWrapper_InvalidAft() { - new DmaapDmePublisherWrapper(makeBuilder().aftEnvironment(null).build()); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapDmePublisherWrapper_InvalidLat() { - new DmaapDmePublisherWrapper(makeBuilder().latitude(null).build()); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapDmePublisherWrapper_InvalidLong() { - new DmaapDmePublisherWrapper(makeBuilder().longitude(null).build()); - } - - @Test(expected = IllegalArgumentException.class) - public void testDmaapDmePublisherWrapper_InvalidPartner() { - new DmaapDmePublisherWrapper(makeBuilder().partner(null).build()); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java deleted file mode 100644 index 0a2a5d34..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicBaseTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.utils.gson.GsonTestUtils; - -public class BusTopicBaseTest extends TopicTestBase { - - private BusTopicBaseImpl base; - - /** - * Initializes the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - base = new BusTopicBaseImpl(builder.build()); - } - - @Test - public void testToString() { - assertNotNull(base.toString()); - } - - @Test - public void testSerialize() { - assertThatCode(() -> new GsonTestUtils().compareGson(base, BusTopicBaseTest.class)).doesNotThrowAnyException(); - } - - @Test - public void testGetApiKey() { - assertEquals(MY_API_KEY, base.getApiKey()); - } - - @Test - public void testGetApiSecret() { - assertEquals(MY_API_SECRET, base.getApiSecret()); - } - - @Test - public void testIsUseHttps() { - assertEquals(true, base.isUseHttps()); - assertEquals(false, new BusTopicBaseImpl(builder.useHttps(false).build()).isUseHttps()); - } - - @Test - public void testIsAllowSelfSignedCerts() { - assertEquals(true, base.isAllowSelfSignedCerts()); - assertEquals(false, new BusTopicBaseImpl(builder.allowSelfSignedCerts(false).build()).isAllowSelfSignedCerts()); - } - - @Test - public void testTopic() { - assertEquals(MY_TOPIC, base.getTopic()); - assertEquals(MY_EFFECTIVE_TOPIC, base.getEffectiveTopic()); - assertNotEquals(base.getTopic(), base.getEffectiveTopic()); - } - - @Test - public void testAnyNullOrEmpty() { - assertFalse(base.anyNullOrEmpty()); - assertFalse(base.anyNullOrEmpty("any-none-null", "any-none-null-B")); - - assertTrue(base.anyNullOrEmpty(null, "any-first-null")); - assertTrue(base.anyNullOrEmpty("any-middle-null", null, "any-middle-null-B")); - assertTrue(base.anyNullOrEmpty("any-last-null", null)); - assertTrue(base.anyNullOrEmpty("any-empty", "")); - } - - @Test - public void testAllNullOrEmpty() { - assertTrue(base.allNullOrEmpty()); - assertTrue(base.allNullOrEmpty("")); - assertTrue(base.allNullOrEmpty(null, "")); - - assertFalse(base.allNullOrEmpty("all-ok-only-one")); - assertFalse(base.allNullOrEmpty("all-ok-one", "all-ok-two")); - assertFalse(base.allNullOrEmpty("all-ok-null", null)); - assertFalse(base.allNullOrEmpty("", "all-ok-empty")); - assertFalse(base.allNullOrEmpty("", "all-one-ok", null)); - } - - private static class BusTopicBaseImpl extends BusTopicBase { - - public BusTopicBaseImpl(BusTopicParams busTopicParams) { - super(busTopicParams); - } - - @Override - public CommInfrastructure getTopicCommInfrastructure() { - return CommInfrastructure.NOOP; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - - @Override - public void shutdown() { - // do nothing - } - - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java deleted file mode 100644 index c00f2b56..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/BusTopicParamsTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.function.BiConsumer; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder; - -public class BusTopicParamsTest extends TopicTestBase { - - @Before - @Override - public void setUp() { - super.setUp(); - } - - @Test - public void test() { - BusTopicParams params = makeBuilder().build(); - - assertEquals(addProps, params.getAdditionalProps()); - assertEquals(MY_AFT_ENV, params.getAftEnvironment()); - assertEquals(true, params.isAllowSelfSignedCerts()); - assertEquals(MY_API_KEY, params.getApiKey()); - assertEquals(MY_API_SECRET, params.getApiSecret()); - assertEquals(MY_BASE_PATH, params.getBasePath()); - assertEquals(MY_CLIENT_NAME, params.getClientName()); - assertEquals(MY_CONS_GROUP, params.getConsumerGroup()); - assertEquals(MY_CONS_INST, params.getConsumerInstance()); - assertEquals(MY_ENV, params.getEnvironment()); - assertEquals(MY_FETCH_LIMIT, params.getFetchLimit()); - assertEquals(MY_FETCH_TIMEOUT, params.getFetchTimeout()); - assertEquals(MY_HOST, params.getHostname()); - assertEquals(MY_LAT, params.getLatitude()); - assertEquals(MY_LONG, params.getLongitude()); - assertEquals(true, params.isManaged()); - assertEquals(MY_PARTITION, params.getPartitionId()); - assertEquals(MY_PARTNER, params.getPartner()); - assertEquals(MY_PASS, params.getPassword()); - assertEquals(MY_PORT, params.getPort()); - assertEquals(servers, params.getServers()); - assertEquals(MY_TOPIC, params.getTopic()); - assertEquals(MY_EFFECTIVE_TOPIC, params.getEffectiveTopic()); - assertEquals(true, params.isUseHttps()); - assertEquals(MY_USERNAME, params.getUserName()); - - // ensure that booleans are independent of each other - testBoolean("true:false:false", (bldr, flag) -> bldr.allowSelfSignedCerts(flag)); - testBoolean("false:true:false", (bldr, flag) -> bldr.managed(flag)); - testBoolean("false:false:true", (bldr, flag) -> bldr.useHttps(flag)); - - // test validity methods - assertTrue(params.isAdditionalPropsValid()); - assertFalse(params.isAftEnvironmentInvalid()); - assertTrue(params.isApiKeyValid()); - assertTrue(params.isApiSecretValid()); - assertFalse(params.isClientNameInvalid()); - assertFalse(params.isConsumerGroupInvalid()); - assertFalse(params.isConsumerInstanceInvalid()); - assertFalse(params.isEnvironmentInvalid()); - assertFalse(params.isHostnameInvalid()); - assertFalse(params.isLatitudeInvalid()); - assertFalse(params.isLongitudeInvalid()); - assertFalse(params.isPartitionIdInvalid()); - assertFalse(params.isPartnerInvalid()); - assertTrue(params.isPasswordValid()); - assertFalse(params.isPortInvalid()); - assertFalse(params.isServersInvalid()); - assertFalse(params.isTopicInvalid()); - assertTrue(params.isUserNameValid()); - - // test inverted validity - assertFalse(makeBuilder().additionalProps(null).build().isAdditionalPropsValid()); - assertTrue(makeBuilder().aftEnvironment("").build().isAftEnvironmentInvalid()); - assertFalse(makeBuilder().apiKey("").build().isApiKeyValid()); - assertFalse(makeBuilder().apiSecret("").build().isApiSecretValid()); - assertTrue(makeBuilder().clientName("").build().isClientNameInvalid()); - assertTrue(makeBuilder().consumerGroup("").build().isConsumerGroupInvalid()); - assertTrue(makeBuilder().consumerInstance("").build().isConsumerInstanceInvalid()); - assertTrue(makeBuilder().environment("").build().isEnvironmentInvalid()); - assertTrue(makeBuilder().hostname("").build().isHostnameInvalid()); - assertTrue(makeBuilder().latitude("").build().isLatitudeInvalid()); - assertTrue(makeBuilder().longitude("").build().isLongitudeInvalid()); - assertTrue(makeBuilder().partitionId("").build().isPartitionIdInvalid()); - assertTrue(makeBuilder().partner("").build().isPartnerInvalid()); - assertFalse(makeBuilder().password("").build().isPasswordValid()); - assertTrue(makeBuilder().port(-1).build().isPortInvalid()); - assertTrue(makeBuilder().port(65536).build().isPortInvalid()); - assertTrue(makeBuilder().servers(null).build().isServersInvalid()); - assertTrue(makeBuilder().servers(new LinkedList<>()).build().isServersInvalid()); - assertTrue(makeBuilder().servers(Arrays.asList("")).build().isServersInvalid()); - assertFalse(makeBuilder().servers(Arrays.asList("one-server")).build().isServersInvalid()); - assertTrue(makeBuilder().topic("").build().isTopicInvalid()); - assertFalse(makeBuilder().userName("").build().isUserNameValid()); - } - - /** - * Tests the boolean methods by applying a function, once with {@code false} and once - * with {@code true}. Verifies that all of the boolean methods return the correct - * value by concatenating them. - * - * @param expectedTrue the string that is expected when {@code true} is passed to the - * method - * @param function function to be applied to the builder - */ - private void testBoolean(String expectedTrue, BiConsumer<TopicParamsBuilder, Boolean> function) { - TopicParamsBuilder builder = BusTopicParams.builder(); - - // first try the "false" case - function.accept(builder, false); - - BusTopicParams params = builder.build(); - assertEquals("false:false:false", - "" + params.isAllowSelfSignedCerts() + ":" + params.isManaged() + ":" + params.isUseHttps()); - - - // now try the "true" case - function.accept(builder, true); - - params = builder.build(); - assertEquals(expectedTrue, - "" + params.isAllowSelfSignedCerts() + ":" + params.isManaged() + ":" + params.isUseHttps()); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java deleted file mode 100644 index e6eec799..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineBusTopicSinkTest.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.utils.gson.GsonTestUtils; - -public class InlineBusTopicSinkTest extends TopicTestBase { - - private InlineBusTopicSinkImpl sink; - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - sink = new InlineBusTopicSinkImpl(makeBuilder().build()); - } - - @After - public void tearDown() { - sink.shutdown(); - } - - @Test - public void testSerialize() { - assertThatCode(() -> new GsonTestUtils().compareGson(sink, InlineBusTopicSinkTest.class)) - .doesNotThrowAnyException(); - } - - @Test - public void testInlineBusTopicSinkImpl() { - // verify that different wrappers can be built - sink = new InlineBusTopicSinkImpl(makeBuilder().build()); - assertEquals(MY_PARTITION, sink.getPartitionKey()); - - sink = new InlineBusTopicSinkImpl(makeBuilder().partitionId(null).build()); - assertNotNull(sink.getPartitionKey()); - } - - @Test - public void testStart() { - assertTrue(sink.start()); - assertEquals(1, sink.initCount); - - // re-start, init() should not be invoked again - assertTrue(sink.start()); - assertEquals(1, sink.initCount); - } - - @Test(expected = IllegalStateException.class) - public void testStart_Locked() { - sink.lock(); - sink.start(); - } - - @Test - public void testStop() { - BusPublisher pub = mock(BusPublisher.class); - sink.publisher = pub; - - assertTrue(sink.stop()); - verify(pub).close(); - - // stop again, shouldn't not invoke close() again - assertFalse(sink.stop()); - verify(pub).close(); - - // publisher throws exception - sink = new InlineBusTopicSinkImpl(makeBuilder().build()); - sink.publisher = pub; - doThrow(new RuntimeException(EXPECTED)).when(pub).close(); - assertTrue(sink.stop()); - } - - @Test - public void testSend() { - sink.start(); - BusPublisher pub = mock(BusPublisher.class); - sink.publisher = pub; - - TopicListener listener = mock(TopicListener.class); - sink.register(listener); - - assertTrue(sink.send(MY_MESSAGE)); - - verify(pub).send(MY_PARTITION, MY_MESSAGE); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE); - assertEquals(Arrays.asList(MY_MESSAGE), Arrays.asList(sink.getRecentEvents())); - - // arrange for send to throw an exception - when(pub.send(anyString(), anyString())).thenThrow(new RuntimeException(EXPECTED)); - - assertFalse(sink.send(MY_MESSAGE)); - - // no more event deliveries - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE); - } - - @Test(expected = IllegalArgumentException.class) - public void testSend_NullMessage() { - sink.start(); - BusPublisher pub = mock(BusPublisher.class); - sink.publisher = pub; - - sink.send(null); - } - - @Test(expected = IllegalArgumentException.class) - public void testSend_EmptyMessage() { - sink.start(); - BusPublisher pub = mock(BusPublisher.class); - sink.publisher = pub; - - sink.send(""); - } - - @Test(expected = IllegalStateException.class) - public void testSend_NotStarted() { - BusPublisher pub = mock(BusPublisher.class); - sink.publisher = pub; - - sink.send(MY_MESSAGE); - } - - @Test - public void testSetPartitionKey_getPartitionKey() { - assertEquals(MY_PARTITION, sink.getPartitionKey()); - - sink.setPartitionKey("part-B"); - assertEquals("part-B", sink.getPartitionKey()); - } - - @Test - public void testShutdown() { - BusPublisher pub = mock(BusPublisher.class); - sink.publisher = pub; - - sink.shutdown(); - verify(pub).close(); - } - - @Test - public void testAnyNullOrEmpty() { - assertFalse(sink.anyNullOrEmpty()); - assertFalse(sink.anyNullOrEmpty("any-none-null", "any-none-null-B")); - - assertTrue(sink.anyNullOrEmpty(null, "any-first-null")); - assertTrue(sink.anyNullOrEmpty("any-middle-null", null, "any-middle-null-B")); - assertTrue(sink.anyNullOrEmpty("any-last-null", null)); - assertTrue(sink.anyNullOrEmpty("any-empty", "")); - } - - @Test - public void testAllNullOrEmpty() { - assertTrue(sink.allNullOrEmpty()); - assertTrue(sink.allNullOrEmpty("")); - assertTrue(sink.allNullOrEmpty(null, "")); - - assertFalse(sink.allNullOrEmpty("all-ok-only-one")); - assertFalse(sink.allNullOrEmpty("all-ok-one", "all-ok-two")); - assertFalse(sink.allNullOrEmpty("all-ok-null", null)); - assertFalse(sink.allNullOrEmpty("", "all-ok-empty")); - assertFalse(sink.allNullOrEmpty("", "all-one-ok", null)); - } - - @Test - public void testToString() { - assertTrue(sink.toString().startsWith("InlineBusTopicSink [")); - } - - /** - * Implementation of InlineBusTopicSink that tracks the number of times that init() is - * invoked. - */ - private static class InlineBusTopicSinkImpl extends InlineBusTopicSink { - - private int initCount = 0; - - public InlineBusTopicSinkImpl(BusTopicParams busTopicParams) { - super(busTopicParams); - } - - @Override - public CommInfrastructure getTopicCommInfrastructure() { - return CommInfrastructure.NOOP; - } - - @Override - public void init() { - ++initCount; - } - - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java deleted file mode 100644 index 239bf33a..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineDmaapTopicSinkTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.utils.gson.GsonTestUtils; - -public class InlineDmaapTopicSinkTest extends TopicTestBase { - private InlineDmaapTopicSink sink; - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - sink = new InlineDmaapTopicSink(makeBuilder().build()); - } - - @After - public void tearDown() { - sink.shutdown(); - } - - @Test - public void testSerialize() { - assertThatCode(() -> new GsonTestUtils().compareGson(sink, InlineDmaapTopicSinkTest.class)) - .doesNotThrowAnyException(); - } - - @Test - public void testToString() { - assertTrue(sink.toString().startsWith("InlineDmaapTopicSink [")); - } - - @Test - public void testInit() { - // nothing null - sink = new InlineDmaapTopicSink(makeBuilder().build()); - sink.init(); - sink.shutdown(); - - // no DME2 info - sink = new InlineDmaapTopicSink(makeBuilder().environment(null).aftEnvironment(null).latitude(null) - .longitude(null).partner(null).build()); - sink.init(); - assertThatCode(() -> sink.shutdown()).doesNotThrowAnyException(); - } - - @Test - public void testGetTopicCommInfrastructure() { - assertEquals(CommInfrastructure.DMAAP, sink.getTopicCommInfrastructure()); - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java deleted file mode 100644 index 674f379f..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/InlineUebTopicSinkTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.utils.gson.GsonTestUtils; - -public class InlineUebTopicSinkTest extends TopicTestBase { - private InlineUebTopicSink sink; - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - sink = new InlineUebTopicSink(makeBuilder().build()); - } - - @After - public void tearDown() { - sink.shutdown(); - } - - @Test - public void testSerialize() { - assertThatCode(() -> new GsonTestUtils().compareGson(sink, InlineUebTopicSinkTest.class)) - .doesNotThrowAnyException(); - } - - @Test - public void testToString() { - assertTrue(sink.toString().startsWith("InlineUebTopicSink [")); - } - - @Test - public void testInit() { - assertThatCode(() -> sink.init()).doesNotThrowAnyException(); - } - - @Test - public void testGetTopicCommInfrastructure() { - assertEquals(CommInfrastructure.UEB, sink.getTopicCommInfrastructure()); - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.java deleted file mode 100644 index 1e95924d..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.java +++ /dev/null @@ -1,369 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.Arrays; -import java.util.Collections; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.FilterableBusConsumer; -import org.onap.policy.common.utils.gson.GsonTestUtils; - -public class SingleThreadedBusTopicSourceTest extends TopicTestBase { - private Thread thread; - private BusConsumer cons; - private TopicListener listener; - private SingleThreadedBusTopicSourceImpl source; - - /** - * Creates the object to be tested, as well as various mocks. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - thread = mock(Thread.class); - cons = mock(BusConsumer.class); - listener = mock(TopicListener.class); - source = new SingleThreadedBusTopicSourceImpl(makeBuilder().build()); - } - - @After - public void tearDown() { - source.shutdown(); - } - - @Test - public void testSerialize() { - assertThatCode(() -> new GsonTestUtils().compareGson(source, SingleThreadedBusTopicSourceTest.class)) - .doesNotThrowAnyException(); - } - - @Test - public void testRegister() { - source.register(listener); - assertEquals(1, source.initCount); - source.offer(MY_MESSAGE); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE); - - // register another - should not re-init - TopicListener listener2 = mock(TopicListener.class); - source.register(listener2); - assertEquals(1, source.initCount); - source.offer(MY_MESSAGE + "z"); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE + "z"); - verify(listener2).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE + "z"); - - // re-register - should not re-init - source.register(listener); - assertEquals(1, source.initCount); - source.offer(MY_MESSAGE2); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE2); - - // lock & register - should not init - source = new SingleThreadedBusTopicSourceImpl(makeBuilder().build()); - source.lock(); - source.register(listener); - assertEquals(0, source.initCount); - - // exception during init - source = new SingleThreadedBusTopicSourceImpl(makeBuilder().build()); - source.initEx = true; - source.register(listener); - } - - @Test - public void testUnregister() { - TopicListener listener2 = mock(TopicListener.class); - source.register(listener); - source.register(listener2); - - // unregister first listener - should NOT invoke close - source.unregister(listener); - verify(cons, never()).close(); - assertEquals(Arrays.asList(listener2), source.snapshotTopicListeners()); - - // unregister same listener - should not invoke close - source.unregister(listener); - verify(cons, never()).close(); - assertEquals(Arrays.asList(listener2), source.snapshotTopicListeners()); - - // unregister second listener - SHOULD invoke close - source.unregister(listener2); - verify(cons).close(); - assertTrue(source.snapshotTopicListeners().isEmpty()); - - // unregister same listener - should not invoke close again - source.unregister(listener2); - verify(cons).close(); - assertTrue(source.snapshotTopicListeners().isEmpty()); - } - - @Test - public void testToString() { - assertTrue(source.toString().startsWith("SingleThreadedBusTopicSource [")); - } - - @Test - public void testMakePollerThread() { - SingleThreadedBusTopicSource source2 = new SingleThreadedBusTopicSource(makeBuilder().build()) { - @Override - public CommInfrastructure getTopicCommInfrastructure() { - return CommInfrastructure.NOOP; - } - - @Override - public void init() throws MalformedURLException { - // do nothing - } - }; - - assertNotNull(source2.makePollerThread()); - } - - @Test - public void testSingleThreadedBusTopicSource() { - // verify that different wrappers can be built - new SingleThreadedBusTopicSourceImpl(makeBuilder().consumerGroup(null).build()); - new SingleThreadedBusTopicSourceImpl(makeBuilder().consumerInstance(null).build()); - new SingleThreadedBusTopicSourceImpl(makeBuilder().fetchTimeout(-1).build()); - assertThatCode(() -> new SingleThreadedBusTopicSourceImpl(makeBuilder().fetchLimit(-1).build())) - .doesNotThrowAnyException(); - } - - @Test - public void testStart() { - source.start(); - assertTrue(source.isAlive()); - assertEquals(1, source.initCount); - verify(thread).start(); - - // attempt to start again - nothing should be invoked again - source.start(); - assertTrue(source.isAlive()); - assertEquals(1, source.initCount); - verify(thread).start(); - - // stop & re-start - source.stop(); - source.start(); - assertTrue(source.isAlive()); - assertEquals(2, source.initCount); - verify(thread, times(2)).start(); - } - - @Test(expected = IllegalStateException.class) - public void testStart_Locked() { - source.lock(); - source.start(); - } - - @Test(expected = IllegalStateException.class) - public void testStart_InitEx() { - source.initEx = true; - source.start(); - } - - @Test - public void testStop() { - source.start(); - source.stop(); - verify(cons).close(); - - // stop it again - not re-closed - source.stop(); - verify(cons).close(); - - // start & stop again, but with an exception - doThrow(new RuntimeException(EXPECTED)).when(cons).close(); - source.start(); - source.stop(); - } - - @Test - public void testRun() throws Exception { - source.register(listener); - - /* - * Die in the middle of fetching messages. Also, throw an exception during the - * first fetch attempt. - */ - when(cons.fetch()).thenAnswer(new Answer<Iterable<String>>() { - int count = 0; - - @Override - public Iterable<String> answer(InvocationOnMock invocation) throws Throwable { - if (++count > 1) { - source.alive = false; - return Arrays.asList(MY_MESSAGE, MY_MESSAGE2); - - } else { - throw new IOException(EXPECTED); - } - } - }); - source.alive = true; - source.run(); - assertEquals(Arrays.asList(MY_MESSAGE), Arrays.asList(source.getRecentEvents())); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE); - verify(listener, never()).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE2); - - /* - * Die AFTER fetching messages. - */ - final String msga = "message-A"; - final String msgb = "message-B"; - when(cons.fetch()).thenAnswer(new Answer<Iterable<String>>() { - int count = 0; - - @Override - public Iterable<String> answer(InvocationOnMock invocation) throws Throwable { - if (++count > 1) { - source.alive = false; - return Collections.emptyList(); - - } else { - return Arrays.asList(msga, msgb); - } - } - }); - source.alive = true; - source.run(); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, msga); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, msgb); - - assertEquals(Arrays.asList(MY_MESSAGE, msga, msgb), Arrays.asList(source.getRecentEvents())); - } - - @Test - public void testOffer() { - source.register(listener); - source.offer(MY_MESSAGE); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE); - assertEquals(Arrays.asList(MY_MESSAGE), Arrays.asList(source.getRecentEvents())); - } - - @Test(expected = IllegalStateException.class) - public void testOffer_NotStarted() { - source.offer(MY_MESSAGE); - } - - @Test - public void testSetFilter() { - FilterableBusConsumer filt = mock(FilterableBusConsumer.class); - cons = filt; - - source.start(); - source.setFilter("my-filter"); - verify(filt).setFilter("my-filter"); - } - - @Test(expected = UnsupportedOperationException.class) - public void testSetFilter_Unsupported() { - source.start(); - source.setFilter("unsupported-filter"); - } - - @Test - public void testGetConsumerGroup() { - assertEquals(MY_CONS_GROUP, source.getConsumerGroup()); - } - - @Test - public void testGetConsumerInstance() { - assertEquals(MY_CONS_INST, source.getConsumerInstance()); - } - - @Test - public void testShutdown() { - source.register(listener); - - source.shutdown(); - verify(cons).close(); - assertTrue(source.snapshotTopicListeners().isEmpty()); - } - - @Test - public void testGetFetchTimeout() { - assertEquals(MY_FETCH_TIMEOUT, source.getFetchTimeout()); - } - - @Test - public void testGetFetchLimit() { - assertEquals(MY_FETCH_LIMIT, source.getFetchLimit()); - } - - /** - * Implementation of SingleThreadedBusTopicSource that counts the number of times - * init() is invoked. - */ - private class SingleThreadedBusTopicSourceImpl extends SingleThreadedBusTopicSource { - - private int initCount = 0; - private boolean initEx = false; - - public SingleThreadedBusTopicSourceImpl(BusTopicParams busTopicParams) { - super(busTopicParams); - } - - @Override - public CommInfrastructure getTopicCommInfrastructure() { - return CommInfrastructure.NOOP; - } - - @Override - public void init() throws MalformedURLException { - ++initCount; - - if (initEx) { - throw new MalformedURLException(EXPECTED); - } - - consumer = cons; - } - - @Override - protected Thread makePollerThread() { - return thread; - } - - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSourceTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSourceTest.java deleted file mode 100644 index c7d30025..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedDmaapTopicSourceTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.net.MalformedURLException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.utils.gson.GsonTestUtils; - -public class SingleThreadedDmaapTopicSourceTest extends TopicTestBase { - private static final String SOURCE_NAME = "SingleThreadedDmaapTopicSource ["; - private SingleThreadedDmaapTopicSource source; - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - source = new SingleThreadedDmaapTopicSource(makeBuilder().build()); - } - - @After - public void tearDown() { - source.shutdown(); - } - - @Test - public void testSerialize() { - assertThatCode(() -> new GsonTestUtils().compareGson(source, SingleThreadedDmaapTopicSourceTest.class)) - .doesNotThrowAnyException(); - } - - @Test - public void testToString() { - assertTrue(source.toString().startsWith(SOURCE_NAME)); - source.shutdown(); - - // try with null password - source = new SingleThreadedDmaapTopicSource(makeBuilder().password(null).build()); - assertTrue(source.toString().startsWith(SOURCE_NAME)); - source.shutdown(); - - // try with empty password - source = new SingleThreadedDmaapTopicSource(makeBuilder().password("").build()); - assertTrue(source.toString().startsWith(SOURCE_NAME)); - source.shutdown(); - } - - @Test - public void testInit() { - // verify with different parameters - new SingleThreadedDmaapTopicSource(makeBuilder().environment(null).aftEnvironment(null).latitude(null) - .longitude(null).partner(null).build()).shutdown(); - assertThatCode(() -> new SingleThreadedDmaapTopicSource(makeBuilder().userName(null).build()).shutdown()) - .doesNotThrowAnyException(); - } - - @Test(expected = IllegalArgumentException.class) - public void testSingleThreadedDmaapTopicSource_Ex() { - new SingleThreadedDmaapTopicSource(makeBuilder().build()) { - @Override - public void init() throws MalformedURLException { - throw new MalformedURLException(EXPECTED); - } - }.shutdown(); - } - - @Test - public void testGetTopicCommInfrastructure() { - assertEquals(CommInfrastructure.DMAAP, source.getTopicCommInfrastructure()); - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.java deleted file mode 100644 index 6536d0e8..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedUebTopicSourceTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.utils.gson.GsonTestUtils; - -public class SingleThreadedUebTopicSourceTest extends TopicTestBase { - private SingleThreadedUebTopicSource source; - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - source = new SingleThreadedUebTopicSource(makeBuilder().build()); - } - - @After - public void tearDown() { - source.shutdown(); - } - - @Test - public void testSerialize() { - assertThatCode(() -> new GsonTestUtils().compareGson(source, SingleThreadedUebTopicSourceTest.class)) - .doesNotThrowAnyException(); - } - - @Test - public void testToString() { - assertTrue(source.toString().startsWith("SingleThreadedUebTopicSource [")); - source.shutdown(); - } - - @Test - public void testGetTopicCommInfrastructure() { - assertEquals(CommInfrastructure.UEB, source.getTopicCommInfrastructure()); - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBaseTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBaseTest.java deleted file mode 100644 index 67b84ea8..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/TopicBaseTest.java +++ /dev/null @@ -1,341 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.bus.internal; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.bus.TopicTestBase; -import org.onap.policy.common.utils.gson.GsonTestUtils; - -public class TopicBaseTest extends TopicTestBase { - - private TopicBaseImpl base; - - /** - * Creates the object to be tested. - */ - @Before - @Override - public void setUp() { - super.setUp(); - - base = new TopicBaseImpl(servers, MY_TOPIC); - } - - @Test(expected = IllegalArgumentException.class) - public void testTopicBase_NullServers() { - new TopicBaseImpl(null, MY_TOPIC); - } - - @Test(expected = IllegalArgumentException.class) - public void testTopicBase_EmptyServers() { - new TopicBaseImpl(Collections.emptyList(), MY_TOPIC); - } - - @Test(expected = IllegalArgumentException.class) - public void testTopicBase_NullTopic() { - new TopicBaseImpl(servers, null); - } - - @Test(expected = IllegalArgumentException.class) - public void testTopicBase_EmptyTopic() { - new TopicBaseImpl(servers, ""); - } - - @Test - public void testTopicBase_EffectiveTopic() { - TopicBase baseEf = new TopicBaseImpl(servers, MY_TOPIC, MY_EFFECTIVE_TOPIC); - assertEquals(MY_TOPIC, baseEf.getTopic()); - assertEquals(MY_EFFECTIVE_TOPIC, baseEf.getEffectiveTopic()); - } - - @Test - public void testTopicBase_NullEffectiveTopic() { - TopicBase baseEf = new TopicBaseImpl(servers, MY_TOPIC, null); - assertEquals(MY_TOPIC, baseEf.getTopic()); - assertEquals(MY_TOPIC, baseEf.getEffectiveTopic()); - } - - @Test - public void testTopicBase_EmptyEffectiveTopic() { - TopicBase baseEf = new TopicBaseImpl(servers, MY_TOPIC, ""); - assertEquals(MY_TOPIC, baseEf.getTopic()); - assertEquals(MY_TOPIC, baseEf.getEffectiveTopic()); - } - - @Test - public void testSerialize() { - assertThatCode(() -> new GsonTestUtils().compareGson(base, TopicBaseTest.class)).doesNotThrowAnyException(); - } - - @Test - public void testRegister() { - TopicListener listener = mock(TopicListener.class); - base.register(listener); - assertEquals(Arrays.asList(listener), base.snapshotTopicListeners()); - - // re-register - list should be unchanged - base.register(listener); - assertEquals(Arrays.asList(listener), base.snapshotTopicListeners()); - - // register a new listener - TopicListener listener2 = mock(TopicListener.class); - base.register(listener2); - assertEquals(Arrays.asList(listener, listener2), base.snapshotTopicListeners()); - } - - @Test(expected = IllegalArgumentException.class) - public void testRegister_NullListener() { - base.register(null); - } - - @Test - public void testUnregister() { - // register two listeners - TopicListener listener = mock(TopicListener.class); - TopicListener listener2 = mock(TopicListener.class); - base.register(listener); - base.register(listener2); - - // unregister one - base.unregister(listener); - assertEquals(Arrays.asList(listener2), base.snapshotTopicListeners()); - - // unregister the other - base.unregister(listener2); - assertTrue(base.snapshotTopicListeners().isEmpty()); - - // unregister again - base.unregister(listener2); - assertTrue(base.snapshotTopicListeners().isEmpty()); - } - - @Test(expected = IllegalArgumentException.class) - public void testUnregister_NullListener() { - base.register(mock(TopicListener.class)); - base.unregister(null); - } - - @Test - public void testBroadcast() { - // register two listeners - TopicListener listener = mock(TopicListener.class); - TopicListener listener2 = mock(TopicListener.class); - base.register(listener); - base.register(listener2); - - // broadcast a message - final String msg1 = "message-A"; - base.broadcast(msg1); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, msg1); - verify(listener2).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, msg1); - - // broadcast another message, with an exception - final String msg2 = "message-B"; - doThrow(new RuntimeException(EXPECTED)).when(listener).onTopicEvent(any(), any(), any()); - base.broadcast(msg2); - verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, msg2); - verify(listener2).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, msg2); - } - - @Test - public void testLock_testUnlock() { - assertFalse(base.isLocked()); - assertTrue(base.lock()); - assertEquals(0, base.startCount); - assertEquals(1, base.stopCount); - - // lock again - should not stop again - assertTrue(base.isLocked()); - assertTrue(base.lock()); - assertEquals(0, base.startCount); - assertEquals(1, base.stopCount); - - assertTrue(base.isLocked()); - assertTrue(base.unlock()); - assertEquals(1, base.startCount); - assertEquals(1, base.stopCount); - - // unlock again - should not start again - assertFalse(base.isLocked()); - assertTrue(base.unlock()); - assertEquals(1, base.startCount); - assertEquals(1, base.stopCount); - - // lock, but stop returns false - base = new TopicBaseImpl(servers, MY_TOPIC); - base.stopReturn = false; - assertFalse(base.lock()); - assertTrue(base.isLocked()); - assertTrue(base.lock()); - - // unlock, but start returns false - base.startReturn = false; - assertFalse(base.unlock()); - assertFalse(base.isLocked()); - assertTrue(base.unlock()); - - // lock & re-lock, but start throws an exception - base = new TopicBaseImpl(servers, MY_TOPIC); - base.startEx = true; - assertTrue(base.lock()); - assertFalse(base.unlock()); - assertFalse(base.isLocked()); - assertTrue(base.unlock()); - } - - @Test - public void testIsLocked() { - assertFalse(base.isLocked()); - base.lock(); - assertTrue(base.isLocked()); - base.unlock(); - assertFalse(base.isLocked()); - } - - @Test - public void testGetTopic() { - assertEquals(MY_TOPIC, base.getTopic()); - } - - @Test - public void testGetEffectiveTopic() { - assertEquals(MY_TOPIC, base.getTopic()); - assertEquals(MY_TOPIC, base.getEffectiveTopic()); - } - - @Test - public void testIsAlive() { - assertFalse(base.isAlive()); - base.start(); - assertTrue(base.isAlive()); - base.stop(); - assertFalse(base.isAlive()); - } - - @Test - public void testGetServers() { - assertEquals(servers, base.getServers()); - } - - @Test - public void testGetRecentEvents() { - assertEquals(0, base.getRecentEvents().length); - - base.addEvent("recent-A"); - base.addEvent("recent-B"); - - String[] recent = base.getRecentEvents(); - assertEquals(2, recent.length); - assertEquals("recent-A", recent[0]); - assertEquals("recent-B", recent[1]); - } - - @Test - public void testToString() { - assertNotNull(base.toString()); - } - - /** - * Implementation of TopicBase. - */ - private static class TopicBaseImpl extends TopicBase { - private int startCount = 0; - private int stopCount = 0; - private boolean startReturn = true; - private boolean stopReturn = true; - private boolean startEx = false; - - /** - * Constructor. - * - * @param servers list of servers - * @param topic topic name - */ - public TopicBaseImpl(List<String> servers, String topic) { - super(servers, topic); - } - - /** - * Constructor. - * - * @param servers list of servers - * @param topic topic name - * @param effectiveTopic effective topic name for network communication - */ - public TopicBaseImpl(List<String> servers, String topic, String effectiveTopic) { - super(servers, topic, effectiveTopic); - } - - @Override - public CommInfrastructure getTopicCommInfrastructure() { - return CommInfrastructure.NOOP; - } - - @Override - public boolean start() { - ++startCount; - - if (startEx) { - throw new RuntimeException(EXPECTED); - } - - alive = true; - return startReturn; - } - - @Override - public boolean stop() { - ++stopCount; - alive = false; - return stopReturn; - } - - @Override - public void shutdown() { - // do nothing - } - - /** - * Adds an event to the list of recent events. - * - * @param event event to be added - */ - public void addEvent(String event) { - recentEvents.add(event); - } - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientTest.java deleted file mode 100644 index 3f0a002c..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/BidirectionalTopicClientTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2020 AT&T Intellectual Property. 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.policy.common.endpoints.event.comm.client; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Properties; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.event.comm.TopicSource; - -public class BidirectionalTopicClientTest { - private static final String SINK_TOPIC = "my-sink-topic"; - private static final String SOURCE_TOPIC = "my-source-topic"; - - private static final CommInfrastructure SINK_INFRA = CommInfrastructure.UEB; - private static final CommInfrastructure SOURCE_INFRA = CommInfrastructure.NOOP; - - @Mock - private TopicSink sink; - @Mock - private TopicSource source; - @Mock - private TopicEndpoint endpoint; - @Mock - private TopicListener listener; - - private BidirectionalTopicClient client; - - /** - * Configures the endpoints. - */ - @BeforeClass - public static void setUpBeforeClass() { - Properties props = new Properties(); - props.setProperty("noop.sink.topics", SINK_TOPIC); - props.setProperty("noop.source.topics", SOURCE_TOPIC); - - // clear all topics and then configure one sink and one source - TopicEndpointManager.getManager().shutdown(); - TopicEndpointManager.getManager().addTopicSinks(props); - TopicEndpointManager.getManager().addTopicSources(props); - } - - @AfterClass - public static void tearDownAfterClass() { - // clear all topics after the tests - TopicEndpointManager.getManager().shutdown(); - } - - /** - * Creates mocks and an initial client object. - */ - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - - when(sink.send(anyString())).thenReturn(true); - when(sink.getTopicCommInfrastructure()).thenReturn(SINK_INFRA); - - when(source.offer(anyString())).thenReturn(true); - when(source.getTopicCommInfrastructure()).thenReturn(SOURCE_INFRA); - - when(endpoint.getTopicSinks(anyString())).thenReturn(Arrays.asList()); - when(endpoint.getTopicSinks(SINK_TOPIC)).thenReturn(Arrays.asList(sink)); - - when(endpoint.getTopicSources(any())).thenReturn(Arrays.asList()); - when(endpoint.getTopicSources(eq(Arrays.asList(SOURCE_TOPIC)))).thenReturn(Arrays.asList(source)); - - client = new BidirectionalTopicClient2(SINK_TOPIC, SOURCE_TOPIC); - } - - @Test - public void testBidirectionalTopicClient_testGetters() { - assertSame(sink, client.getSink()); - assertSame(source, client.getSource()); - assertEquals(SINK_TOPIC, client.getSinkTopic()); - assertEquals(SOURCE_TOPIC, client.getSourceTopic()); - assertEquals(SINK_INFRA, client.getSinkTopicCommInfrastructure()); - assertEquals(SOURCE_INFRA, client.getSourceTopicCommInfrastructure()); - } - - /** - * Tests the constructor when the sink or source cannot be found. - */ - @Test - public void testBidirectionalTopicClientExceptions() { - assertThatThrownBy(() -> new BidirectionalTopicClient2("unknown-sink", SOURCE_TOPIC)) - .isInstanceOf(BidirectionalTopicClientException.class) - .hasMessage("no sinks for topic: unknown-sink"); - - assertThatThrownBy(() -> new BidirectionalTopicClient2(SINK_TOPIC, "unknown-source")) - .isInstanceOf(BidirectionalTopicClientException.class) - .hasMessage("no sources for topic: unknown-source"); - - // too many sources - when(endpoint.getTopicSources(eq(Arrays.asList(SOURCE_TOPIC)))).thenReturn(Arrays.asList(source, source)); - - assertThatThrownBy(() -> new BidirectionalTopicClient2(SINK_TOPIC, SOURCE_TOPIC)) - .isInstanceOf(BidirectionalTopicClientException.class) - .hasMessage("too many sources for topic: my-source-topic"); - } - - /** - * Tests the "delegate" methods. - */ - @Test - public void testDelegates() { - assertTrue(client.send("hello")); - verify(sink).send("hello"); - - assertTrue(client.offer("incoming")); - verify(source).offer("incoming"); - - client.register(listener); - verify(source).register(listener); - - client.unregister(listener); - verify(source).unregister(listener); - } - - @Test - public void testGetTopicEndpointManager() throws BidirectionalTopicClientException { - // use a real manager - client = new BidirectionalTopicClient(SINK_TOPIC, SOURCE_TOPIC); - assertNotNull(client.getTopicEndpointManager()); - - assertNotNull(client.getSink()); - assertNotNull(client.getSource()); - - assertNotSame(sink, client.getSink()); - assertNotSame(source, client.getSource()); - } - - - /** - * BidirectionalTopicClient with some overrides. - */ - private class BidirectionalTopicClient2 extends BidirectionalTopicClient { - - public BidirectionalTopicClient2(String sinkTopic, String sourceTopic) - throws BidirectionalTopicClientException { - super(sinkTopic, sourceTopic); - } - - @Override - protected TopicEndpoint getTopicEndpointManager() { - return endpoint; - } - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicClientExceptionTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicClientExceptionTest.java deleted file mode 100644 index 7b64a20f..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicClientExceptionTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP PAP - * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 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.client; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.onap.policy.common.utils.test.ExceptionsTester; - -public class TopicClientExceptionTest { - - @Test - public void test() { - assertEquals(5, new ExceptionsTester().test(TopicSinkClientException.class)); - assertEquals(5, new ExceptionsTester().test(BidirectionalTopicClientException.class)); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientTest.java deleted file mode 100644 index 48c86c98..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/client/TopicSinkClientTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP PAP - * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 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.client; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; -import org.onap.policy.common.endpoints.event.comm.TopicSink; - -public class TopicSinkClientTest { - private static final String TOPIC = "my-topic"; - - private TopicSinkClient client; - private TopicSink sink; - private List<TopicSink> sinks; - - /** - * Creates mocks and an initial client object. - * - * @throws Exception if an error occurs - */ - @Before - public void setUp() throws Exception { - sink = mock(TopicSink.class); - when(sink.send(anyString())).thenReturn(true); - - sinks = Arrays.asList(sink, null); - - client = new TopicSinkClient2(TOPIC); - - Properties props = new Properties(); - props.setProperty("noop.sink.topics", TOPIC); - - // clear all topics and then configure one topic - TopicEndpointManager.getManager().shutdown(); - TopicEndpointManager.getManager().addTopicSinks(props); - } - - @AfterClass - public static void tearDown() { - // clear all topics after the tests - TopicEndpointManager.getManager().shutdown(); - } - - /** - * Uses a real NO-OP topic sink. - */ - @Test - public void testGetTopicSinks() throws Exception { - - sink = TopicEndpointManager.getManager().getNoopTopicSink(TOPIC); - assertNotNull(sink); - - final AtomicReference<String> evref = new AtomicReference<>(null); - - sink.register((infra, topic, event) -> evref.set(event)); - sink.start(); - - client = new TopicSinkClient(TOPIC); - client.send(100); - - assertEquals("100", evref.get()); - } - - @Test - public void testTopicSinkClient() { - // unknown topic -> should throw exception - sinks = new LinkedList<>(); - assertThatThrownBy(() -> new TopicSinkClient2(TOPIC)).isInstanceOf(TopicSinkClientException.class) - .hasMessage("no sinks for topic: my-topic"); - } - - @Test - public void testTopicSinkClient_GetTopic() throws TopicSinkClientException { - assertEquals(TOPIC, new TopicSinkClient(TopicEndpointManager.getManager().getNoopTopicSink(TOPIC)).getTopic()); - assertEquals(TOPIC, new TopicSinkClient(TOPIC).getTopic()); - - assertThatThrownBy(() -> new TopicSinkClient((TopicSink) null)).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new TopicSinkClient("blah")).isInstanceOf(TopicSinkClientException.class) - .hasMessage("no sinks for topic: blah"); - } - - @Test - public void testSend() { - client.send(Arrays.asList("abc", "def")); - verify(sink).send("['abc','def']".replace('\'', '"')); - - // sink send fails - when(sink.send(anyString())).thenReturn(false); - assertFalse(client.send("ghi")); - - // sink send throws an exception - final RuntimeException ex = new RuntimeException("expected exception"); - when(sink.send(anyString())).thenThrow(ex); - assertFalse(client.send("jkl")); - } - - /** - * TopicSinkClient with some overrides. - */ - private class TopicSinkClient2 extends TopicSinkClient { - - public TopicSinkClient2(final String topic) throws TopicSinkClientException { - super(topic); - } - - @Override - protected List<TopicSink> getTopicSinks(final String topic) { - return sinks; - } - } -} 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/http/server/test/HttpClientTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java index 7e03b1f6..10d40051 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpClientTest.java @@ -2,8 +2,9 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright 2023-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. @@ -21,12 +22,17 @@ package org.onap.policy.common.endpoints.http.server.test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - +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.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.prometheus.client.servlet.jakarta.exporter.MetricsServlet; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.InvocationCallback; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -34,16 +40,12 @@ import java.util.Properties; import java.util.TreeMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.InvocationCallback; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import lombok.Getter; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; +import lombok.Setter; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.http.client.HttpClient; import org.onap.policy.common.endpoints.http.client.HttpClientConfigException; import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; @@ -51,9 +53,10 @@ import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; import org.onap.policy.common.endpoints.http.server.internal.JettyJerseyServer; import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; +import org.onap.policy.common.parameters.topic.BusTopicParams; import org.onap.policy.common.utils.network.NetworkUtil; -public class HttpClientTest { +class HttpClientTest { private static final String TEST_HTTP_NO_AUTH_CLIENT = "testHttpNoAuthClient"; private static final String TEST_HTTP_AUTH_CLIENT = "testHttpAuthClient"; private static final String LOCALHOST = "localhost"; @@ -73,7 +76,7 @@ public class HttpClientTest { * * @throws InterruptedException can be interrupted */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws InterruptedException { /* echo server - http + no auth */ @@ -119,13 +122,11 @@ public class HttpClientTest { /* echo server - https + basic auth */ final HttpServletServer echoServerAuth = HttpServletServerFactoryInstance.getServerFactory() - .build("echo", true, LOCALHOST, 6667, "/", false, true); + .build("echo", true, LOCALHOST, 6667, false, "/", false, true); echoServerAuth.setBasicAuthentication("x", "y", null); echoServerAuth.addServletPackage("/*", HttpClientTest.class.getPackage().getName()); echoServerAuth.addFilterClass("/*", TestFilter.class.getName()); echoServerAuth.addFilterClass("/*", TestAuthorizationFilter.class.getName()); - echoServerAuth.addFilterClass("/*", TestAafAuthFilter.class.getName()); - echoServerAuth.addFilterClass("/*", TestAafGranularAuthFilter.class.getName()); echoServerAuth.waitedStart(5000); if (!NetworkUtil.isTcpPortOpen(LOCALHOST, echoServerAuth.getPort(), 5, 10000L)) { @@ -136,7 +137,7 @@ public class HttpClientTest { /** * Clear https clients and reset providers. */ - @Before + @BeforeEach public void setUp() { HttpClientFactoryInstance.getClientFactory().destroy(); @@ -146,7 +147,7 @@ public class HttpClientTest { /** * After the class is created method. */ - @AfterClass + @AfterAll public static void tearDownAfterClass() { HttpServletServerFactoryInstance.getServerFactory().destroy(); HttpClientFactoryInstance.getClientFactory().destroy(); @@ -187,7 +188,7 @@ public class HttpClientTest { } @Test - public void testHttpGetNoAuthClient() throws Exception { + void testHttpGetNoAuthClient() throws Exception { final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666); final Response response = client.get(HELLO); @@ -198,7 +199,7 @@ public class HttpClientTest { } @Test - public void testHttpGetNoAuthClientAsync() throws Exception { + void testHttpGetNoAuthClientAsync() throws Exception { final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666); MyCallback callback = new MyCallback(); @@ -214,13 +215,13 @@ public class HttpClientTest { private void verifyCallback(String testName, MyCallback callback, final Response response) throws InterruptedException { - assertTrue(testName, callback.await()); - assertNull(testName, callback.getThrowable()); - assertSame(testName, response, callback.getResponse()); + assertTrue(callback.await(), testName); + assertNull(callback.getThrowable(), testName); + assertSame(response, callback.getResponse(), testName); } @Test - public void testHttpPutNoAuthClient() throws Exception { + void testHttpPutNoAuthClient() throws Exception { final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666); Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON); @@ -232,7 +233,7 @@ public class HttpClientTest { } @Test - public void testHttpPutNoAuthClientAsync() throws Exception { + void testHttpPutNoAuthClientAsync() throws Exception { final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666); Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON); @@ -248,7 +249,7 @@ public class HttpClientTest { } @Test - public void testHttpPostNoAuthClient() throws Exception { + void testHttpPostNoAuthClient() throws Exception { final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666); @@ -261,7 +262,7 @@ public class HttpClientTest { } @Test - public void testHttpPostNoAuthClientAsync() throws Exception { + void testHttpPostNoAuthClientAsync() throws Exception { final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666); @@ -278,7 +279,7 @@ public class HttpClientTest { } @Test - public void testHttpDeletetNoAuthClient() throws Exception { + void testHttpDeletetNoAuthClient() throws Exception { final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666); @@ -290,7 +291,7 @@ public class HttpClientTest { } @Test - public void testHttpDeletetNoAuthClientAsync() throws Exception { + void testHttpDeletetNoAuthClientAsync() throws Exception { final HttpClient client = getNoAuthHttpClient(TEST_HTTP_NO_AUTH_CLIENT, false, 6666); @@ -310,7 +311,7 @@ public class HttpClientTest { * @throws Exception if an error occurs */ @Test - public void testHttpAsyncAuthClient() throws Exception { + void testHttpAsyncAuthClient() throws Exception { final HttpClient client = getAuthHttpClient(); MyCallback callback = new MyCallback(); @@ -325,7 +326,7 @@ public class HttpClientTest { } @Test - public void testHttpGetAuthClient() throws Exception { + void testHttpGetAuthClient() throws Exception { final HttpClient client = getAuthHttpClient(); final Response response = client.get(HELLO); @@ -336,7 +337,7 @@ public class HttpClientTest { } @Test - public void testHttpPutAuthClient() throws Exception { + void testHttpPutAuthClient() throws Exception { final HttpClient client = getAuthHttpClient(); Entity<MyEntity> entity = Entity.entity(new MyEntity(MY_VALUE), MediaType.APPLICATION_JSON); @@ -348,7 +349,7 @@ public class HttpClientTest { } @Test - public void testHttpPutAuthClient_GsonProvider() throws Exception { + void testHttpPutAuthClient_GsonProvider() throws Exception { final HttpClient client = HttpClientFactoryInstance.getClientFactory() .build(BusTopicParams.builder().clientName(TEST_HTTP_AUTH_CLIENT).useHttps(true) .allowSelfSignedCerts(true).hostname(LOCALHOST).port(6667).basePath(JUNIT_ECHO) @@ -366,7 +367,7 @@ public class HttpClientTest { } @Test - public void testHttpAuthClient401() throws Exception { + void testHttpAuthClient401() throws Exception { final HttpClient client = getNoAuthHttpClient("testHttpAuthClient401", true, 6667); final Response response = client.get(HELLO); @@ -374,10 +375,15 @@ public class HttpClientTest { } @Test - public void testHttpAuthClientProps() throws Exception { + void testHttpAuthClientProps() throws Exception { final Properties httpProperties = new Properties(); + /* PAP and PDP services */ + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, "PAP,PDP"); + + /* PAP server service configuration */ + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST); httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP @@ -394,8 +400,15 @@ public class HttpClientTest { PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP + PolicyEndPointProperties.PROPERTY_HTTP_FILTER_CLASSES_SUFFIX, TestFilter.class.getName()); - httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP + + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_CLASS_SUFFIX, MetricsServlet.class.getName()); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PAP + + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_URIPATH_SUFFIX, + "/pap/test/random/metrics"); + + /* PDP server service configuration */ httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST); @@ -409,10 +422,19 @@ public class HttpClientTest { PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, RestMockHealthCheck.class.getName()); - httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP + + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "true"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + DOT_PDP + + PolicyEndPointProperties.PROPERTY_HTTP_PROMETHEUS_SUFFIX, "true"); + + /* PDP and PAP client services */ httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES, "PAP,PDP"); + + /* PAP client service configuration */ + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST); httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP @@ -428,13 +450,13 @@ public class HttpClientTest { httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PAP + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true"); + /* PDP client service configuration */ + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, LOCALHOST); httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7778"); httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP - + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, "pdp"); - httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, FALSE_STRING); httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + DOT_PDP + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpdp"); @@ -460,15 +482,28 @@ public class HttpClientTest { assertEquals(200, response.getStatus()); final HttpClient clientPdp = HttpClientFactoryInstance.getClientFactory().get("PDP"); - response = clientPdp.get("test"); + + response = clientPdp.get("pdp/test"); assertEquals(500, response.getStatus()); + response = clientPdp.get("metrics"); + assertEquals(200, response.getStatus()); + + response = clientPdp.get("openapi.json"); + assertEquals(200, response.getStatus()); + assertFalse(MyGsonProvider.hasWrittenSome()); // try with empty path response = clientPap.get(""); assertEquals(200, response.getStatus()); + response = clientPap.get("random/metrics"); + assertEquals(200, response.getStatus()); + + response = clientPap.get("metrics"); + assertEquals(404, response.getStatus()); + // try it asynchronously, too MyCallback callback = new MyCallback(); response = clientPap.get(callback, null).get(); @@ -498,7 +533,9 @@ public class HttpClientTest { } - class MyEntity { + @Setter + @Getter + static class MyEntity { private String myParameter; @@ -506,24 +543,16 @@ public class HttpClientTest { this.myParameter = myParameter; } - public void setMyParameter(final String myParameter) { - this.myParameter = myParameter; - } - - public String getMyParameter() { - return myParameter; - } - } - class MyCallback implements InvocationCallback<Response> { + static class MyCallback implements InvocationCallback<Response> { @Getter private Response response; @Getter private Throwable throwable; - private CountDownLatch latch = new CountDownLatch(1); + private final CountDownLatch latch = new CountDownLatch(1); @Override public void completed(Response response) { diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpExceptionsTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpExceptionsTest.java index 85135759..aaa9c489 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpExceptionsTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpExceptionsTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications 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. @@ -20,14 +21,14 @@ package org.onap.policy.common.endpoints.http.server.test; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.http.client.HttpClientConfigException; import org.onap.policy.common.utils.test.ExceptionsTester; -public class HttpExceptionsTest extends ExceptionsTester { +class HttpExceptionsTest extends ExceptionsTester { @Test - public void testHttpClientConfigException() { + void testHttpClientConfigException() { test(HttpClientConfigException.class); } } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java index 68c9dc8a..399754a6 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/HttpServerTest.java @@ -3,7 +3,8 @@ * ONAP * ================================================================================ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020, 2023-2024 Nordix Foundation. + * Modifications Copyright (C) 2021 Bell Canada. 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. @@ -25,12 +26,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.gson.Gson; +import io.prometheus.client.servlet.jakarta.exporter.MetricsServlet; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; @@ -38,11 +40,12 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; +import java.util.Objects; import java.util.UUID; import org.apache.commons.io.IOUtils; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler; @@ -55,11 +58,14 @@ import org.slf4j.LoggerFactory; /** * HttpServletServer JUNIT tests. */ -public class HttpServerTest { +class HttpServerTest { + private static final String JVM_MEMORY_BYTES_USED = "jvm_memory_bytes_used"; + private static final String METRICS_URI = "/metrics"; + private static final String PROMETHEUS = "prometheus"; private static final String LOCALHOST = "localhost"; private static final String JSON_MEDIA = "application/json"; private static final String YAML_MEDIA = YamlMessageBodyHandler.APPLICATION_YAML; - private static final String SWAGGER_JSON = "/swagger.json"; + private static final String SWAGGER_JSON = "/openapi.json"; private static final String JUNIT_ECHO_HELLO = "/junit/echo/hello"; private static final String JUNIT_ECHO_FULL_REQUEST = "/junit/echo/full/request"; private static final String SOME_TEXT = "some text"; @@ -68,7 +74,7 @@ public class HttpServerTest { /** * Logger. */ - private static Logger logger = LoggerFactory.getLogger(HttpServerTest.class); + private static final Logger logger = LoggerFactory.getLogger(HttpServerTest.class); private static final String LOCALHOST_PREFIX = "http://localhost:"; @@ -84,7 +90,7 @@ public class HttpServerTest { /** * Increments the port number, clears the servers, and resets the providers. */ - @Before + @BeforeEach public void setUp() { incrementPort(); portUrl = LOCALHOST_PREFIX + port; @@ -102,7 +108,7 @@ public class HttpServerTest { /** * To delete temporary properties cadi_longitude,and cadi_latitude. */ - @AfterClass + @AfterAll public static void tearDownAfterClass() { HttpServletServerFactoryInstance.getServerFactory().destroy(); System.clearProperty("cadi_longitude"); @@ -110,7 +116,7 @@ public class HttpServerTest { } @Test - public void testDefaultPackageServer() throws Exception { + void testDefaultPackageServer() throws Exception { logger.info("-- testDefaultPackageServer() --"); HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() @@ -131,7 +137,7 @@ public class HttpServerTest { } @Test - public void testGsonPackageServer() throws Exception { + void testGsonPackageServer() throws Exception { logger.info("-- testGsonPackageServer() --"); HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() @@ -160,7 +166,7 @@ public class HttpServerTest { } @Test - public void testYamlPackageServer() throws Exception { + void testYamlPackageServer() throws Exception { logger.info("-- testYamlPackageServer() --"); HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() @@ -191,7 +197,7 @@ public class HttpServerTest { } @Test - public void testDefaultClassServer() throws Exception { + void testDefaultClassServer() throws Exception { logger.info("-- testDefaultClassServer() --"); HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() @@ -211,8 +217,81 @@ public class HttpServerTest { assertEquals(reqText, response); } + /** + * This test checks a server from a plain java servlet (note it uses prometheus as the sample server). + */ + @Test + void testStdServletServer() throws Exception { + logger.info("-- testStdServletServer() --"); + + HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() + .build(PROMETHEUS, LOCALHOST, port, "/", false, true); + + server.addStdServletClass("/prom-generic-servlet/metrics", MetricsServlet.class.getName()); + server.waitedStart(5000); + + assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive()); + assertTrue(server.isPrometheus()); + + String response = http(portUrl + "/prom-generic-servlet/metrics"); + assertThat(response).contains(JVM_MEMORY_BYTES_USED); + } + + /** + * This test explicitly creates a prometheus server. + */ + @Test + void testExplicitPrometheusServer() throws Exception { + logger.info("-- testExplicitPrometheusServer() --"); + + HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() + .build(PROMETHEUS, LOCALHOST, port, "/", false, true); + server.setPrometheus(METRICS_URI); + server.waitedStart(5000); + + assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive()); + assertTrue(server.isPrometheus()); + + String response = http(portUrl + METRICS_URI); + assertThat(response).contains(JVM_MEMORY_BYTES_USED); + } + + /** + * This test is an all-in-one for a single server: prometheus, jax-rs, servlet, swagger, and filters. + */ + @Test + void testPrometheusJaxRsFilterSwaggerServer() throws Exception { + logger.info("-- testPrometheusJaxRsFilterSwaggerServer() --"); + + HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() + .build(PROMETHEUS, LOCALHOST, port, "/", true, true); + + server.addServletClass("/*", RestEchoService.class.getName()); + server.addFilterClass("/*", TestFilter.class.getName()); + server.setPrometheus(METRICS_URI); + + server.waitedStart(5000); + + assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive()); + assertTrue(server.isPrometheus()); + + String response = http(portUrl + METRICS_URI); + assertThat(response).contains(JVM_MEMORY_BYTES_USED); + + RestEchoReqResp request = new RestEchoReqResp(); + request.setRequestId(100); + request.setText(SOME_TEXT); + String reqText = gson.toJson(request); + + response = http(portUrl + JUNIT_ECHO_FULL_REQUEST, JSON_MEDIA, reqText); + assertEquals(reqText, response); + + response = http(portUrl + SWAGGER_JSON); + assertThat(response).contains("openapi"); + } + @Test - public void testJacksonClassServer() throws Exception { + void testJacksonClassServer() throws Exception { logger.info("-- testJacksonClassServer() --"); HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() @@ -239,7 +318,7 @@ public class HttpServerTest { } @Test - public void testGsonClassServer() throws Exception { + void testGsonClassServer() throws Exception { logger.info("-- testGsonClassServer() --"); HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() @@ -267,7 +346,7 @@ public class HttpServerTest { } @Test - public void testYamlClassServer() throws Exception { + void testYamlClassServer() throws Exception { logger.info("-- testYamlClassServer() --"); HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() @@ -297,18 +376,19 @@ public class HttpServerTest { } @Test - public void testSerialize() { + void testSerialize() { HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() .build("echo", LOCALHOST, port, "/", false, true); server.addServletPackage("/*", this.getClass().getPackage().getName()); server.addFilterClass("/*", TestFilter.class.getName()); // ensure we can serialize the server + new GsonTestUtils().compareGson(server, HttpServerTest.class); assertThatCode(() -> new GsonTestUtils().compareGson(server, HttpServerTest.class)).doesNotThrowAnyException(); } @Test - public void testSingleServer() throws Exception { + void testSingleServer() throws Exception { logger.info("-- testSingleServer() --"); HttpServletServer server = HttpServletServerFactoryInstance.getServerFactory() @@ -318,7 +398,6 @@ public class HttpServerTest { server.waitedStart(5000); assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive()); - assertFalse(HttpServletServerFactoryInstance.getServerFactory().get(port).isAaf()); String response = http(portUrl + JUNIT_ECHO_HELLO); assertEquals(HELLO, response); @@ -331,21 +410,16 @@ public class HttpServerTest { assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive()); assertEquals(1, HttpServletServerFactoryInstance.getServerFactory().inventory().size()); - System.setProperty("cadi_longitude", "0.0"); - System.setProperty("cadi_latitude", "0.0"); - server.setAafAuthentication("/*"); - assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAaf()); - HttpServletServerFactoryInstance.getServerFactory().destroy(port); assertEquals(0, HttpServletServerFactoryInstance.getServerFactory().inventory().size()); } @Test - public void testMultipleServers() throws Exception { + void testMultipleServers() throws Exception { logger.info("-- testMultipleServers() --"); HttpServletServer server1 = HttpServletServerFactoryInstance.getServerFactory() - .build("echo-1", false, LOCALHOST, port, "/", true, true); + .build("echo-1", false, LOCALHOST, port, false, "/", true, true); server1.addServletPackage("/*", this.getClass().getPackage().getName()); server1.waitedStart(5000); @@ -375,7 +449,7 @@ public class HttpServerTest { } @Test - public void testMultiServicePackage() throws Exception { + void testMultiServicePackage() throws Exception { logger.info("-- testMultiServicePackage() --"); String randomName = UUID.randomUUID().toString(); @@ -398,7 +472,7 @@ public class HttpServerTest { } @Test - public void testServiceClass() throws Exception { + void testServiceClass() throws Exception { logger.info("-- testServiceClass() --"); String randomName = UUID.randomUUID().toString(); @@ -417,7 +491,7 @@ public class HttpServerTest { } @Test - public void testMultiServiceClass() throws Exception { + void testMultiServiceClass() throws Exception { logger.info("-- testMultiServiceClass() --"); String randomName = UUID.randomUUID().toString(); @@ -441,17 +515,18 @@ public class HttpServerTest { } @Test - public void testSingleStaticResourceServer() throws Exception { + void testSingleStaticResourceServer() throws Exception { logger.info("-- testSingleStaticResourceServer() --"); HttpServletServer staticServer = HttpServletServerFactoryInstance.getServerFactory() - .buildStaticResourceServer("Static Resources Server", false, LOCALHOST, port, "/", true); + .buildStaticResourceServer("Static Resources Server", false, LOCALHOST, port, false, "/", true); Throwable thrown = catchThrowable(() -> staticServer.addServletResource("/*", null)); assertThat(thrown).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("No resourceBase provided"); staticServer.addServletResource(null, - HttpServerTest.class.getClassLoader().getResource("webapps/root").toExternalForm()); + Objects.requireNonNull(HttpServerTest.class.getClassLoader().getResource("webapps/root")) + .toExternalForm()); thrown = catchThrowable(() -> staticServer.addServletClass("/*", RestEchoService.class.getName())); assertThat(thrown).isInstanceOf(UnsupportedOperationException.class) @@ -478,15 +553,17 @@ public class HttpServerTest { } @Test - public void testMultiStaticResourceServer() throws Exception { + void testMultiStaticResourceServer() throws Exception { logger.info("-- testMultiStaticResourceServer() --"); HttpServletServer staticResourceServer = HttpServletServerFactoryInstance.getServerFactory() - .buildStaticResourceServer("Static Resources Server", false, LOCALHOST, port, "/", true); + .buildStaticResourceServer("Static Resources Server", false, LOCALHOST, port, false, "/", true); staticResourceServer.addServletResource("/root/*", - HttpServerTest.class.getClassLoader().getResource("webapps/root").toExternalForm()); + Objects.requireNonNull(HttpServerTest.class.getClassLoader().getResource("webapps/root")) + .toExternalForm()); staticResourceServer.addServletResource("/alt-root/*", - HttpServerTest.class.getClassLoader().getResource("webapps/alt-root").toExternalForm()); + Objects.requireNonNull(HttpServerTest.class.getClassLoader().getResource("webapps/alt-root")) + .toExternalForm()); staticResourceServer.waitedStart(5000); assertTrue(HttpServletServerFactoryInstance.getServerFactory().get(port).isAlive()); @@ -503,13 +580,14 @@ public class HttpServerTest { } @Test - public void testMultiTypesServer() throws Exception { + void testMultiTypesServer() throws Exception { logger.info("-- testMultiTypesServer() --"); HttpServletServer staticResourceServer = HttpServletServerFactoryInstance.getServerFactory() - .buildStaticResourceServer("Static Resources Server", false, LOCALHOST, port, "/", true); + .buildStaticResourceServer("Static Resources Server", false, LOCALHOST, port, false, "/", true); staticResourceServer.addServletResource("/root/*", - HttpServerTest.class.getClassLoader().getResource("webapps/root").toExternalForm()); + Objects.requireNonNull(HttpServerTest.class.getClassLoader().getResource("webapps/root")) + .toExternalForm()); staticResourceServer.waitedStart(5000); int port2 = port + 1; @@ -518,7 +596,8 @@ public class HttpServerTest { jerseyServer.addServletPackage("/api/*", this.getClass().getPackage().getName()); Throwable thrown = catchThrowable(() -> jerseyServer.addServletResource("/root/*", - HttpServerTest.class.getClassLoader().getResource("webapps/root").toExternalForm())); + Objects.requireNonNull(HttpServerTest.class.getClassLoader().getResource("webapps/root")) + .toExternalForm())); assertThat(thrown).isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("is not supported on this type of jetty server"); @@ -554,7 +633,7 @@ public class HttpServerTest { } /** - * Performs an http request. + * Performs a http request. * * @throws MalformedURLException make sure URL is good * @throws IOException thrown is IO exception occurs diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/JsonExceptionMapperTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/JsonExceptionMapperTest.java index 59ce0c1c..e1441908 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/JsonExceptionMapperTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/JsonExceptionMapperTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023-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. @@ -20,26 +21,26 @@ package org.onap.policy.common.endpoints.http.server.test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.gson.JsonSyntaxException; -import javax.ws.rs.core.Response; -import org.junit.Before; -import org.junit.Test; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.http.server.JsonExceptionMapper; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; -public class JsonExceptionMapperTest { +class JsonExceptionMapperTest { private JsonExceptionMapper mapper; - @Before + @BeforeEach public void setUp() { mapper = new JsonExceptionMapper(); } @Test - public void testToResponse() throws CoderException { + void testToResponse() throws CoderException { JsonSyntaxException ex = new JsonSyntaxException("expected exception"); Response resp = mapper.toResponse(ex); diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyGsonProvider.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyGsonProvider.java index 8343d02d..78c41cc2 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyGsonProvider.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyGsonProvider.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +21,13 @@ package org.onap.policy.common.endpoints.http.server.test; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; import lombok.AccessLevel; import lombok.Setter; import org.onap.policy.common.gson.GsonMessageBodyHandler; diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyYamlProvider.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyYamlProvider.java index 098ecb44..624d7686 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyYamlProvider.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/MyYamlProvider.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +21,13 @@ package org.onap.policy.common.endpoints.http.server.test; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; import lombok.AccessLevel; import lombok.Setter; import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler; diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoReqResp.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoReqResp.java index 2a3e244d..2748fadd 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoReqResp.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoReqResp.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2021 AT&T Intellectual Property. 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. @@ -21,12 +21,14 @@ package org.onap.policy.common.endpoints.http.server.test; import com.google.gson.annotations.SerializedName; +import lombok.ToString; import org.onap.policy.common.gson.annotation.GsonJsonProperty; /** * "ECHO" request and response supporting serialization and de-serialization via * both jackson and gson. */ +@ToString public class RestEchoReqResp { @GsonJsonProperty("reqId") @SerializedName("reqId") @@ -51,9 +53,4 @@ public class RestEchoReqResp { public void setText(String text) { this.text = text; } - - @Override - public String toString() { - return "RestEchoReqResp [requestId=" + requestId + ", text=" + text + "]"; - } } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoService.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoService.java index 373950b2..b4a652aa 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoService.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEchoService.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,29 +21,30 @@ package org.onap.policy.common.endpoints.http.server.test; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.Status; import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler; -@Api(value = "echo") @Path("/junit/echo") public class RestEchoService { @GET @Path("{word}") @Produces(MediaType.TEXT_PLAIN) - @ApiOperation(value = "echoes back whatever received") + @Operation(summary = "echoes back whatever received") public String echo(@PathParam("word") String word) { return word; } @@ -50,7 +52,7 @@ public class RestEchoService { @PUT @Path("{word}") @Produces(MediaType.TEXT_PLAIN) - @ApiOperation(value = "echoes back whatever received") + @Operation(summary = "echoes back whatever received") public String echoPut(@PathParam("word") String word, Object entity) { return "PUT:" + word + ":" + entity.toString(); } @@ -58,7 +60,8 @@ public class RestEchoService { @POST @Path("/full/request") @Produces({MediaType.APPLICATION_JSON, YamlMessageBodyHandler.APPLICATION_YAML}) - @ApiOperation(value = "echoes back the request structure", response = RestEchoReqResp.class) + @Operation(summary = "echoes back the request structure") + @ApiResponse(content = {@Content(schema = @Schema(implementation = RestEchoReqResp.class))}) public Response echoFullyPost(RestEchoReqResp reqResp) { return Response.status(Status.OK).entity(reqResp).build(); } @@ -66,7 +69,7 @@ public class RestEchoService { @POST @Path("{word}") @Produces(MediaType.TEXT_PLAIN) - @ApiOperation(value = "echoes back whatever received") + @Operation(summary = "echoes back whatever received") public String echoPost(@PathParam("word") String word, Object entity) { return "POST:" + word + ":" + entity.toString(); } @@ -74,7 +77,7 @@ public class RestEchoService { @DELETE @Path("{word}") @Produces(MediaType.TEXT_PLAIN) - @ApiOperation(value = "echoes back whatever received") + @Operation(summary = "echoes back whatever received") public String echoDelete(@PathParam("word") String word) { return "DELETE:" + word; } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEndpoints.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEndpoints.java index cafab42f..cbcf4c9a 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEndpoints.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestEndpoints.java @@ -3,6 +3,7 @@ * policy-endpoints * ================================================================================ * Copyright (C) 2017, 2019-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,11 +21,11 @@ package org.onap.policy.common.endpoints.http.server.test; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; import java.util.List; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestMockHealthCheck.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestMockHealthCheck.java index f0d68c0c..f476dbaf 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestMockHealthCheck.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestMockHealthCheck.java @@ -3,6 +3,7 @@ * policy-endpoints * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,12 +21,12 @@ package org.onap.policy.common.endpoints.http.server.test; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.Response.Status; @Path("/") public class RestMockHealthCheck { @@ -40,7 +41,7 @@ public class RestMockHealthCheck { @GET @Path("pdp/test") @Produces(MediaType.APPLICATION_JSON) - public Response pdpHealthCheck() { + public Response pdpHealthCheck() { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("At least some Dead").build(); } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestServerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestServerTest.java index 16f17652..431dae7c 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestServerTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/RestServerTest.java @@ -2,7 +2,9 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2023-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. @@ -22,15 +24,24 @@ package org.onap.policy.common.endpoints.http.server.test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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.ArgumentMatchers.any; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import io.prometheus.client.servlet.jakarta.exporter.MetricsServlet; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; import java.io.IOException; import java.io.PrintWriter; import java.net.HttpURLConnection; @@ -38,20 +49,14 @@ import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Base64; +import java.util.List; import java.util.Properties; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; import lombok.Getter; import org.apache.commons.io.IOUtils; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactory; @@ -60,15 +65,15 @@ import org.onap.policy.common.endpoints.http.server.RestServer; import org.onap.policy.common.endpoints.http.server.RestServer.Factory; import org.onap.policy.common.endpoints.http.server.YamlExceptionMapper; import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler; -import org.onap.policy.common.endpoints.http.server.aaf.AafAuthFilter; -import org.onap.policy.common.endpoints.parameters.RestServerParameters; import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.common.gson.GsonMessageBodyHandler; +import org.onap.policy.common.parameters.rest.RestServerParameters; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.network.NetworkUtil; -import org.powermock.reflect.Whitebox; +import org.springframework.test.util.ReflectionTestUtils; -public class RestServerTest { +class RestServerTest { + private static final String METRICS_URI = "/metrics"; private static final String SERVER1 = "my-server-A"; private static final String SERVER2 = "my-server-B"; private static final String FACTORY_FIELD = "factory"; @@ -94,15 +99,15 @@ public class RestServerTest { * Starts the REST server. * @throws Exception if an error occurs */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws Exception { - saveFactory = Whitebox.getInternalState(RestServer.class, FACTORY_FIELD); + saveFactory = (Factory) ReflectionTestUtils.getField(RestServer.class, FACTORY_FIELD); realPort = NetworkUtil.allocPort(); initRealParams(); - realRest = new RestServer(params, null, RealProvider.class) { + realRest = new RestServer(params, RealProvider.class) { @Override protected Properties getServerProperties(RestServerParameters restServerParameters, String names) { Properties props = super.getServerProperties(restServerParameters, names); @@ -122,9 +127,9 @@ public class RestServerTest { /** * Restores the factory and stops the REST server. */ - @AfterClass + @AfterAll public static void tearDownAfterClass() { - Whitebox.setInternalState(RestServer.class, FACTORY_FIELD, saveFactory); + ReflectionTestUtils.setField(RestServer.class, FACTORY_FIELD, saveFactory); realRest.stop(); } @@ -132,7 +137,7 @@ public class RestServerTest { /** * Initializes mocks. */ - @Before + @BeforeEach public void setUp() { server1 = mock(HttpServletServer.class); server2 = mock(HttpServletServer.class); @@ -147,12 +152,12 @@ public class RestServerTest { when(server1.getName()).thenReturn(SERVER1); when(server2.getName()).thenReturn(SERVER2); - Whitebox.setInternalState(RestServer.class, FACTORY_FIELD, factory); + ReflectionTestUtils.setField(RestServer.class, FACTORY_FIELD, factory); } @Test - public void testRestServer() { - rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class); + void testRestServer() { + rest = new RestServer(params, Filter2.class, Provider1.class, Provider2.class); rest.start(); verify(server1).start(); @@ -164,52 +169,26 @@ public class RestServerTest { } @Test - public void testRestServer_NoAaf() { - rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class); - verify(server1, never()).addFilterClass(any(), any()); - verify(server2, never()).addFilterClass(any(), any()); - } - - @Test - public void testRestServer_OnlyOneAaf() { - when(server2.isAaf()).thenReturn(true); - - rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class); - - verify(server1, never()).addFilterClass(any(), any()); - verify(server2).addFilterClass(null, Filter.class.getName()); - } - - @Test - public void testRestServer_BothAaf() { - when(server1.isAaf()).thenReturn(true); - when(server2.isAaf()).thenReturn(true); - - rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class); - - verify(server1).addFilterClass(null, Filter.class.getName()); - verify(server2).addFilterClass(null, Filter.class.getName()); - } + void testRestServerListList() { + rest = new RestServer(params, List.of(Filter2.class), List.of(Provider1.class, Provider2.class)); - @Test - public void testRestServer_BothAaf_NoFilter() { - when(server1.isAaf()).thenReturn(true); - when(server2.isAaf()).thenReturn(true); - - rest = new RestServer(params, null, Provider1.class, Provider2.class); + rest.start(); + verify(server1).start(); + verify(server2).start(); - verify(server1, never()).addFilterClass(any(), any()); - verify(server2, never()).addFilterClass(any(), any()); + rest.stop(); + verify(server1).stop(); + verify(server2).stop(); } @Test - public void testRestServer_MissingProviders() { - assertThatIllegalArgumentException().isThrownBy(() -> new RestServer(params, Filter.class)); + void testRestServer_MissingProviders() { + assertThatIllegalArgumentException().isThrownBy(() -> new RestServer(params, List.of(Filter2.class), null)); } @Test - public void testGetServerProperties_testGetProviderNames() { - rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class); + void testGetServerProperties_testGetProviderNames() { + rest = new RestServer(params, Provider1.class, Provider2.class); ArgumentCaptor<Properties> cap = ArgumentCaptor.forClass(Properties.class); verify(serverFactory).build(cap.capture()); @@ -227,14 +206,47 @@ public class RestServerTest { assertEquals(USER, props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX)); assertEquals(PASS, props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX)); assertEquals("true", props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX)); - assertEquals("true", props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX)); assertEquals(String.join(",", GsonMessageBodyHandler.class.getName(), YamlMessageBodyHandler.class.getName(), JsonExceptionMapper.class.getName(), YamlExceptionMapper.class.getName()), props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER)); + assertEquals("false", props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PROMETHEUS_SUFFIX)); } @Test - public void testInvalidJson() throws Exception { + void testExplicitPrometheusAddedToProperty() { + when(params.isPrometheus()).thenReturn(true); + rest = new RestServer(params, Filter2.class, Provider1.class, Provider2.class); + ArgumentCaptor<Properties> cap = ArgumentCaptor.forClass(Properties.class); + verify(serverFactory).build(cap.capture()); + + Properties props = cap.getValue(); + String svcpfx = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + PARAM_NAME; + + assertEquals("true", props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PROMETHEUS_SUFFIX)); + assertThat(props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_URIPATH_SUFFIX)).isBlank(); + assertThat(props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_CLASS_SUFFIX)).isBlank(); + } + + @Test + void testStandardServletAddedToProperty() { + when(params.getServletUriPath()).thenReturn("/metrics"); + when(params.getServletClass()).thenReturn(MetricsServlet.class.getName()); + rest = new RestServer(params, Filter2.class, Provider1.class, Provider2.class); + ArgumentCaptor<Properties> cap = ArgumentCaptor.forClass(Properties.class); + verify(serverFactory).build(cap.capture()); + + Properties props = cap.getValue(); + String svcpfx = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + PARAM_NAME; + + assertEquals("false", props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PROMETHEUS_SUFFIX)); + assertEquals(METRICS_URI, + props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_URIPATH_SUFFIX)); + assertEquals(MetricsServlet.class.getName(), + props.getProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERVLET_CLASS_SUFFIX)); + } + + @Test + void testInvalidJson() throws Exception { initRealParams(); assertEquals(200, roundTrip(new StandardCoder().encode(new MyRequest()))); @@ -243,7 +255,7 @@ public class RestServerTest { } @Test - public void testInvalidYaml() throws Exception { + void testInvalidYaml() throws Exception { initRealParams(); assertEquals(200, roundTrip(new StandardCoder().encode(new MyRequest()), @@ -284,13 +296,13 @@ public class RestServerTest { } @Test - public void testToString() { - rest = new RestServer(params, Filter.class, Provider1.class, Provider2.class); + void testToString() { + rest = new RestServer(params, Filter2.class, Provider1.class, Provider2.class); assertNotNull(rest.toString()); } @Test - public void testFactory() { + void testFactory() { assertNotNull(saveFactory); assertNotNull(saveFactory.getServerFactory()); } @@ -316,15 +328,10 @@ public class RestServerTest { when(params.isHttps()).thenReturn(true); } - private static class Filter extends AafAuthFilter { + private static class Filter2 implements jakarta.servlet.Filter { @Override - protected String getPermissionType(HttpServletRequest request) { - return ""; - } - - @Override - protected String getPermissionInstance(HttpServletRequest request) { - return ""; + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { + // do nothing } } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafAuthFilter.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafAuthFilter.java deleted file mode 100644 index 27d45c8d..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafAuthFilter.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. 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.policy.common.endpoints.http.server.test; - -import javax.servlet.http.HttpServletRequest; -import org.onap.policy.common.endpoints.http.server.aaf.AafAuthFilter; - -public class TestAafAuthFilter extends AafAuthFilter { - - @Override - protected String getRole(HttpServletRequest request) { - String expectedPerm = "test|test|" + request.getMethod().toLowerCase(); - if (!expectedPerm.equals(super.getRole(request))) { - throw new IllegalStateException("unexpected permission"); - } else { - return "user"; - } - } - - @Override - protected String getPermissionType(HttpServletRequest request) { - return "test"; - } - - @Override - protected String getPermissionInstance(HttpServletRequest request) { - return "test"; - } -}
\ No newline at end of file diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafGranularAuthFilter.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafGranularAuthFilter.java deleted file mode 100644 index 183e5ae7..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAafGranularAuthFilter.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. 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.policy.common.endpoints.http.server.test; - -import javax.servlet.http.HttpServletRequest; -import org.onap.policy.common.endpoints.http.server.aaf.AafGranularAuthFilter; -import org.onap.policy.common.utils.network.NetworkUtil; - -public class TestAafGranularAuthFilter extends AafGranularAuthFilter { - - @Override - protected String getRole(HttpServletRequest request) { - String expectedPerm = this.getPermissionTypeRoot() - + request.getRequestURI().replace('/', '.') + "|" - + NetworkUtil.getHostname() + "|" - + request.getMethod().toLowerCase(); - if (!expectedPerm.equals(super.getRole(request))) { - throw new IllegalStateException("unexpected AAF granular permission"); - } else { - return "user"; - } - } - - @Override - public String getPermissionTypeRoot() { - return "org.onap.policy"; - } -}
\ No newline at end of file diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAuthorizationFilter.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAuthorizationFilter.java index f3cd7424..59ec6f13 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAuthorizationFilter.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestAuthorizationFilter.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +21,7 @@ package org.onap.policy.common.endpoints.http.server.test; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.onap.policy.common.endpoints.http.server.AuthorizationFilter; public class TestAuthorizationFilter extends AuthorizationFilter { diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestFilter.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestFilter.java index 44b37656..155e12bb 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestFilter.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/TestFilter.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,12 +21,12 @@ package org.onap.policy.common.endpoints.http.server.test; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; public class TestFilter implements Filter { diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlExceptionMapperTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlExceptionMapperTest.java index 96c23ed3..b5dcb182 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlExceptionMapperTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlExceptionMapperTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023-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. @@ -20,26 +21,26 @@ package org.onap.policy.common.endpoints.http.server.test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import javax.ws.rs.core.Response; -import org.junit.Before; -import org.junit.Test; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.http.server.YamlExceptionMapper; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardYamlCoder; import org.yaml.snakeyaml.error.YAMLException; -public class YamlExceptionMapperTest { +class YamlExceptionMapperTest { private YamlExceptionMapper mapper; - @Before + @BeforeEach public void setUp() { mapper = new YamlExceptionMapper(); } @Test - public void testToResponse() throws CoderException { + void testToResponse() throws CoderException { YAMLException ex = new YAMLException("expected exception"); Response resp = mapper.toResponse(ex); diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlJacksonHandlerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlJacksonHandlerTest.java index 7ca131ec..01e9fdc5 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlJacksonHandlerTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlJacksonHandlerTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023-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. @@ -20,27 +21,29 @@ package org.onap.policy.common.endpoints.http.server.test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.gson.JsonObject; +import jakarta.ws.rs.core.MediaType; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; -import javax.ws.rs.core.MediaType; -import org.junit.Test; +import lombok.ToString; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.http.server.YamlJacksonHandler; import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler; import org.onap.policy.common.gson.annotation.GsonJsonAnyGetter; import org.onap.policy.common.gson.annotation.GsonJsonAnySetter; -public class YamlJacksonHandlerTest { +class YamlJacksonHandlerTest { @Test - public void test() throws Exception { + void test() throws Exception { YamlJacksonHandler hdlr = new YamlJacksonHandler(); assertTrue(hdlr.isReadable(null, null, null, MediaType.valueOf(YamlMessageBodyHandler.APPLICATION_YAML))); @@ -65,7 +68,7 @@ public class YamlJacksonHandlerTest { ByteArrayOutputStream outstr = new ByteArrayOutputStream(); hdlr.writeTo(data, Data.class, Data.class, null, null, null, outstr); - assertEquals("abc: def\nhello: world\nmyId: 100\nvalue: a value\n", outstr.toString("UTF-8")); + assertEquals("abc: def\nhello: world\nmyId: 100\nvalue: a value\n", outstr.toString(StandardCharsets.UTF_8)); /* * Ensure everything deserializes as expected. @@ -80,7 +83,7 @@ public class YamlJacksonHandlerTest { } @Test - public void testMapDouble() throws Exception { + void testMapDouble() throws Exception { MyMap map = new MyMap(); map.props = new HashMap<>(); map.props.put("plainString", "def"); @@ -106,6 +109,7 @@ public class YamlJacksonHandlerTest { /** * This class includes all policy-specific gson annotations. */ + @ToString public static class Data { protected int id; @@ -144,11 +148,6 @@ public class YamlJacksonHandlerTest { props.put(name, value); } - - @Override - public String toString() { - return "Data [id=" + id + ", value=" + value + ", props=" + props + "]"; - } } private static class MyMap { diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlMessageBodyHandlerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlMessageBodyHandlerTest.java index 4f2eb316..1c7f5245 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlMessageBodyHandlerTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/http/server/test/YamlMessageBodyHandlerTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2023-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. @@ -21,10 +22,11 @@ package org.onap.policy.common.endpoints.http.server.test; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import jakarta.ws.rs.core.MediaType; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -32,13 +34,13 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; -import javax.ws.rs.core.MediaType; -import org.junit.Before; -import org.junit.Test; +import lombok.ToString; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler; import org.yaml.snakeyaml.error.YAMLException; -public class YamlMessageBodyHandlerTest { +class YamlMessageBodyHandlerTest { private static final String EXPECTED_EXCEPTION = "expected exception"; private static final String GEN_TYPE = "some-type"; @@ -52,15 +54,15 @@ public class YamlMessageBodyHandlerTest { private YamlMessageBodyHandler hdlr; - @Before + @BeforeEach public void setUp() { hdlr = new YamlMessageBodyHandler(); } @Test - public void testIsWriteable() { + void testIsWriteable() { for (String subtype : subtypes) { - assertTrue("writeable " + subtype, hdlr.isWriteable(null, null, null, new MediaType(GEN_TYPE, subtype))); + assertTrue(hdlr.isWriteable(null, null, null, new MediaType(GEN_TYPE, subtype)), "writeable " + subtype); } @@ -77,12 +79,12 @@ public class YamlMessageBodyHandlerTest { } @Test - public void testGetSize() { + void testGetSize() { assertEquals(-1, hdlr.getSize(null, null, null, null, null)); } @Test - public void testWriteTo_testReadFrom() throws Exception { + void testWriteTo_testReadFrom() throws Exception { ByteArrayOutputStream outstr = new ByteArrayOutputStream(); MyObject obj1 = new MyObject(10); hdlr.writeTo(obj1, obj1.getClass(), CLASS_OBJ, null, null, null, outstr); @@ -93,7 +95,7 @@ public class YamlMessageBodyHandlerTest { } @Test - public void testWriteTo_DifferentTypes() throws Exception { + void testWriteTo_DifferentTypes() throws Exception { ByteArrayOutputStream outstr = new ByteArrayOutputStream(); // use a derived type, but specify the base type when writing @@ -106,7 +108,7 @@ public class YamlMessageBodyHandlerTest { } @Test - public void testWriteTo_Ex() throws Exception { + void testWriteTo_Ex() throws Exception { OutputStream outstr = new OutputStream() { @Override public void write(int value) throws IOException { @@ -122,9 +124,9 @@ public class YamlMessageBodyHandlerTest { } @Test - public void testIsReadable() { + void testIsReadable() { for (String subtype : subtypes) { - assertTrue("readable " + subtype, hdlr.isReadable(null, null, null, new MediaType(GEN_TYPE, subtype))); + assertTrue(hdlr.isReadable(null, null, null, new MediaType(GEN_TYPE, subtype)), "readable " + subtype); } @@ -141,7 +143,7 @@ public class YamlMessageBodyHandlerTest { } @Test - public void testReadFrom_DifferentTypes() throws Exception { + void testReadFrom_DifferentTypes() throws Exception { ByteArrayOutputStream outstr = new ByteArrayOutputStream(); MyObject obj1 = new MyObject(10); hdlr.writeTo(obj1, obj1.getClass(), CLASS_OBJ, null, null, null, outstr); @@ -159,7 +161,7 @@ public class YamlMessageBodyHandlerTest { } @Test - public void testReadFrom_Ex() throws Exception { + void testReadFrom_Ex() throws Exception { InputStream inpstr = new InputStream() { @Override public int read() throws IOException { @@ -174,7 +176,7 @@ public class YamlMessageBodyHandlerTest { } @Test - public void testReadFrom_Invalid() throws Exception { + void testReadFrom_Invalid() throws Exception { InputStream inpstr = new ByteArrayInputStream("plain text".getBytes()); assertThatThrownBy(() -> hdlr.readFrom(CLASS_OBJ, CLASS_OBJ, null, null, null, inpstr)) @@ -184,7 +186,7 @@ public class YamlMessageBodyHandlerTest { } @Test - public void testMapDouble() throws Exception { + void testMapDouble() throws Exception { MyMap map = new MyMap(); map.props = new HashMap<>(); map.props.put("plainString", "def"); @@ -212,6 +214,7 @@ public class YamlMessageBodyHandlerTest { } } + @ToString public static class MyObject { private int id; @@ -222,11 +225,6 @@ public class YamlMessageBodyHandlerTest { public MyObject(int id) { this.id = id; } - - @Override - public String toString() { - return "MyObject [id=" + id + "]"; - } } private static class MyMap { diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/JsonListenerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/JsonListenerTest.java index 54f49077..c2e5f90d 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/JsonListenerTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/JsonListenerTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Modifications 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. @@ -20,8 +21,8 @@ package org.onap.policy.common.endpoints.listeners; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; @@ -30,17 +31,17 @@ import static org.mockito.Mockito.verify; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.policy.common.message.bus.event.Topic.CommInfrastructure; import org.onap.policy.common.utils.coder.StandardCoderObject; import org.onap.policy.common.utils.test.log.logback.ExtractAppender; import org.slf4j.LoggerFactory; -public class JsonListenerTest { +class JsonListenerTest { /** * Used to attach an appender to the class' logger. @@ -62,7 +63,7 @@ public class JsonListenerTest { /** * Initializes statics. */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { saveLevel = logger.getLevel(); logger.setLevel(Level.INFO); @@ -71,7 +72,7 @@ public class JsonListenerTest { appender.start(); } - @AfterClass + @AfterAll public static void tearDownAfterClass() { logger.setLevel(saveLevel); appender.stop(); @@ -80,7 +81,7 @@ public class JsonListenerTest { /** * Initializes mocks and a listener. */ - @Before + @BeforeEach public void setUp() { appender.clearExtractions(); @@ -92,13 +93,13 @@ public class JsonListenerTest { }; } - @After + @AfterEach public void tearDown() { logger.detachAppender(appender); } @Test - public void testOnTopicEvent() { + void testOnTopicEvent() { logger.addAppender(appender); primary = spy(primary); diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcherTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcherTest.java index e4c84f3a..e0184bd1 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcherTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/MessageTypeDispatcherTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Modifications 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. @@ -20,8 +21,8 @@ package org.onap.policy.common.endpoints.listeners; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -31,17 +32,17 @@ import static org.mockito.Mockito.verify; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.policy.common.message.bus.event.Topic.CommInfrastructure; import org.onap.policy.common.utils.coder.StandardCoderObject; import org.onap.policy.common.utils.test.log.logback.ExtractAppender; import org.slf4j.LoggerFactory; -public class MessageTypeDispatcherTest { +class MessageTypeDispatcherTest { /** * Used to attach an appender to the class' logger. @@ -68,7 +69,7 @@ public class MessageTypeDispatcherTest { /** * Initializes statics. */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { saveLevel = logger.getLevel(); logger.setLevel(Level.INFO); @@ -77,7 +78,7 @@ public class MessageTypeDispatcherTest { appender.start(); } - @AfterClass + @AfterAll public static void tearDownAfterClass() { logger.setLevel(saveLevel); appender.stop(); @@ -86,7 +87,7 @@ public class MessageTypeDispatcherTest { /** * Initializes mocks and a listener. */ - @Before + @BeforeEach @SuppressWarnings("unchecked") public void setUp() { appender.clearExtractions(); @@ -97,13 +98,13 @@ public class MessageTypeDispatcherTest { primary = new MessageTypeDispatcher(TYPE_FIELD); } - @After + @AfterEach public void tearDown() { logger.detachAppender(appender); } @Test - public void testRegister_testUnregister() { + void testRegister_testUnregister() { primary.register(TYPE1, secondary1); primary.register(TYPE2, secondary2); @@ -136,7 +137,7 @@ public class MessageTypeDispatcherTest { } @Test - public void testOnTopicEvent() { + void testOnTopicEvent() { primary.register(TYPE1, secondary1); logger.addAppender(appender); diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcherTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcherTest.java index 94717e53..ac61ae7c 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcherTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/RequestIdDispatcherTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications 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. @@ -21,9 +22,8 @@ package org.onap.policy.common.endpoints.listeners; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.eq; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -32,12 +32,12 @@ import static org.mockito.Mockito.verify; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.policy.common.message.bus.event.Topic.CommInfrastructure; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; @@ -45,7 +45,7 @@ import org.onap.policy.common.utils.coder.StandardCoderObject; import org.onap.policy.common.utils.test.log.logback.ExtractAppender; import org.slf4j.LoggerFactory; -public class RequestIdDispatcherTest { +class RequestIdDispatcherTest { /** * Used to attach an appender to the class' logger. @@ -76,7 +76,7 @@ public class RequestIdDispatcherTest { /** * Initializes statics. */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { saveLevel = logger.getLevel(); logger.setLevel(Level.INFO); @@ -85,7 +85,7 @@ public class RequestIdDispatcherTest { appender.start(); } - @AfterClass + @AfterAll public static void tearDownAfterClass() { logger.setLevel(saveLevel); appender.stop(); @@ -95,7 +95,7 @@ public class RequestIdDispatcherTest { * Create various mocks and primary listener. */ @SuppressWarnings("unchecked") - @Before + @BeforeEach public void setUp() { appender.clearExtractions(); @@ -107,52 +107,52 @@ public class RequestIdDispatcherTest { primary = new RequestIdDispatcher<>(MyMessage.class, REQID_FIELD); } - @After + @AfterEach public void tearDown() { logger.detachAppender(appender); } @Test - public void testRegisterMessageListener() { + void testRegisterMessageListener() { primary.register(secondary1); // should process message that does not have a request id status = new MyMessage(); primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1).onTopicEvent(INFRA, TOPIC, status); // should process again primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1, times(2)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1, times(2)).onTopicEvent(INFRA, TOPIC, status); // should NOT process a message that has a request id status = new MyMessage(REQID1); primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1, never()).onTopicEvent(INFRA, TOPIC, status); } @Test - public void testRegisterStringMessageListener() { + void testRegisterStringMessageListener() { primary.register(REQID1, secondary1); // should NOT process message that does not have a request id status = new MyMessage(); primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1, never()).onTopicEvent(INFRA, TOPIC, status); // should process a message that has the desired request id status = new MyMessage(REQID1); primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1).onTopicEvent(INFRA, TOPIC, status); // should process again primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1, times(2)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1, times(2)).onTopicEvent(INFRA, TOPIC, status); // should NOT process a message that does NOT have the desired request id status = new MyMessage(REQID2); primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1, never()).onTopicEvent(INFRA, TOPIC, status); // null request id => exception assertThatIllegalArgumentException().isThrownBy(() -> primary.register(null, secondary1)); @@ -162,50 +162,50 @@ public class RequestIdDispatcherTest { } @Test - public void testUnregisterMessageListener() { + void testUnregisterMessageListener() { primary.register(secondary1); primary.register(secondary2); // should process message status = new MyMessage(); primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); - verify(secondary2).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1).onTopicEvent(INFRA, TOPIC, status); + verify(secondary2).onTopicEvent(INFRA, TOPIC, status); primary.unregister(secondary1); // should NOT process again primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1, times(1)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1, times(1)).onTopicEvent(INFRA, TOPIC, status); // other listener should still have processed it - verify(secondary2, times(2)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary2, times(2)).onTopicEvent(INFRA, TOPIC, status); } @Test - public void testUnregisterString() { + void testUnregisterString() { primary.register(REQID1, secondary1); primary.register(REQID2, secondary2); // should process a message that has the desired request id status = new MyMessage(REQID1); primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1).onTopicEvent(INFRA, TOPIC, status); primary.unregister(REQID1); // should NOT re-process primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1, times(1)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1, times(1)).onTopicEvent(INFRA, TOPIC, status); // secondary should still be able to process status = new MyMessage(REQID2); primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary2).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary2).onTopicEvent(INFRA, TOPIC, status); } @Test - public void testOnTopicEvent() { + void testOnTopicEvent() { primary.register(REQID1, secondary1); primary.register(REQID2, secondary2); primary.register(secondary3); @@ -214,22 +214,22 @@ public class RequestIdDispatcherTest { // without request id status = new MyMessage(); primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); - verify(secondary2, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); - verify(secondary3).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); - verify(secondary4).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1, never()).onTopicEvent(INFRA, TOPIC, status); + verify(secondary2, never()).onTopicEvent(INFRA, TOPIC, status); + verify(secondary3).onTopicEvent(INFRA, TOPIC, status); + verify(secondary4).onTopicEvent(INFRA, TOPIC, status); // with request id status = new MyMessage(REQID1); primary.onTopicEvent(INFRA, TOPIC, makeSco(status)); - verify(secondary1).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); - verify(secondary2, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); - verify(secondary3, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); - verify(secondary4, never()).onTopicEvent(eq(INFRA), eq(TOPIC), eq(status)); + verify(secondary1).onTopicEvent(INFRA, TOPIC, status); + verify(secondary2, never()).onTopicEvent(INFRA, TOPIC, status); + verify(secondary3, never()).onTopicEvent(INFRA, TOPIC, status); + verify(secondary4, never()).onTopicEvent(INFRA, TOPIC, status); } @Test - public void testOfferToListener() { + void testOfferToListener() { logger.addAppender(appender); // no listener for this diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/ScoListenerTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/ScoListenerTest.java index 8543b73e..cb8fb70d 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/ScoListenerTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/listeners/ScoListenerTest.java @@ -2,7 +2,8 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications 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. @@ -20,21 +21,20 @@ package org.onap.policy.common.endpoints.listeners; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.eq; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.policy.common.message.bus.event.Topic.CommInfrastructure; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; @@ -42,7 +42,7 @@ import org.onap.policy.common.utils.coder.StandardCoderObject; import org.onap.policy.common.utils.test.log.logback.ExtractAppender; import org.slf4j.LoggerFactory; -public class ScoListenerTest { +class ScoListenerTest { /** * Used to attach an appender to the class' logger. @@ -62,13 +62,11 @@ public class ScoListenerTest { private static final Coder coder = new StandardCoder(); private ScoListener<MyMessage> primary; - private MyMessage status; - private StandardCoderObject sco; /** * Initializes statics. */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { saveLevel = logger.getLevel(); logger.setLevel(Level.INFO); @@ -77,7 +75,7 @@ public class ScoListenerTest { appender.start(); } - @AfterClass + @AfterAll public static void tearDownAfterClass() { logger.setLevel(saveLevel); appender.stop(); @@ -86,7 +84,7 @@ public class ScoListenerTest { /** * Create various mocks and primary handler. */ - @Before + @BeforeEach public void setUp() { appender.clearExtractions(); @@ -99,38 +97,37 @@ public class ScoListenerTest { }; } - @After + @AfterEach public void tearDown() { logger.detachAppender(appender); } @Test - public void testOnTopicEvent() { + void testOnTopicEvent() { primary = spy(primary); - status = new MyMessage(NAME); - sco = makeSco(status); + MyMessage status = new MyMessage(NAME); + StandardCoderObject sco = makeSco(status); primary.onTopicEvent(INFRA, TOPIC, sco); - verify(primary).onTopicEvent(eq(INFRA), eq(TOPIC), eq(sco), eq(status)); + verify(primary).onTopicEvent(INFRA, TOPIC, sco, status); assertFalse(appender.getExtracted().toString().contains("unable to decode")); // undecodable message logger.addAppender(appender); - primary.onTopicEvent(INFRA, TOPIC, makeSco("[]")); - verify(primary, times(1)).onTopicEvent(eq(INFRA), eq(TOPIC), eq(sco), eq(status)); + primary.onTopicEvent(INFRA, TOPIC, makeSco()); + verify(primary, times(1)).onTopicEvent(INFRA, TOPIC, sco, status); assertTrue(appender.getExtracted().toString().contains("unable to decode")); } /** * Makes a standard object from a JSON string. * - * @param source message to be converted * @return a standard object representing the message */ - private StandardCoderObject makeSco(String source) { + private StandardCoderObject makeSco() { try { - return coder.decode(source, StandardCoderObject.class); + return coder.decode("[]", StandardCoderObject.class); } catch (CoderException e) { throw new RuntimeException(e); @@ -184,13 +181,10 @@ public class ScoListenerTest { } MyMessage other = (MyMessage) obj; if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; + return other.name == null; + } else { + return name.equals(other.name); } - return true; } } } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroupTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroupTest.java deleted file mode 100644 index 98b3d84a..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/TopicParameterGroupTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.endpoints.parameters; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.beans.PropertyDescriptor; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.List; -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; -import org.onap.policy.common.parameters.GroupValidationResult; -import org.onap.policy.common.utils.coder.Coder; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; - -/** - * Class to perform unit test of {@link TopicParameterGroup}. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class TopicParameterGroupTest { - private static CommonTestData testData = new CommonTestData(); - private static final Coder coder = new StandardCoder(); - - @Test - public void test() throws CoderException { - final TopicParameterGroup topicParameterGroup = - testData.toObject(testData.getTopicParameterGroupMap(false), TopicParameterGroup.class); - final GroupValidationResult validationResult = topicParameterGroup.validate(); - assertTrue(validationResult.isValid()); - assertEquals(CommonTestData.TOPIC_PARAMS, topicParameterGroup.getTopicSinks()); - assertEquals(CommonTestData.TOPIC_PARAMS, topicParameterGroup.getTopicSources()); - - // these should default to true - assertTrue(new TopicParameters().isManaged()); - assertTrue(coder.decode("{}", TopicParameters.class).isManaged()); - - // but can be overridden - assertFalse(coder.decode("{'managed':false}".replace('\'', '"'), TopicParameters.class).isManaged()); - } - - @Test - public void testValidate() { - final TopicParameterGroup topicParameterGroup = - testData.toObject(testData.getTopicParameterGroupMap(false), TopicParameterGroup.class); - final GroupValidationResult result = topicParameterGroup.validate(); - assertNull(result.getResult()); - assertTrue(result.isValid()); - } - - @Test - public void test_valid() throws Exception { - String json = testData.getParameterGroupAsString( - "src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_valid.json"); - TopicParameterGroup topicParameterGroup = coder.decode(json, TopicParameterGroup.class); - final GroupValidationResult result = topicParameterGroup.validate(); - assertNull(result.getResult()); - assertTrue(result.isValid()); - } - - @Test - public void test_invalid() throws Exception { - String json = testData.getParameterGroupAsString( - "src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_invalid.json"); - TopicParameterGroup topicParameterGroup = coder.decode(json, TopicParameterGroup.class); - final GroupValidationResult result = topicParameterGroup.validate(); - assertFalse(result.isValid()); - assertTrue(result.getResult().contains("INVALID")); - } - - @Test - public void test_missing_mandatory_params() throws Exception { - String json = testData.getParameterGroupAsString( - "src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_missing_mandatory.json"); - TopicParameterGroup topicParameterGroup = coder.decode(json, TopicParameterGroup.class); - final GroupValidationResult result = topicParameterGroup.validate(); - assertTrue(result.getResult().contains("Mandatory parameters are missing")); - assertFalse(result.isValid()); - } - - @Test - public void test_allparams() throws Exception { - String json = testData.getParameterGroupAsString( - "src/test/resources/org/onap/policy/common/endpoints/parameters/TopicParameters_all_params.json"); - TopicParameterGroup topicParameterGroup = coder.decode(json, TopicParameterGroup.class); - final GroupValidationResult result = topicParameterGroup.validate(); - assertNull(result.getResult()); - assertTrue(result.isValid()); - assertTrue(checkIfAllParamsNotEmpty(topicParameterGroup.getTopicSinks())); - assertTrue(checkIfAllParamsNotEmpty(topicParameterGroup.getTopicSources())); - } - - /** - * Method to check if all parameters in TopicParameters are set. - * Any parameters added to @link TopicParameters or @link BusTopicParams must be added to - * TopicParameters_all_params.json. - * - * @param topicParameters topic parameters - * @return true if all parameters are not empty (if string) or true (if boolean) - * @throws Exception the exception - */ - private boolean checkIfAllParamsNotEmpty(List<TopicParameters> topicParametersList) throws Exception { - for (TopicParameters topicParameters : topicParametersList) { - Field[] fields = BusTopicParams.class.getDeclaredFields(); - for (Field field : fields) { - if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers())) { - Object parameter = new PropertyDescriptor(field.getName(), TopicParameters.class).getReadMethod() - .invoke(topicParameters); - if ((parameter instanceof String && StringUtils.isBlank(parameter.toString())) - || (parameter instanceof Boolean && !(Boolean) parameter) - || (parameter instanceof Number && ((Number) parameter).longValue() == 0)) { - return false; - } - } - } - } - return true; - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/report/TestHealthCheckReport.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/report/TestHealthCheckReport.java deleted file mode 100644 index 36970d74..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/report/TestHealthCheckReport.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 AT&T Intellectual Property. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.common.endpoints.report; - -import com.openpojo.reflection.filters.FilterClassName; -import com.openpojo.validation.Validator; -import com.openpojo.validation.ValidatorBuilder; -import com.openpojo.validation.rule.impl.GetterMustExistRule; -import com.openpojo.validation.rule.impl.SetterMustExistRule; -import com.openpojo.validation.test.impl.GetterTester; -import com.openpojo.validation.test.impl.SetterTester; -import org.junit.Test; -import org.onap.policy.common.utils.test.ToStringTester; - -/** - * Class to perform unit test of HealthCheckReport. - * - * @author Ram Krishna Verma (ram.krishna.verma@ericsson.com) - */ -public class TestHealthCheckReport { - - @Test - public void testHealthCheckReport() { - final Validator validator = - ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule()) - .with(new GetterTester()).with(new SetterTester()).with(new ToStringTester()).build(); - validator.validate(HealthCheckReport.class.getPackage().getName(), - new FilterClassName(HealthCheckReport.class.getName())); - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/CommonTestData.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/rest/CommonTestData.java index e3f0878f..3e16b8a5 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/CommonTestData.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/rest/CommonTestData.java @@ -1,8 +1,7 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2024 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. 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. @@ -20,14 +19,12 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.common.endpoints.parameters; +package org.onap.policy.common.endpoints.rest; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.util.Arrays; -import java.util.List; import java.util.Map; import java.util.TreeMap; import org.onap.policy.common.parameters.ParameterGroup; @@ -49,33 +46,9 @@ public class CommonTestData { public static final boolean REST_SERVER_HTTPS = true; public static final boolean REST_SERVER_AAF = false; - public static final String TOPIC_NAME = "POLICY-PDP-PAP"; - public static final String TOPIC_INFRA = "dmaap"; - public static final String TOPIC_SERVER = "message-router"; - - public static final List<TopicParameters> TOPIC_PARAMS = - Arrays.asList(getTopicParameters(TOPIC_NAME, TOPIC_INFRA, TOPIC_SERVER)); - protected static final Coder coder = new StandardCoder(); /** - * Create topic parameters for test cases. - * - * @param topicName name of topic - * @param topicInfra topicCommInfrastructure - * @param topicServer topic server - * - * @return topic parameters - */ - public static TopicParameters getTopicParameters(String topicName, String topicInfra, String topicServer) { - final TopicParameters topicParams = new TopicParameters(); - topicParams.setTopic(topicName); - topicParams.setTopicCommInfrastructure(topicInfra); - topicParams.setServers(Arrays.asList(topicServer)); - return topicParams; - } - - /** * Converts the contents of a map to a parameter class. * * @param source property map @@ -113,22 +86,6 @@ public class CommonTestData { } /** - * Returns a property map for a TopicParameters map for test cases. - * - * @param isEmpty boolean value to represent that object created should be empty or not - * @return a property map suitable for constructing an object - */ - public Map<String, Object> getTopicParameterGroupMap(final boolean isEmpty) { - final Map<String, Object> map = new TreeMap<>(); - if (!isEmpty) { - map.put("topicSources", TOPIC_PARAMS); - map.put("topicSinks", TOPIC_PARAMS); - } - - return map; - } - - /** * Gets the standard parameter group as a String. * * @param filePath path of the file @@ -137,6 +94,6 @@ public class CommonTestData { */ public String getParameterGroupAsString(String filePath) throws IOException { File file = new File(filePath); - return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + return Files.readString(file.toPath()); } } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/RestServerParametersTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/rest/RestServerParametersTest.java index 58bf98b3..ccabc455 100644 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/parameters/RestServerParametersTest.java +++ b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/rest/RestServerParametersTest.java @@ -1,8 +1,7 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - + * Copyright (C) 2019-2024 Nordix Foundation. + * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. 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. @@ -20,15 +19,17 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.common.endpoints.parameters; +package org.onap.policy.common.endpoints.rest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +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 org.junit.Test; -import org.onap.policy.common.parameters.GroupValidationResult; +import org.junit.jupiter.api.Test; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.common.parameters.rest.RestServerParameters; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.StandardCoder; @@ -37,16 +38,16 @@ import org.onap.policy.common.utils.coder.StandardCoder; * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class RestServerParametersTest { +class RestServerParametersTest { - private static CommonTestData testData = new CommonTestData(); + private static final CommonTestData testData = new CommonTestData(); private static final Coder coder = new StandardCoder(); @Test - public void test() { + void test() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class); - final GroupValidationResult validationResult = restServerParameters.validate(); + final ValidationResult validationResult = restServerParameters.validate(); assertTrue(validationResult.isValid()); assertEquals(CommonTestData.REST_SERVER_HOST, restServerParameters.getHost()); assertEquals(CommonTestData.REST_SERVER_PORT, restServerParameters.getPort()); @@ -57,31 +58,31 @@ public class RestServerParametersTest { } @Test - public void testValidate() { + void testValidate() { final RestServerParameters restServerParameters = testData.toObject(testData.getRestServerParametersMap(false), RestServerParameters.class); - final GroupValidationResult result = restServerParameters.validate(); + final ValidationResult result = restServerParameters.validate(); assertNull(result.getResult()); assertTrue(result.isValid()); } @Test - public void test_valid() throws Exception { + void test_valid() throws Exception { String json = testData.getParameterGroupAsString( - "src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_valid.json"); + "src/test/resources/org/onap/policy/common/endpoints/rest/RestServerParameters_valid.json"); RestServerParameters restServerParameters = coder.decode(json, RestServerParameters.class); - final GroupValidationResult result = restServerParameters.validate(); + final ValidationResult result = restServerParameters.validate(); assertNull(result.getResult()); assertTrue(result.isValid()); } @Test - public void test_invalid() throws Exception { + void test_invalid() throws Exception { String json = testData.getParameterGroupAsString( - "src/test/resources/org/onap/policy/common/endpoints/parameters/RestServerParameters_invalid.json"); + "src/test/resources/org/onap/policy/common/endpoints/rest/RestServerParameters_invalid.json"); RestServerParameters restServerParameters = coder.decode(json, RestServerParameters.class); - final GroupValidationResult result = restServerParameters.validate(); + final ValidationResult result = restServerParameters.validate(); assertFalse(result.isValid()); - assertTrue(result.getResult().contains("parameter group has status INVALID")); + assertThat(result.getResult()).contains("item has status INVALID"); } } diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/NetLoggerUtilTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/NetLoggerUtilTest.java deleted file mode 100644 index 1e8c0316..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/NetLoggerUtilTest.java +++ /dev/null @@ -1,270 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. 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.policy.common.endpoints.utils; - -import static org.junit.Assert.assertEquals; - -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.AppenderBase; -import java.util.ArrayList; -import java.util.List; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.features.NetLoggerFeatureApi; -import org.onap.policy.common.endpoints.features.NetLoggerFeatureProviders; -import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType; -import org.slf4j.Logger; - -/** - * Test class for network log utilities such as logging and feature invocation. - */ -public class NetLoggerUtilTest { - - private static final String TEST_TOPIC = "test-topic"; - private static final String MESSAGE = "hello world!"; - /** - * Test feature used for junits. - */ - private static NetLoggerFeature netLoggerFeature; - - /** - * Obtains the test implementation of NetLoggerFeatureApi. - */ - @BeforeClass - public static void setUp() { - netLoggerFeature = (NetLoggerFeature) NetLoggerFeatureProviders.getProviders().getList().get(0); - } - - /** - * Clears events list and resets return/exceptions flags before invoking every unit test. - */ - @Before - public void reset() { - TestAppender.clear(); - netLoggerFeature.setReturnValue(false, false); - netLoggerFeature.setExceptions(false, false); - } - - /** - * Tests obtaining the network logger instance. - */ - @Test - public void getNetworkLoggerTest() { - assertEquals("network", NetLoggerUtil.getNetworkLogger().getName()); - } - - /** - * Tests logging a message to the network logger and invoking features before/after logging. - */ - @Test - public void logTest() { - NetLoggerUtil.log(EventType.IN, CommInfrastructure.NOOP, TEST_TOPIC, MESSAGE); - assertEquals(3, TestAppender.events.size()); - } - - /** - * Tests that the network logger is used to log messages if a logger is not passed in. - */ - @Test - public void logDefaultTest() { - NetLoggerUtil.log(null, EventType.IN, CommInfrastructure.NOOP, TEST_TOPIC, MESSAGE); - assertEquals(3, TestAppender.events.size()); - assertEquals("network", TestAppender.events.get(0).getLoggerName()); - } - - /** - * Tests a NetLoggerFeature that replaces base implementation before logging. - */ - @Test - public void beforeLogReturnTrueTest() { - netLoggerFeature.setReturnValue(true, false); - NetLoggerUtil.log(null, EventType.IN, CommInfrastructure.NOOP, TEST_TOPIC, MESSAGE); - assertEquals(1, TestAppender.events.size()); - } - - /** - * Tests a NetLoggerFeature that post processes a logged message. - */ - @Test - public void afterLogReturnTrueTest() { - netLoggerFeature.setReturnValue(false, true); - NetLoggerUtil.log(null, EventType.IN, CommInfrastructure.NOOP, TEST_TOPIC, MESSAGE); - assertEquals(3, TestAppender.events.size()); - } - - /** - * Tests throwing an exception in the before hook. - */ - @Test - public void beforeLogExceptionTest() { - netLoggerFeature.setExceptions(true, false); - NetLoggerUtil.log(null, EventType.IN, CommInfrastructure.NOOP, TEST_TOPIC, MESSAGE); - assertEquals(2, TestAppender.events.size()); - } - - /** - * Tests throwing an exception in the after hook. - */ - @Test - public void afterLogExceptionTest() { - netLoggerFeature.setExceptions(false, true); - NetLoggerUtil.log(null, EventType.IN, CommInfrastructure.NOOP, TEST_TOPIC, MESSAGE); - assertEquals(2, TestAppender.events.size()); - } - - /** - * A custom list appender to track messages being logged to the network logger. - * NOTE: Check src/test/resources/logback-test.xml for network logger configurations. - */ - public static class TestAppender extends AppenderBase<ILoggingEvent> { - - /** - * List of logged events. - */ - private static final List<ILoggingEvent> events = new ArrayList<>(); - - /** - * Called after every unit test to clear list of events. - */ - public static void clear() { - events.clear(); - } - - /** - * Appends each event to the event list. - */ - @Override - protected void append(ILoggingEvent event) { - events.add(event); - } - - } - - /** - * Test implementation of NetLoggerFeatureApi to be used by junits. - */ - public static class NetLoggerFeature implements NetLoggerFeatureApi { - - /** - * Used for setting the return values of before/after hooks. - */ - private boolean beforeReturn = false; - private boolean afterReturn = false; - - /** - * Used for throwing an exception in the before/after hooks. - */ - private boolean beforeException = false; - private boolean afterException = false; - - - /** - * Gets sequence number. - */ - @Override - public int getSequenceNumber() { - return 0; - } - - /** - * Get beforeLog return value. - */ - public boolean getBeforeReturn() { - return this.beforeReturn; - } - - /** - * Get afterLog return value. - */ - public boolean getAfterReturn() { - return this.afterReturn; - } - - /** - * Sets the return value for the before/after hooks. - * - * @param beforeVal beforeLog() return value - * @param afterVal afterLog() return value - */ - public void setReturnValue(boolean beforeVal, boolean afterVal) { - this.beforeReturn = beforeVal; - this.afterReturn = afterVal; - } - - /** - * Gets beforeException boolean. - */ - public boolean getBeforeException() { - return this.beforeException; - } - - /** - * Gets afterException boolean. - */ - public boolean getAfterException() { - return this.afterException; - } - - /** - * Sets before/after flags to determine if the feature should throw an exception. - */ - public void setExceptions(boolean beforeException, boolean afterException) { - this.beforeException = beforeException; - this.afterException = afterException; - } - - /** - * Simple beforeLog message. - */ - @Override - public boolean beforeLog(Logger eventLogger, EventType type, CommInfrastructure protocol, String topic, - String message) { - - if (beforeException) { - throw new RuntimeException("beforeLog exception"); - } - - eventLogger.info("before feature test"); - - return this.beforeReturn; - } - - /** - * Simple afterLog message. - */ - @Override - public boolean afterLog(Logger eventLogger, EventType type, CommInfrastructure protocol, String topic, - String message) { - - if (afterException) { - throw new RuntimeException("afterLog exception"); - } - - eventLogger.info("after feature test"); - - return this.afterReturn; - } - - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/PropertyUtilsTest.java b/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/PropertyUtilsTest.java deleted file mode 100644 index 048a3902..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/utils/PropertyUtilsTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. 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.policy.common.endpoints.utils; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Properties; -import org.junit.Before; -import org.junit.Test; - -public class PropertyUtilsTest { - private static final String DFLT_STRING = "my-default"; - private static final int DLFT_INT = 1000; - - private PropertyUtils utils; - private String invalidName; - private String invalidValue; - private Exception invalidEx; - - /** - * Initializes {@link #utils}. - */ - @Before - public void setUp() { - Properties properties = new Properties(); - properties.put("myPrefix.my-string", "some text"); - properties.put("myPrefix.empty-string", ""); - - properties.put("myPrefix.my-bool", "true"); - properties.put("myPrefix.my-bool2", "false"); - properties.put("myPrefix.empty-bool", ""); - properties.put("myPrefix.invalid-bool", "not a bool"); - - properties.put("myPrefix.my-int", "100"); - properties.put("myPrefix.my-int2", "200"); - properties.put("myPrefix.empty-int", ""); - properties.put("myPrefix.invalid-int", "not an int"); - - utils = new PropertyUtils(properties, "myPrefix", (name, value, ex) -> { - invalidName = name; - invalidValue = value; - invalidEx = ex; - }); - } - - @Test - public void testGetString() { - assertEquals("some text", utils.getString(".my-string", DFLT_STRING)); - assertEquals(DFLT_STRING, utils.getString(".empty-string", DFLT_STRING)); - assertEquals(DFLT_STRING, utils.getString(".missing-string", DFLT_STRING)); - - assertNull(invalidName); - assertNull(invalidValue); - assertNull(invalidEx); - } - - @Test - public void testGetBoolean() { - assertEquals(true, utils.getBoolean(".my-bool", false)); - assertEquals(false, utils.getBoolean(".my-bool2", true)); - assertEquals(true, utils.getBoolean(".empty-bool", true)); - assertEquals(false, utils.getBoolean(".invalid-bool", true)); - assertEquals(true, utils.getBoolean(".missing-bool", true)); - - assertNull(invalidName); - assertNull(invalidValue); - assertNull(invalidEx); - } - - @Test - public void testGetInteger() { - assertEquals(100, utils.getInteger(".my-int", DLFT_INT)); - assertEquals(200, utils.getInteger(".my-int2", DLFT_INT)); - assertEquals(DLFT_INT, utils.getInteger(".empty-int", DLFT_INT)); - assertEquals(DLFT_INT, utils.getInteger(".missing-int", DLFT_INT)); - - assertNull(invalidName); - assertNull(invalidValue); - assertNull(invalidEx); - - assertEquals(DLFT_INT, utils.getInteger(".invalid-int", DLFT_INT)); - - assertEquals("myPrefix.invalid-int", invalidName); - assertEquals("not an int", invalidValue); - assertTrue(invalidEx instanceof NumberFormatException); - } - -} |