diff options
author | PawelSzalapski <pawel.szalapski@nokia.com> | 2018-06-26 15:16:41 +0200 |
---|---|---|
committer | PawelSzalapski <pawel.szalapski@nokia.com> | 2018-07-02 09:52:44 +0200 |
commit | cd66181b35300f020f197bb411d6bdf6ad2514fb (patch) | |
tree | e4decd179d56ed2f64e5ab97c31c148cf2178aec /src/test | |
parent | 943a47187dbb1393d720b2fdf0019d48270edb4d (diff) |
Prepare codebase for dynamic DMaaP configuration
From now on, there is only one single place
where we can create whole app core concerning sending events
and it has a single entry point, based on DMaaP configuration.
It can be used to rebuild part of app that is responsible
for sending events dynamically.
Changes are in scope for the dynamic DMaaP config feature.
+ bumped up code coverage a bit
Change-Id: Iecc8c4e534ae9b781f47e3616409271ba83169c8
Signed-off-by: PawelSzalapski <pawel.szalapski@nokia.com>
Issue-ID: DCAEGEN2-517
Diffstat (limited to 'src/test')
14 files changed, 368 insertions, 419 deletions
diff --git a/src/test/java/org/onap/dcae/commonFunction/DmaapPublishersTest.java b/src/test/java/org/onap/dcae/commonFunction/DmaapPublishersTest.java deleted file mode 100644 index f4955ac8..00000000 --- a/src/test/java/org/onap/dcae/commonFunction/DmaapPublishersTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.ves - * ================================================================================ - * Copyright (C) 2018 Nokia. 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.dcae.commonFunction; - -import static org.hamcrest.CoreMatchers.allOf; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertSame; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import com.att.nsa.cambria.client.CambriaPublisher; -import com.google.common.collect.ImmutableList; -import com.google.common.util.concurrent.UncheckedExecutionException; -import java.io.IOException; -import java.net.MalformedURLException; -import java.security.GeneralSecurityException; -import java.util.concurrent.TimeUnit; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - - -@RunWith(MockitoJUnitRunner.class) -public class DmaapPublishersTest { - - @Mock - private CambriaPublisherFactory publisherFactory; - @Mock - private CambriaBatchingPublisher cambriaPublisher; - private DmaapPublishers cut; - - @Rule - public final ExpectedException expectedException = ExpectedException.none(); - - @Before - public void setUp() throws MalformedURLException, GeneralSecurityException { - given(publisherFactory.createCambriaPublisher(anyString())).willReturn(cambriaPublisher); - cut = DmaapPublishers.create(publisherFactory); - } - - @Test - public void getByStreamIdShouldUseCachedItem() throws IOException, GeneralSecurityException { - // given - String streamId = "sampleStream"; - - // when - CambriaBatchingPublisher firstPublisher = cut.getByStreamId(streamId); - CambriaBatchingPublisher secondPublisher = cut.getByStreamId(streamId); - - // then - verify(publisherFactory, times(1)).createCambriaPublisher(streamId); - assertSame("should return same instance", firstPublisher, secondPublisher); - } - - @Test - public void getByStreamIdShouldHandleErrors() throws MalformedURLException, GeneralSecurityException { - // given - MalformedURLException exception = new MalformedURLException(); - given(publisherFactory.createCambriaPublisher(anyString())).willThrow(exception); - expectedException.expect(allOf( - instanceOf(UncheckedExecutionException.class), - causeIsInstanceOf(exception.getClass()))); - - // when - cut.getByStreamId("a stream"); - - // then - // exception should have been thrown - } - - @Test - public void closeByStreamIdShouldCloseConnection() throws IOException, InterruptedException { - // given - String streamId = "sampleStream"; - given(cambriaPublisher.close(anyLong(), any(TimeUnit.class))) - .willReturn(ImmutableList.of(new CambriaPublisher.message("p", "msg"))); - - // when - CambriaBatchingPublisher cachedPublisher = cut.getByStreamId(streamId); - cut.closeByStreamId(streamId); - - // then - assertSame("should return proper publisher", cambriaPublisher, cachedPublisher); - verify(cambriaPublisher).close(20, TimeUnit.SECONDS); - } - - @Test - public void closeByStreamIdShouldHandleErrors() throws IOException, InterruptedException { - // given - String streamId = "sampleStream"; - given(cambriaPublisher.close(anyLong(), any(TimeUnit.class))).willThrow(IOException.class); - - // when - CambriaBatchingPublisher cachedPublisher = cut.getByStreamId(streamId); - cut.closeByStreamId(streamId); - - // then - assertSame("should return proper publisher", cambriaPublisher, cachedPublisher); - verify(cambriaPublisher).close(20, TimeUnit.SECONDS); - } - - private Matcher<Exception> causeIsInstanceOf(final Class<?> clazz) { - return new BaseMatcher<Exception>() { - @Override - public boolean matches(Object o) { - return o instanceof Throwable && clazz.isInstance(((Throwable) o).getCause()); - } - - @Override - public void describeTo(Description description) { - description.appendText("exception cause should be an instance of " + clazz.getName()); - } - }; - } -}
\ No newline at end of file diff --git a/src/test/java/org/onap/dcae/commonFunction/EventProcessorTest.java b/src/test/java/org/onap/dcae/commonFunction/EventProcessorTest.java index 973ee014..e211c12a 100644 --- a/src/test/java/org/onap/dcae/commonFunction/EventProcessorTest.java +++ b/src/test/java/org/onap/dcae/commonFunction/EventProcessorTest.java @@ -20,17 +20,17 @@ */ package org.onap.dcae.commonFunction; -import com.att.nsa.cambria.client.CambriaBatchingPublisher; import com.google.gson.Gson; +import java.util.concurrent.atomic.AtomicReference; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import java.util.List; +import org.onap.dcae.commonFunction.event.publishing.EventPublisher; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -52,7 +52,7 @@ public class EventProcessorTest { @Test public void testLoad() { //given - EventProcessor ec = new EventProcessor(); + EventProcessor ec = new EventProcessor(mock(EventPublisher.class)); ec.event = new org.json.JSONObject(ev); //when ec.overrideEvent(); @@ -65,7 +65,7 @@ public class EventProcessorTest { @Test public void shouldParseJsonEvents() throws ReflectiveOperationException { //given - EventProcessor eventProcessor = new EventProcessor(); + EventProcessor eventProcessor = new EventProcessor(mock(EventPublisher.class)); String event_json = "[{ \"filter\": {\"event.commonEventHeader.domain\":\"heartbeat\",\"VESversion\":\"v4\"},\"processors\":[" + "{\"functionName\": \"concatenateValue\",\"args\":{\"field\":\"event.commonEventHeader.eventName\",\"concatenate\": [\"$event.commonEventHeader.domain\",\"$event.commonEventHeader.eventType\",\"$event.faultFields.alarmCondition\"], \"delimiter\":\"_\"}}" + ",{\"functionName\": \"addAttribute\",\"args\":{\"field\": \"event.heartbeatFields.heartbeatFieldsVersion\",\"value\": \"1.0\",\"fieldType\": \"number\"}}" + @@ -84,32 +84,5 @@ public class EventProcessorTest { assertThat(stringArgumentCaptor.getAllValues()).contains("concatenateValue", "addAttribute", "map"); } - @Test - public void shouldCreateDmaapPublisher() { - - //given - EventPublisherHash eph = EventPublisherHash.getInstance(); - EventProcessor ec = new EventProcessor(); - ec.event = new org.json.JSONObject(ev); - CommonStartup.cambriaConfigFile = "src/test/resources/testDmaapConfig_ip.json"; - - //when - CambriaBatchingPublisher pub = eph.getDmaapPublisher("sec_fault_ueb"); - - //then - assertNotNull(pub); - } - - @Test - public void shouldSendEventWithNoError() { - - EventPublisherHash eph = EventPublisherHash.getInstance(); - EventProcessor eventProcessor = new EventProcessor(); - eventProcessor.event = new org.json.JSONObject(ev); - CommonStartup.cambriaConfigFile = "src/test/resources/testDmaapConfig_ip.json"; - - //when - eph.sendEvent(eventProcessor.event, "sec_fault_ueb"); - } } diff --git a/src/test/java/org/onap/dcae/commonFunction/TestCommonStartup.java b/src/test/java/org/onap/dcae/commonFunction/TestCommonStartup.java index e0fd5a42..12428024 100644 --- a/src/test/java/org/onap/dcae/commonFunction/TestCommonStartup.java +++ b/src/test/java/org/onap/dcae/commonFunction/TestCommonStartup.java @@ -22,6 +22,7 @@ package org.onap.dcae.commonFunction; import static java.util.Base64.getDecoder; import static java.util.Base64.getEncoder; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.att.nsa.cmdLine.NsaCommandLineUtil; @@ -43,6 +44,7 @@ import org.json.JSONObject; import org.junit.Test; import org.mockito.Mockito; import org.onap.dcae.commonFunction.CommonStartup.QueueFullException; +import org.onap.dcae.commonFunction.event.publishing.EventPublisher; import org.onap.dcae.restapi.RestfulCollectorServlet; @@ -79,7 +81,7 @@ public class TestCommonStartup { public void testParseStreamIdToStreamHashMapping() { // given CommonStartup.streamID = "fault=sec_fault|syslog=sec_syslog|heartbeat=sec_heartbeat|measurementsForVfScaling=sec_measurement|mobileFlow=sec_mobileflow|other=sec_other|stateChange=sec_statechange|thresholdCrossingAlert=sec_thresholdCrossingAlert|voiceQuality=ves_voicequality|sipSignaling=ves_sipsignaling"; - EventProcessor eventProcessor = new EventProcessor(); + EventProcessor eventProcessor = new EventProcessor(mock(EventPublisher.class)); // when Map<String, String[]> streamHashMapping = EventProcessor.streamidHash; diff --git a/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPConfigurationParserTest.java b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPConfigurationParserTest.java new file mode 100644 index 00000000..5a94c662 --- /dev/null +++ b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPConfigurationParserTest.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.collectors.ves + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018 Nokia. 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.dcae.commonFunction.event.publishing; + +import static io.vavr.API.List; +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.dcae.commonFunction.event.publishing.DMaaPConfigurationParser.parseToDomainMapping; + +import io.vavr.collection.Map; +import io.vavr.control.Try; +import java.nio.file.Path; +import java.nio.file.Paths; +import org.junit.Test; + +/** + * @author Pawel Szalapski (pawel.szalapski@nokia.com) + */ +public class DMaaPConfigurationParserTest { + + @Test + public void testParseCredentialsForGen2() { + Path path = Paths.get("src/test/resources/testParseDMaaPCredentialsGen2.json"); + Try<Map<String, PublisherConfig>> publisherConfigs = parseToDomainMapping(path); + + PublisherConfig authCredentialsNulls = publisherConfigs.get().get("auth-credentials-null").getOrNull(); + assertThat(authCredentialsNulls.userName().isEmpty()).isTrue(); + assertThat(authCredentialsNulls.password().isEmpty()).isTrue(); + assertThat(authCredentialsNulls.isSecured()).isFalse(); + + PublisherConfig authCredentialsPresent = publisherConfigs.get().get("auth-credentials-present").getOrNull(); + assertThat(authCredentialsPresent.userName().getOrNull()).isEqualTo("sampleUser"); + assertThat(authCredentialsPresent.password().getOrNull()).isEqualTo("samplePassword"); + assertThat(authCredentialsPresent.isSecured()).isTrue(); + + PublisherConfig authCredentialsKeysMissing = publisherConfigs.get().get("auth-credentials-missing").getOrNull(); + assertThat(authCredentialsKeysMissing.userName().isEmpty()).isTrue(); + assertThat(authCredentialsKeysMissing.password().isEmpty()).isTrue(); + assertThat(authCredentialsKeysMissing.isSecured()).isFalse(); + } + + + @Test + public void testParseCredentialsForLegacy() { + Path path = Paths.get("src/test/resources/testParseDMaaPCredentialsLegacy.json"); + Try<Map<String, PublisherConfig>> publisherConfigs = parseToDomainMapping(path); + + PublisherConfig authCredentialsNull = publisherConfigs.get().get("auth-credentials-null").getOrNull(); + assertThat(authCredentialsNull.userName().isEmpty()).isTrue(); + assertThat(authCredentialsNull.password().isEmpty()).isTrue(); + assertThat(authCredentialsNull.isSecured()).isFalse(); + + PublisherConfig authCredentialsPresent = publisherConfigs.get().get("auth-credentials-present").getOrNull(); + assertThat(authCredentialsPresent.userName().getOrNull()).isEqualTo("sampleUser"); + assertThat(authCredentialsPresent.password().getOrNull()).isEqualTo("samplePassword"); + assertThat(authCredentialsPresent.isSecured()).isTrue(); + + PublisherConfig authCredentialsMissing = publisherConfigs.get().get("auth-credentials-missing").getOrNull(); + assertThat(authCredentialsMissing.userName().isEmpty()).isTrue(); + assertThat(authCredentialsMissing.password().isEmpty()).isTrue(); + assertThat(authCredentialsMissing.isSecured()).isFalse(); + } + + + @Test + public void testParseGen2() { + Path path = Paths.get("src/test/resources/testParseDMaaPGen2.json"); + Try<Map<String, PublisherConfig>> publisherConfigs = parseToDomainMapping(path); + + PublisherConfig withEventsSegment = publisherConfigs.get().get("event-segments-with-port").getOrNull(); + assertThat(withEventsSegment.destinations()).isEqualTo(List("UEBHOST:3904")); + assertThat(withEventsSegment.topic()).isEqualTo("DCAE-SE-COLLECTOR-EVENTS-DEV"); + + PublisherConfig withOtherSegment = publisherConfigs.get().get("other-segments-without-ports").getOrNull(); + assertThat(withOtherSegment.destinations()).isEqualTo(List("UEBHOST")); + assertThat(withOtherSegment.topic()).isEqualTo("DCAE-SE-COLLECTOR-EVENTS-DEV"); + } + + @Test + public void testParseLegacy() { + Path exemplaryConfig = Paths.get("src/test/resources/testParseDMaaPLegacy.json"); + Try<Map<String, PublisherConfig>> publisherConfigs = DMaaPConfigurationParser + .parseToDomainMapping(exemplaryConfig); + + PublisherConfig urlFirstThenHosts = publisherConfigs.get().get("url-precedes-hosts").getOrNull(); + assertThat(urlFirstThenHosts.destinations()).isEqualTo(List("127.0.0.1:3904")); + assertThat(urlFirstThenHosts.topic()).isEqualTo("DCAE-SE-COLLECTOR-EVENTS-DEV"); + + PublisherConfig urlKeyMissing = publisherConfigs.get().get("url-key-missing").getOrNull(); + assertThat(urlKeyMissing.destinations()).isEqualTo(List("h1.att.com", "h2.att.com")); + assertThat(urlKeyMissing.topic()).isEqualTo("DCAE-SE-COLLECTOR-EVENTS-DEV"); + + PublisherConfig urlIsMissing = publisherConfigs.get().get("url-is-null").getOrNull(); + assertThat(urlIsMissing.destinations()).isEqualTo(List("h1.att.com", "h2.att.com")); + assertThat(urlIsMissing.topic()).isEqualTo("DCAE-SE-COLLECTOR-EVENTS-DEV"); + } +}
\ No newline at end of file diff --git a/src/test/java/org/onap/dcae/commonFunction/EventPublisherHashTest.java b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPEventPublisherTest.java index 81c6556b..bbe5079e 100644 --- a/src/test/java/org/onap/dcae/commonFunction/EventPublisherHashTest.java +++ b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPEventPublisherTest.java @@ -17,74 +17,73 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.dcae.commonFunction; +package org.onap.dcae.commonFunction.event.publishing; +import static io.vavr.API.Option; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; +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 org.json.JSONObject; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.Logger; -@RunWith(MockitoJUnitRunner.class) -public class EventPublisherHashTest { - private EventPublisherHash cut; +public class DMaaPEventPublisherTest { - @Mock - private DmaapPublishers dmaapPublishers; - @Mock + private static final String STREAM_ID = "sampleStreamId"; + + private DMaaPEventPublisher eventPublisher; private CambriaBatchingPublisher cambriaPublisher; + private DMaaPPublishersCache DMaaPPublishersCache; @Before public void setUp() { - given(dmaapPublishers.getByStreamId(anyString())).willReturn(cambriaPublisher); - - cut = new EventPublisherHash(dmaapPublishers); + cambriaPublisher = mock(CambriaBatchingPublisher.class); + DMaaPPublishersCache = mock(DMaaPPublishersCache.class); + when(DMaaPPublishersCache.getPublisher(anyString())).thenReturn(Option(cambriaPublisher)); + eventPublisher = new DMaaPEventPublisher(DMaaPPublishersCache, mock(Logger.class)); } @Test - public void sendEventShouldSendEventToATopic() throws Exception { + public void shouldSendEventToTopic() throws Exception { // given JSONObject event = new JSONObject("{}"); - final String streamId = "sampleStreamId"; // when - cut.sendEvent(event, streamId); + eventPublisher.sendEvent(event, STREAM_ID); // then verify(cambriaPublisher).send("MyPartitionKey", event.toString()); } @Test - public void sendEventShouldRemoveUuid() throws Exception { + public void shouldRemoveInternalVESUIDBeforeSending() throws Exception { // given - JSONObject event = new JSONObject("{\"VESuniqueId\": \"362e0146-ec5f-45f3-8d8f-bfe877c3f58e\", \"another\": 8}"); - final String streamId = "sampleStreamId"; + JSONObject event = new JSONObject( + "{\"VESuniqueId\": \"362e0146-ec5f-45f3-8d8f-bfe877c3f58e\", \"another\": 8}"); // when - cut.sendEvent(event, streamId); + eventPublisher.sendEvent(event, STREAM_ID); // then verify(cambriaPublisher).send("MyPartitionKey", new JSONObject("{\"another\": 8}").toString()); } @Test - public void sendEventShouldCloseConnectionWhenExceptionOccurred() throws Exception { + public void shouldCloseConnectionWhenExceptionOccurred() throws Exception { // given JSONObject event = new JSONObject("{}"); - final String streamId = "sampleStreamId"; given(cambriaPublisher.send(anyString(), anyString())).willThrow(new IOException("epic fail")); // when - cut.sendEvent(event, streamId); + eventPublisher.sendEvent(event, STREAM_ID); // then - verify(dmaapPublishers).closeByStreamId(streamId); + verify(DMaaPPublishersCache).closePublisherFor(STREAM_ID); } }
\ No newline at end of file diff --git a/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPPublishersCacheTest.java b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPPublishersCacheTest.java new file mode 100644 index 00000000..8dc69f62 --- /dev/null +++ b/src/test/java/org/onap/dcae/commonFunction/event/publishing/DMaaPPublishersCacheTest.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.collectors.ves + * ================================================================================ + * Copyright (C) 2018 Nokia. 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.dcae.commonFunction.event.publishing; + +import static io.vavr.API.List; +import static io.vavr.API.Map; +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 static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import io.vavr.collection.Map; +import io.vavr.control.Option; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Test; +import org.onap.dcae.commonFunction.event.publishing.DMaaPPublishersCache.CambriaPublishersCacheLoader; +import org.onap.dcae.commonFunction.event.publishing.DMaaPPublishersCache.OnPublisherRemovalListener; + + +public class DMaaPPublishersCacheTest { + + private String streamId1; + private Map<String, PublisherConfig> dMaaPConfigs; + + @Before + public void setUp() { + streamId1 = "sampleStream1"; + dMaaPConfigs = Map("sampleStream1", new PublisherConfig(List("destination1"), "topic1")); + } + + @Test + public void shouldReturnTheSameCachedInstanceOnConsecutiveRetrievals() { + // given + DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(dMaaPConfigs); + + // when + Option<CambriaBatchingPublisher> firstPublisher = dMaaPPublishersCache.getPublisher(streamId1); + Option<CambriaBatchingPublisher> secondPublisher = dMaaPPublishersCache.getPublisher(streamId1); + + // then + assertSame("should return same instance", firstPublisher.get(), secondPublisher.get()); + } + + @Test + public void shouldCloseCambriaPublisherOnCacheInvalidate() throws IOException, InterruptedException { + // given + CambriaBatchingPublisher cambriaPublisherMock1 = mock(CambriaBatchingPublisher.class); + CambriaPublishersCacheLoader cacheLoaderMock = mock(CambriaPublishersCacheLoader.class); + DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(cacheLoaderMock, + new OnPublisherRemovalListener(), + dMaaPConfigs); + when(cacheLoaderMock.load(streamId1)).thenReturn(cambriaPublisherMock1); + + // when + dMaaPPublishersCache.getPublisher(streamId1); + dMaaPPublishersCache.closePublisherFor(streamId1); + + // then + verify(cambriaPublisherMock1).close(20, TimeUnit.SECONDS); + + } + + @Test + public void shouldReturnNoneIfThereIsNoDMaaPConfigurationForGivenStreamID() { + // given + DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(dMaaPConfigs); + + // then + assertTrue("should not exist", dMaaPPublishersCache.getPublisher("non-existing").isEmpty()); + } + + + @Test + public void shouldCloseOnlyChangedPublishers() throws IOException, InterruptedException { + // given + CambriaBatchingPublisher cambriaPublisherMock1 = mock(CambriaBatchingPublisher.class); + CambriaBatchingPublisher cambriaPublisherMock2 = mock(CambriaBatchingPublisher.class); + CambriaPublishersCacheLoader cacheLoaderMock = mock(CambriaPublishersCacheLoader.class); + String firstDomain = "domain1"; + String secondDomain = "domain2"; + Map<String, PublisherConfig> oldConfig = Map(firstDomain, + new PublisherConfig(List("destination1"), "topic1"), + secondDomain, + new PublisherConfig(List("destination2"), "topic2", + "user", "pass")); + Map<String, PublisherConfig> newConfig = Map(firstDomain, new PublisherConfig(List("destination1"), "topic1"), + secondDomain, new PublisherConfig(List("destination2"), "topic2")); + DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(cacheLoaderMock, + new OnPublisherRemovalListener(), + oldConfig); + when(cacheLoaderMock.load(firstDomain)).thenReturn(cambriaPublisherMock1); + when(cacheLoaderMock.load(secondDomain)).thenReturn(cambriaPublisherMock2); + + dMaaPPublishersCache.getPublisher(firstDomain); + dMaaPPublishersCache.getPublisher(secondDomain); + + // when + dMaaPPublishersCache.reconfigure(newConfig); + + // then + verify(cambriaPublisherMock2).close(20, TimeUnit.SECONDS); + verifyZeroInteractions(cambriaPublisherMock1); + } +}
\ No newline at end of file diff --git a/src/test/java/org/onap/dcae/vestest/AnyNodeTest.java b/src/test/java/org/onap/dcae/vestest/AnyNodeTest.java index 695f53c9..9400e46d 100644 --- a/src/test/java/org/onap/dcae/vestest/AnyNodeTest.java +++ b/src/test/java/org/onap/dcae/vestest/AnyNodeTest.java @@ -19,89 +19,45 @@ */ package org.onap.dcae.vestest; -import com.google.common.collect.ImmutableMap; +import static org.assertj.core.api.Assertions.assertThat; + import com.google.common.collect.Sets; -import org.json.JSONObject; +import java.util.Set; import org.junit.BeforeClass; import org.junit.Test; import org.onap.dcae.commonFunction.AnyNode; -import java.io.IOException; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; - /** * Created by koblosz on 07.06.18. */ public class AnyNodeTest { - private static final String SAMPLE_JSON_FILEPATH = "src/test/resources/test_anynode_class.json"; - private static final Map<String, Object> EXPECTED_RAW_MAP = ImmutableMap.<String, Object>builder().put("a", 1).put("b", 2).build(); - private static final Set<String> EXPECTED_JSON_KEYS = Sets.newHashSet("channels", "sampleStrList", "sampleNestedObject", "sampleInt", "sampleString", "sampleNull"); + private static final String SAMPLE_JSON_FILEPATH = "{\n" + + " \"channels\": [{\n" + + " \"one\": \"number1\", \"two\": \"number2\", \"three\": \"number3\"}],\n" + + " \"sampleStrList\": [\"1\", \"2\", \"3\", \"4\", \"5\"],\n" + + " \"sampleNestedObject\": {\"a\": 1, \"b\": 2},\n" + + " \"sampleInt\": 1,\n" + + " \"sampleString\": \"str\",\n" + + " \"sampleNull\": null\n" + + "}\n"; + private static final Set<String> EXPECTED_JSON_KEYS = Sets + .newHashSet("channels", "sampleStrList", "sampleNestedObject", "sampleInt", "sampleString", "sampleNull"); private static AnyNode node; @BeforeClass - public static void setUpClass() throws IOException { - node = AnyNode.parse(SAMPLE_JSON_FILEPATH); - } - - @Test(expected = IOException.class) - public void testShouldRethrowExceptionWhenFileNotFound() throws IOException { - AnyNode.parse("not/existing/path"); + public static void setUpClass() { + node = AnyNode.fromString(SAMPLE_JSON_FILEPATH); } @Test public void testShouldReturnJsonObjectKeySet() { - assertThat(node.getKeys()).containsOnlyElementsOf(EXPECTED_JSON_KEYS); - } - - @Test - public void testShouldGetElementAsString() { - assertThat(node.get("sampleStrList").get(0).asString()).isEqualTo("1"); - } - - @Test - public void testShouldGetElementAsInt() { - assertThat(node.get("sampleInt").asInt()).isSameAs(1); - } - - @Test - public void testWhenNullValuePresentShouldReturnJsonObjectNullAsString() { - assertThat(node.get("sampleNull").asString()).isSameAs(JSONObject.NULL.toString()); + assertThat(node.keys()).containsOnlyElementsOf(EXPECTED_JSON_KEYS); } - @Test - public void testShouldGetJsonObjectAsStringToObjectMap() { - assertThat(node.get("sampleNestedObject").asRawMap()).containsAllEntriesOf(EXPECTED_RAW_MAP); - } - - @Test - public void testShouldGetAsMap() { - assertThat(node.asMap().keySet()).containsOnlyElementsOf(EXPECTED_JSON_KEYS); - } - - @Test - public void testShouldGetAsList() { - assertThat(node.get("sampleStrList").asList().stream().map(AnyNode::asString).collect(Collectors.toList())).containsExactly("1", "2", "3", "4", "5"); - } - - @Test - public void testShouldGetAsOptional() { - assertThat(node.getAsOptional("absentKey")).isNotPresent(); - } - - @Test - public void testWhenChainMethodsShouldReturnValue() { - assertThat(node.get("channels").get(0).get("two").asString()).isEqualTo("number2"); - } - - @Test(expected = ClassCastException.class) public void whenInvokedOnJsonObjInsteadOfJsonArrShouldRaiseRuntimeEx() { - node.asList(); + node.toList(); } }
\ No newline at end of file diff --git a/src/test/java/org/onap/dcae/vestest/DmaapPropertyReaderTest.java b/src/test/java/org/onap/dcae/vestest/DmaapPropertyReaderTest.java deleted file mode 100644 index 46f5da4b..00000000 --- a/src/test/java/org/onap/dcae/vestest/DmaapPropertyReaderTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * org.onap.dcaegen2.collectors.ves
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * Copyright (C) 2018 Nokia. 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.dcae.vestest;
-
-import com.google.common.collect.ImmutableMap;
-import org.junit.Test;
-import org.onap.dcae.commonFunction.DmaapPropertyReader;
-
-import java.util.Map;
-
-import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
-
-public class DmaapPropertyReaderTest {
-
-
- private static final String legacyConfigFilePath = "src/test/resources/testDmaapConfig_ip.json";
- private static final String dmaapInputConfigFilePath = "src/test/resources/testDmaapConfig_gen2.json";
- private static final String fullDmaapConfigWithChannels = "src/test/resources/testFullDmaapConfig_channels.json";
- private static final String fullGen2DmaapConfig = "src/test/resources/testFullDmaapConfig_gen2.json";
-
- private static final String FAULT_UEB_KEY_PREFIX = "sec_fault_ueb";
- private static final String VES_ALERT_SND_KEY_PREFIX = "ves-thresholdCrossingAlert-secondary";
- private static final String VES_FAULT_SECONDARY = "ves-fault-secondary";
-
- private static final String FAULT_BASIC_AUTH_USERNAME_KEY = VES_FAULT_SECONDARY + ".basicAuthUsername";
- private static final String ALERT_BASIC_AUTH_PWD_KEY = VES_ALERT_SND_KEY_PREFIX + ".basicAuthPassword";
-
- private static final String VES_ALERT_CAMBRIA_TOPIC_KEY = VES_ALERT_SND_KEY_PREFIX + ".cambria.topic";
- private static final String VES_ALERT_CAMBRIA_URL_KEY = VES_ALERT_SND_KEY_PREFIX + ".cambria.url";
- private static final String VES_FAULT_SND_CAMBRIA_URL_KEY = VES_FAULT_SECONDARY + ".cambria.url";
- private static final String VES_FAULT_SND_AUTH_PWD_KEY = VES_FAULT_SECONDARY + ".basicAuthPassword";
- private static final String VES_FAULT_SND_CAMBRIA_TOPIC_KEY = VES_FAULT_SECONDARY + ".cambria.topic";
- private static final String FAULT_UEB_CAMBRIA_HOSTS_KEY = FAULT_UEB_KEY_PREFIX + ".cambria.hosts";
- private static final String FAULT_UEB_CAMBRIA_TOPIC_KEY = FAULT_UEB_KEY_PREFIX + ".cambria.topic";
- private static final String VES_ALERT_SND_AUTH_USERNAME_KEY = VES_ALERT_SND_KEY_PREFIX + ".basicAuthUsername";
-
- private static final String NULL_TOSTRING = "null";
-
- private static final Map<String, String> expectedCompleteGen2DmaapConfig = ImmutableMap.<String, String>builder()
- .put(ALERT_BASIC_AUTH_PWD_KEY, "SamplePassWD2")
- .put(VES_ALERT_CAMBRIA_TOPIC_KEY, "DCAE-SE-COLLECTOR-EVENTS-DEV")
- .put(FAULT_BASIC_AUTH_USERNAME_KEY, "sampleUsername")
- .put(VES_ALERT_CAMBRIA_URL_KEY, "UEBHOST:3904")
- .put(VES_FAULT_SND_CAMBRIA_URL_KEY, "UEBHOST:3904")
- .put(VES_FAULT_SND_AUTH_PWD_KEY, "SamplePasswd")
- .put(VES_FAULT_SND_CAMBRIA_TOPIC_KEY, "DCAE-SE-COLLECTOR-EVENTS-DEV")
- .put(VES_ALERT_SND_AUTH_USERNAME_KEY, "sampleUsername2")
- .build();
-
- private static final Map<String, String> expectedIncompleteGen2DmaapConfig = ImmutableMap.<String, String>builder()
- .put(VES_ALERT_SND_AUTH_USERNAME_KEY, NULL_TOSTRING)
- .put(FAULT_BASIC_AUTH_USERNAME_KEY, NULL_TOSTRING)
- .put(VES_ALERT_CAMBRIA_TOPIC_KEY, "DCAE-SE-COLLECTOR-EVENTS-DEV")
- .put(VES_ALERT_CAMBRIA_URL_KEY, "UEBHOST:3904")
- .put(VES_FAULT_SND_CAMBRIA_URL_KEY, "UEBHOST:3904")
- .put(ALERT_BASIC_AUTH_PWD_KEY, NULL_TOSTRING)
- .put(VES_FAULT_SND_AUTH_PWD_KEY, NULL_TOSTRING)
- .put(VES_FAULT_SND_CAMBRIA_TOPIC_KEY, "DCAE-SE-COLLECTOR-EVENTS-DEV")
- .build();
-
- private static final Map<String, String> expectedCompleteChannelsDmaapConfig = ImmutableMap.<String, String>builder()
- .put(FAULT_UEB_CAMBRIA_HOSTS_KEY, "uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com")
- .put(FAULT_UEB_CAMBRIA_TOPIC_KEY, "DCAE-SE-COLLECTOR-EVENTS-DEV")
- .put(FAULT_UEB_KEY_PREFIX + ".basicAuthPassword", "S0mEPassWD")
- .put(FAULT_UEB_KEY_PREFIX + ".basicAuthUsername", "sampleUser")
- .put(FAULT_UEB_KEY_PREFIX + ".cambria.url", "127.0.0.1:3904")
- .build();
-
- private static final Map<String, String> expectedIncompleteChannelsDmaapConfig = ImmutableMap.<String, String>builder()
- .put(FAULT_UEB_CAMBRIA_HOSTS_KEY, "uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com")
- .put(FAULT_UEB_CAMBRIA_TOPIC_KEY, "DCAE-SE-COLLECTOR-EVENTS-DEV")
- .build();
-
- @Test
- public void testShouldCreateReaderWithAbsentParamsOmittedBasedOnChannelDmaapConfig() {
- assertReaderPreservedAllEntriesAfterTransformation(legacyConfigFilePath, expectedIncompleteChannelsDmaapConfig);
- }
-
- @Test
- public void testShouldCreateReaderWithAbsentParamsOmittedBasedOnGen2DmaapConfig() {
- assertReaderPreservedAllEntriesAfterTransformation(dmaapInputConfigFilePath, expectedIncompleteGen2DmaapConfig);
- }
-
- @Test
- public void shouldCreateReaderWithCompleteChannelDmaapConfig() {
- assertReaderPreservedAllEntriesAfterTransformation(fullDmaapConfigWithChannels, expectedCompleteChannelsDmaapConfig);
- }
-
- @Test
- public void shouldCreateReaderWithCompleteGen2DmaapConfig() {
- assertReaderPreservedAllEntriesAfterTransformation(fullGen2DmaapConfig, expectedCompleteGen2DmaapConfig);
- }
-
- private void assertReaderPreservedAllEntriesAfterTransformation(String dmaapConfigFilePath, Map<String, String> expectedMap) {
- DmaapPropertyReader reader = new DmaapPropertyReader(dmaapConfigFilePath);
-
- assertThat(reader.getDmaapProperties()).containsAllEntriesOf(expectedMap);
- assertThat(expectedMap).containsAllEntriesOf(reader.getDmaapProperties());
- }
-
-}
-
diff --git a/src/test/resources/testDmaapConfig_gen2.json b/src/test/resources/testDmaapConfig_gen2.json deleted file mode 100644 index d8097bf1..00000000 --- a/src/test/resources/testDmaapConfig_gen2.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "ves-fault-secondary": { - "aaf_username": null, - "dmaap_info": { - "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV", - "location": "mtl5", - "client_id": null, - "client_role": null - }, - "type": "message_router", - "aaf_password": null - }, - "ves-thresholdCrossingAlert-secondary": { - "aaf_username": null, - "dmaap_info": { - "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV", - "location": "mtl5", - "client_id": null, - "client_role": null - }, - "type": "message_router", - "aaf_password": null - } - }
\ No newline at end of file diff --git a/src/test/resources/testFullDmaapConfig_channels.json b/src/test/resources/testFullDmaapConfig_channels.json deleted file mode 100644 index e2bc0339..00000000 --- a/src/test/resources/testFullDmaapConfig_channels.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "channels": [ - { - "name": "sec_fault_ueb", - "cambria.url": "127.0.0.1:3904", - "cambria.hosts": "uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com", - "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV", - "basicAuthPassword": "S0mEPassWD", - "basicAuthUsername": "sampleUser", - "stripHpId": "true" - } - ] -}
\ No newline at end of file diff --git a/src/test/resources/testParseDMaaPCredentialsGen2.json b/src/test/resources/testParseDMaaPCredentialsGen2.json new file mode 100644 index 00000000..953cb6e8 --- /dev/null +++ b/src/test/resources/testParseDMaaPCredentialsGen2.json @@ -0,0 +1,21 @@ +{ + "auth-credentials-null": { + "aaf_username": null, + "dmaap_info": { + "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV", + }, + "aaf_password": null + }, + "auth-credentials-present": { + "aaf_username": "sampleUser", + "dmaap_info": { + "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV", + }, + "aaf_password": "samplePassword" + }, + "auth-credentials-missing": { + "dmaap_info": { + "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV", + } + } +}
\ No newline at end of file diff --git a/src/test/resources/testParseDMaaPCredentialsLegacy.json b/src/test/resources/testParseDMaaPCredentialsLegacy.json new file mode 100644 index 00000000..ca59c7e7 --- /dev/null +++ b/src/test/resources/testParseDMaaPCredentialsLegacy.json @@ -0,0 +1,26 @@ +{ + "channels": [ + { + "name": "auth-credentials-null", + "cambria.url": "127.0.0.1:3904", + "cambria.hosts": "uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com", + "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV", + "basicAuthPassword": null, + "basicAuthUsername": null, + }, + { + "name": "auth-credentials-present", + "cambria.url": "127.0.0.1:3904", + "cambria.hosts": "uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com", + "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV", + "basicAuthPassword": "samplePassword", + "basicAuthUsername": "sampleUser", + }, + { + "name": "auth-credentials-missing", + "cambria.url": "127.0.0.1:3904", + "cambria.hosts": "uebsb91kcdc.it.att.com,uebsb92kcdc.it.att.com,uebsb93kcdc.it.att.com", + "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV", + } + ] +}
\ No newline at end of file diff --git a/src/test/resources/testParseDMaaPGen2.json b/src/test/resources/testParseDMaaPGen2.json new file mode 100644 index 00000000..5b4fe6a6 --- /dev/null +++ b/src/test/resources/testParseDMaaPGen2.json @@ -0,0 +1,12 @@ +{ + "event-segments-with-port": { + "dmaap_info": { + "topic_url": "http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV", + } + }, + "other-segments-without-ports": { + "dmaap_info": { + "topic_url": "http://UEBHOST:3904/somethingHere/DCAE-SE-COLLECTOR-EVENTS-DEV", + } + } +}
\ No newline at end of file diff --git a/src/test/resources/testParseDMaaPLegacy.json b/src/test/resources/testParseDMaaPLegacy.json new file mode 100644 index 00000000..9661e30c --- /dev/null +++ b/src/test/resources/testParseDMaaPLegacy.json @@ -0,0 +1,21 @@ +{ + "channels": [ + { + "name": "url-precedes-hosts", + "cambria.url": "127.0.0.1:3904", + "cambria.hosts": "h1.att.com,h2.att.com", + "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV", + }, + { + "name": "url-key-missing", + "cambria.hosts": "h1.att.com,h2.att.com", + "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV", + }, + { + "name": "url-is-null", + "cambria.url": null, + "cambria.hosts": "h1.att.com,h2.att.com", + "cambria.topic": "DCAE-SE-COLLECTOR-EVENTS-DEV" + } + ] +}
\ No newline at end of file |