aboutsummaryrefslogtreecommitdiffstats
path: root/models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider
diff options
context:
space:
mode:
Diffstat (limited to 'models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider')
-rw-r--r--models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/ConsumerGroupDataTest.java305
-rw-r--r--models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/DmaapSimProviderTest.java288
-rw-r--r--models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/TopicDataTest.java214
3 files changed, 0 insertions, 807 deletions
diff --git a/models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/ConsumerGroupDataTest.java b/models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/ConsumerGroupDataTest.java
deleted file mode 100644
index 4513ffb82..000000000
--- a/models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/ConsumerGroupDataTest.java
+++ /dev/null
@@ -1,305 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP Policy Models
- * ================================================================================
- * 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.models.sim.dmaap.provider;
-
-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.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-public class ConsumerGroupDataTest {
- private static final int WAIT_MS = 5000;
- private static final int MIN_WAIT_MS = WAIT_MS / 2;
- private static final String MY_TOPIC = "my-topic";
- private static final String MY_CONSUMER = "my-consumer";
- private static final String MSG1 = "hello";
- private static final String MSG2 = "there";
- private static final String MSG3 = "world";
- private static final int MAX_THREADS = 30;
-
- private MyData data;
- private MyReader thread;
- private List<MyReader> threads;
-
- /**
- * Sets up.
- */
- @Before
- public void setUp() {
- data = new MyData();
- thread = null;
- threads = new ArrayList<>(MAX_THREADS);
- }
-
- /**
- * Stops any running thread.
- */
- @After
- public void tearDown() {
- for (MyReader thr : threads) {
- thr.interrupt();
- }
-
- for (MyReader thr : threads) {
- thr.await();
- }
- }
-
- @Test
- public void testShouldRemove() throws InterruptedException {
- assertFalse(data.shouldRemove());
- assertTrue(data.shouldRemove());
-
- data = new MyData();
-
- // start a reader thread and wait for it to poll its queue
- startReader(0, 10);
- assertTrue(data.await());
-
- assertFalse(data.shouldRemove());
- }
-
- @Test
- public void testRead() {
- data.enqueue(MSG1, MSG2, MSG3, MSG1, MSG2, MSG3);
-
- // this reader only wants one
- startReader(1, 1);
- assertTrue(thread.await());
- assertEquals("[hello]", thread.result.toString());
-
- // this reader wants three
- startReader(3, 1);
- assertTrue(thread.await());
- assertEquals("[there, world, hello]", thread.result.toString());
-
- // this reader wants three, but will only get two
- startReader(3, 1);
- assertTrue(thread.await());
- assertEquals("[there, world]", thread.result.toString());
- }
-
- @Test
- public void testRead_Idle() throws InterruptedException {
- // force it to idle
- data.shouldRemove();
- data.shouldRemove();
-
- long tbeg = System.currentTimeMillis();
- assertSame(ConsumerGroupData.UNREADABLE_LIST, data.read(1, WAIT_MS));
-
- // should not have waited
- assertTrue(System.currentTimeMillis() < tbeg + MIN_WAIT_MS);
- }
-
- @Test
- public void testRead_NegativeCount() throws InterruptedException {
- data.enqueue(MSG1, MSG2);
- startReader(-1, 3);
- assertTrue(data.await());
-
- // wait time should be unaffected
- assertEquals(3L, data.waitMs2);
-
- assertTrue(thread.await());
-
- // should only return one message
- assertEquals("[hello]", thread.result.toString());
- }
-
- @Test
- public void testRead_NegativeWait() throws InterruptedException {
- data.enqueue(MSG1, MSG2, MSG3);
- startReader(2, -3);
- assertTrue(data.await());
-
- assertEquals(0L, data.waitMs2);
-
- assertTrue(thread.await());
-
- // should return two messages, as requested
- assertEquals("[hello, there]", thread.result.toString());
- }
-
- @Test
- public void testRead_NoMessages() throws InterruptedException {
- startReader(0, 0);
- assertTrue(data.await());
-
- assertTrue(thread.await());
- assertTrue(thread.result.isEmpty());
- }
-
- @Test
- public void testRead_MultiThreaded() {
- // queue up a bunch of messages
- final int expected = MAX_THREADS * 3;
- for (int x = 0; x < expected; ++x) {
- data.enqueue(MSG1);
- }
-
- for (int x = 0; x < MAX_THREADS; ++x) {
- startReader(4, 1);
- }
-
- int actual = 0;
- for (MyReader thr : threads) {
- thr.await();
- actual += thr.result.size();
- }
-
- assertEquals(expected, actual);
- }
-
-
- /**
- * Starts a reader thread.
- *
- * @param limit number of messages to read at one time
- * @param waitMs wait time, in milliseconds
- */
- private void startReader(int limit, long waitMs) {
- thread = new MyReader(limit, waitMs);
-
- thread.setDaemon(true);
- thread.start();
-
- threads.add(thread);
- }
-
-
- private class MyData extends ConsumerGroupData {
-
- /**
- * Decremented when {@link #getNextMessage(long)} is invoked.
- */
- private final CountDownLatch latch = new CountDownLatch(1);
-
- /**
- * Messages to be added to the queue when {@link #getNextMessage(long)} is
- * invoked.
- */
- private final List<String> messages = new ArrayList<>();
-
- /**
- * Value passed to {@link #getNextMessage(long)}.
- */
- private volatile long waitMs2 = -1;
-
- /**
- * Constructs the object.
- */
- public MyData() {
- super(MY_TOPIC, MY_CONSUMER);
- }
-
- /**
- * Arranges for messages to be injected into the queue the next time
- * {@link #getNextMessage(long)} is invoked.
- *
- * @param messages the messages to be injected
- */
- public void enqueue(String... messages) {
- this.messages.addAll(Arrays.asList(messages));
- }
-
- @Override
- protected String getNextMessage(long waitMs) throws InterruptedException {
- waitMs2 = waitMs;
-
- latch.countDown();
-
- synchronized (messages) {
- write(messages);
- messages.clear();
- }
-
- return super.getNextMessage(waitMs);
- }
-
- /**
- * Waits for {@link #getNextMessage(long)} to be invoked.
- *
- * @return {@code true} if {@link #getNextMessage(long)} was invoked,
- * {@code false} if the timer expired first
- * @throws InterruptedException if the current thread is interrupted while waiting
- */
- public boolean await() throws InterruptedException {
- return latch.await(WAIT_MS, TimeUnit.MILLISECONDS);
- }
- }
-
- /**
- * Thread that will invoke the consumer group's read() method one time.
- */
- private class MyReader extends Thread {
- private final ConsumerGroupData group = data;
- private final int limit;
- private final long waitMs;
-
- /**
- * Result returned by the read() method.
- */
- private List<String> result = Collections.emptyList();
-
- public MyReader(int limit, long waitMs) {
- this.limit = limit;
- this.waitMs = waitMs;
- }
-
- @Override
- public void run() {
- try {
- result = group.read(limit, waitMs);
-
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
-
- /**
- * Waits for the thread to complete.
- *
- * @return {@code true} if the thread completed, {@code false} if the thread is
- * still running
- */
- public boolean await() {
- try {
- this.join(WAIT_MS);
-
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
-
- return !this.isAlive();
- }
- }
-}
diff --git a/models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/DmaapSimProviderTest.java b/models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/DmaapSimProviderTest.java
deleted file mode 100644
index f82ef03f2..000000000
--- a/models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/DmaapSimProviderTest.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019-2021 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.
- * 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.models.sim.dmaap.provider;
-
-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.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import jakarta.ws.rs.core.Response;
-import jakarta.ws.rs.core.Response.Status;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
-import org.onap.policy.common.utils.coder.CoderException;
-import org.onap.policy.common.utils.coder.StandardCoder;
-import org.onap.policy.common.utils.coder.StandardCoderObject;
-import org.onap.policy.models.sim.dmaap.parameters.DmaapSimParameterGroup;
-
-@RunWith(MockitoJUnitRunner.class)
-public class DmaapSimProviderTest {
- private static final String EXPECTED_EXCEPTION = "expected exception";
- private static final long SWEEP_SEC = 10L;
- private static final String TOPIC1 = "topic-A";
- private static final String TOPIC2 = "topic-B";
- private static final String CONSUMER1 = "consumer-X";
- private static final String CONSUMER_ID1 = "id1";
-
- private MyProvider prov;
-
- @Mock
- private DmaapSimParameterGroup params;
-
- @Mock
- private ScheduledExecutorService timer;
-
- @Mock
- private TopicData data1;
-
- @Mock
- private TopicData data2;
-
- @Captor
- private ArgumentCaptor<List<Object>> listCaptor;
-
- @Captor
- private ArgumentCaptor<List<Object>> listCaptor2;
-
- /**
- * Sets up.
- */
- @Before
- public void setUp() {
- when(params.getTopicSweepSec()).thenReturn(SWEEP_SEC);
-
- prov = new MyProvider(params);
- }
-
- /**
- * Shuts down the provider, if it's running.
- */
- @After
- public void tearDown() {
- if (prov.isAlive()) {
- prov.shutdown();
- }
- }
-
- /**
- * Verifies that the constructor adds all the expected actions to the service
- * manager container.
- */
- @Test
- public void testDmaapSimProvider() {
- prov.start();
- verify(timer).scheduleWithFixedDelay(any(), eq(SWEEP_SEC), eq(SWEEP_SEC), eq(TimeUnit.SECONDS));
-
- prov.stop();
- verify(timer).shutdown();
- }
-
- @Test
- public void testProcessDmaapMessagePut_List() throws CoderException {
- prov = spy(new MyProvider(params));
-
- when(data1.write(any())).thenReturn(2);
-
- // force topics to exist
- prov.processDmaapMessageGet(TOPIC1, CONSUMER1, CONSUMER_ID1, 1, 0);
- prov.processDmaapMessageGet(TOPIC2, CONSUMER1, CONSUMER_ID1, 1, 0);
-
- List<Object> lst = Arrays.asList("hello", "world");
- Response resp = prov.processDmaapMessagePut(TOPIC1, lst);
- assertEquals(Status.OK.getStatusCode(), resp.getStatus());
- StandardCoderObject sco = new StandardCoder().decode(resp.getEntity().toString(), StandardCoderObject.class);
- assertEquals("2", sco.getString("count"));
-
- List<Object> lst2 = Arrays.asList("helloB", "worldB");
- prov.processDmaapMessagePut(TOPIC1, lst2);
- prov.processDmaapMessagePut(TOPIC2, lst2);
-
- // should only invoke this once for each topic
- verify(prov).makeTopicData(TOPIC1);
- verify(prov).makeTopicData(TOPIC2);
-
- // should process all writes
- verify(data1).write(lst);
- verify(data1).write(lst2);
-
- verify(data2).write(lst2);
- }
-
- @Test
- public void testProcessDmaapMessagePut_Single() throws CoderException {
- prov = spy(new MyProvider(params));
-
- // force topics to exist
- prov.processDmaapMessageGet(TOPIC1, CONSUMER1, CONSUMER_ID1, 1, 0);
- prov.processDmaapMessageGet(TOPIC2, CONSUMER1, CONSUMER_ID1, 1, 0);
-
- final String value1 = "abc";
- Response resp = prov.processDmaapMessagePut(TOPIC1, value1);
- assertEquals(Status.OK.getStatusCode(), resp.getStatus());
-
- // ensure that the response can be decoded
- new StandardCoder().decode(resp.getEntity().toString(), StandardCoderObject.class);
-
- final String value2 = "def";
- prov.processDmaapMessagePut(TOPIC1, value2);
- prov.processDmaapMessagePut(TOPIC2, value2);
-
- // should only invoke this once for each topic
- verify(prov).makeTopicData(TOPIC1);
- verify(prov).makeTopicData(TOPIC2);
-
- // should process all writes as singleton lists
- verify(data1, times(2)).write(listCaptor.capture());
- assertEquals(Collections.singletonList(value1), listCaptor.getAllValues().get(0));
- assertEquals(Collections.singletonList(value2), listCaptor.getAllValues().get(1));
-
- verify(data2).write(listCaptor2.capture());
- assertEquals(Collections.singletonList(value2), listCaptor2.getAllValues().get(0));
- }
-
- @Test
- public void testProcessDmaapMessageGet() throws InterruptedException {
- List<String> msgs = Arrays.asList("400", "500");
- when(data1.read(any(), anyInt(), anyLong())).thenReturn(msgs);
-
- Response resp = prov.processDmaapMessageGet(TOPIC1, CONSUMER1, CONSUMER_ID1, 4, 400L);
- assertEquals(Status.OK.getStatusCode(), resp.getStatus());
- assertEquals(msgs.toString(), resp.getEntity().toString());
- }
-
- @Test
- public void testProcessDmaapMessageGet_Timeout() throws InterruptedException {
- when(data1.read(any(), anyInt(), anyLong())).thenReturn(Collections.emptyList());
-
- Response resp = prov.processDmaapMessageGet(TOPIC1, CONSUMER1, CONSUMER_ID1, 3, 300L);
- assertEquals(Status.OK.getStatusCode(), resp.getStatus());
- assertEquals("[]", resp.getEntity().toString());
- }
-
- @Test
- public void testProcessDmaapMessageGet_Ex() throws InterruptedException {
- BlockingQueue<Response> respQueue = new LinkedBlockingQueue<>();
-
- // put in a background thread, so it doesn't interrupt the tester thread
- new Thread(() -> {
- try {
- when(data1.read(any(), anyInt(), anyLong())).thenThrow(new InterruptedException(EXPECTED_EXCEPTION));
- respQueue.offer(prov.processDmaapMessageGet(TOPIC1, CONSUMER1, CONSUMER_ID1, 3, 300L));
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }).start();
-
- Response resp = respQueue.poll(3, TimeUnit.SECONDS);
- assertNotNull(resp);
-
- assertEquals(Status.GONE.getStatusCode(), resp.getStatus());
- assertEquals("[]", resp.getEntity().toString());
- }
-
- @Test
- public void testSweepTopicTaskRun() {
- prov.start();
- prov.processDmaapMessageGet(TOPIC1, CONSUMER1, CONSUMER_ID1, 0, 0);
- prov.processDmaapMessageGet(TOPIC2, CONSUMER1, CONSUMER_ID1, 0, 0);
-
- ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
- verify(timer).scheduleWithFixedDelay(captor.capture(), anyLong(), anyLong(), any(TimeUnit.class));
-
- captor.getValue().run();
- verify(data1).removeIdleConsumers();
- verify(data2).removeIdleConsumers();
-
- // run it again
- captor.getValue().run();
- verify(data1, times(2)).removeIdleConsumers();
- verify(data2, times(2)).removeIdleConsumers();
- }
-
- @Test
- public void testMakeTimerPool() {
- // use a real provider, so we can test the real makeTimer() method
- DmaapSimProvider prov2 = new DmaapSimProvider(params);
- prov2.start();
- assertThatCode(prov2::stop).doesNotThrowAnyException();
- }
-
- @Test
- public void testMakeTopicData() {
- // use a real provider, so we can test the real makeTopicData() method
- DmaapSimProvider prov2 = new DmaapSimProvider(params);
- assertThatCode(() -> prov2.processDmaapMessageGet(TOPIC1, CONSUMER1, CONSUMER_ID1, 0, 0))
- .doesNotThrowAnyException();
- }
-
- @Test
- public void testGetInstance_testSetInstance() {
- DmaapSimProvider.setInstance(prov);
- assertSame(prov, DmaapSimProvider.getInstance());
-
- DmaapSimProvider.setInstance(null);
- assertNull(DmaapSimProvider.getInstance());
- }
-
-
- public class MyProvider extends DmaapSimProvider {
-
- public MyProvider(DmaapSimParameterGroup params) {
- super(params);
- }
-
- @Override
- protected ScheduledExecutorService makeTimerPool() {
- return timer;
- }
-
- @Override
- protected TopicData makeTopicData(String topicName) {
- return switch (topicName) {
- case TOPIC1 -> data1;
- case TOPIC2 -> data2;
- default -> throw new IllegalArgumentException("unknown topic name: " + topicName);
- };
- }
- }
-}
diff --git a/models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/TopicDataTest.java b/models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/TopicDataTest.java
deleted file mode 100644
index f37255acf..000000000
--- a/models-sim/models-sim-dmaap/src/test/java/org/onap/policy/models/sim/dmaap/provider/TopicDataTest.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP Policy Models
- * ================================================================================
- * Copyright (C) 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.
- * 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.models.sim.dmaap.provider;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-import java.util.TreeSet;
-import java.util.stream.Collectors;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.policy.common.utils.coder.Coder;
-import org.onap.policy.common.utils.coder.CoderException;
-import org.onap.policy.common.utils.coder.StandardCoder;
-import org.springframework.test.util.ReflectionTestUtils;
-
-public class TopicDataTest {
- private static final String EXPECTED_EXCEPTION = "expected exception";
- private static final String GROUP1 = "group-A";
- private static final String GROUP2 = "group-B";
- private static final String GROUP3 = "group-C";
-
- private TopicData data;
- private ConsumerGroupData consgrp1;
- private ConsumerGroupData consgrp2;
- private ConsumerGroupData consgrp3;
- private List<ConsumerGroupData> groups;
-
- /**
- * Sets up mocks and the initial data object.
- *
- * @throws Exception if an error occurs
- */
- @Before
- public void setUp() throws Exception {
- consgrp1 = mock(ConsumerGroupData.class);
- consgrp2 = mock(ConsumerGroupData.class);
- consgrp3 = mock(ConsumerGroupData.class);
-
- when(consgrp1.read(anyInt(), anyLong())).thenReturn(Collections.emptyList());
- when(consgrp2.read(anyInt(), anyLong())).thenReturn(Collections.emptyList());
- when(consgrp3.read(anyInt(), anyLong())).thenReturn(Collections.emptyList());
-
- groups = new LinkedList<>(Arrays.asList(consgrp1, consgrp2, consgrp3));
-
- data = new TopicData("my-topic") {
- @Override
- protected ConsumerGroupData makeData(String consumerGroup) {
- return groups.remove(0);
- }
- };
- }
-
- @Test
- public void testRemoveIdleConsumers() throws Exception {
- // force two consumers into the map
- data.read(GROUP1, 0, 0);
- data.read(GROUP2, 0, 0);
- data.read(GROUP3, 0, 0);
-
- // indicate that one should be removed
- when(consgrp1.shouldRemove()).thenReturn(true);
-
- // sweep
- data.removeIdleConsumers();
-
- assertEquals("[group-B, group-C]", new TreeSet<>(getGroups().keySet()).toString());
-
- // indicate that the others should be removed
- when(consgrp2.shouldRemove()).thenReturn(true);
- when(consgrp3.shouldRemove()).thenReturn(true);
-
- // sweep
- data.removeIdleConsumers();
-
- assertTrue(getGroups().isEmpty());
- }
-
- @Test
- public void testRead() throws Exception {
- List<String> lst = Collections.emptyList();
-
- when(consgrp1.read(anyInt(), anyLong())).thenReturn(ConsumerGroupData.UNREADABLE_LIST)
- .thenReturn(ConsumerGroupData.UNREADABLE_LIST).thenReturn(lst);
-
- assertSame(lst, data.read(GROUP1, 10, 20));
-
- // should have invoked three times
- verify(consgrp1, times(3)).read(anyInt(), anyLong());
-
- // should have used the given values
- verify(consgrp1, times(3)).read(10, 20);
-
- // should not have allocated more than one group
- assertEquals(2, groups.size());
- }
-
- @Test
- public void testRead_MultipleGroups() throws Exception {
- List<String> lst1 = Collections.emptyList();
- when(consgrp1.read(anyInt(), anyLong())).thenReturn(lst1);
-
- List<String> lst2 = Collections.emptyList();
- when(consgrp2.read(anyInt(), anyLong())).thenReturn(lst2);
-
- // one from each group
- assertSame(lst1, data.read(GROUP1, 0, 0));
- assertSame(lst2, data.read(GROUP2, 0, 0));
-
- // repeat
- assertSame(lst1, data.read(GROUP1, 0, 0));
- assertSame(lst2, data.read(GROUP2, 0, 0));
-
- // again
- assertSame(lst1, data.read(GROUP1, 0, 0));
- assertSame(lst2, data.read(GROUP2, 0, 0));
-
- // should still have group3 in the list
- assertEquals(1, groups.size());
- }
-
- @Test
- public void testWrite() throws Exception {
- // no groups yet
- List<Object> messages = Arrays.asList("hello", "world");
- data.write(messages);
-
- // add two groups
- data.read(GROUP1, 0, 0);
- data.read(GROUP2, 0, 0);
-
- data.write(messages);
-
- // should have been written to both groups
- List<String> strings = messages.stream().map(Object::toString).collect(Collectors.toList());
- verify(consgrp1).write(strings);
- verify(consgrp2).write(strings);
- }
-
- @Test
- public void testConvertMessagesToStrings() {
- assertEquals("[abc, 200]", data.convertMessagesToStrings(Arrays.asList("abc", null, 200)).toString());
- }
-
- @Test
- public void testConvertMessageToString() throws CoderException {
- Coder coder = new StandardCoder();
-
- assertNull(data.convertMessageToString(null, coder));
- assertEquals("text-msg", data.convertMessageToString("text-msg", coder));
- assertEquals("100", data.convertMessageToString(100, coder));
-
- coder = mock(Coder.class);
- when(coder.encode(any())).thenThrow(new CoderException(EXPECTED_EXCEPTION));
- assertNull(data.convertMessageToString(new TreeMap<String, Object>(), coder));
- }
-
- @Test
- public void testMakeData() throws Exception {
- // use real objects instead of mocks
- TopicData data2 = new TopicData("real-data-topic");
-
- // force a group into the topic
- data2.read(GROUP1, 0, 0);
-
- data2.write(Arrays.asList("abc", "def", "ghi"));
-
- assertEquals("[abc, def]", data2.read(GROUP1, 2, 0).toString());
- }
-
- /**
- * Gets the consumer group map from the topic data object.
- *
- * @return the topic's consumer group map
- */
- @SuppressWarnings("unchecked")
- private Map<String, ConsumerGroupData> getGroups() {
- return (Map<String, ConsumerGroupData>) ReflectionTestUtils.getField(data, "group2data");
- }
-}