You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by tm...@apache.org on 2019/05/09 10:22:10 UTC

[sling-org-apache-sling-distribution-journal-kafka] branch master updated: SLING-8409 - Improve Test coverage for journal kafka (#4)

This is an automated email from the ASF dual-hosted git repository.

tmaret pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-distribution-journal-kafka.git


The following commit(s) were added to refs/heads/master by this push:
     new 96c091f  SLING-8409 - Improve Test coverage for journal kafka (#4)
96c091f is described below

commit 96c091f6150c074adea2a848a1e1f7e892644df3
Author: Christian Schneider <cs...@adobe.com>
AuthorDate: Thu May 9 12:22:06 2019 +0200

    SLING-8409 - Improve Test coverage for journal kafka (#4)
---
 .../journal/kafka/KafkaClientProvider.java         |  51 +++++----
 .../journal/kafka/KafkaClientProviderTest.java     | 122 +++++++++++++++++++++
 .../journal/kafka/KafkaMessageInfoTest.java        |  56 ++++++++++
 .../journal/kafka/KafkaMessageSenderTest.java      |  69 ++++++++++++
 4 files changed, 277 insertions(+), 21 deletions(-)

diff --git a/src/main/java/org/apache/sling/distribution/journal/kafka/KafkaClientProvider.java b/src/main/java/org/apache/sling/distribution/journal/kafka/KafkaClientProvider.java
index 9216d45..b4b78b9 100644
--- a/src/main/java/org/apache/sling/distribution/journal/kafka/KafkaClientProvider.java
+++ b/src/main/java/org/apache/sling/distribution/journal/kafka/KafkaClientProvider.java
@@ -38,6 +38,7 @@ import java.io.Closeable;
 import java.io.IOException;
 import java.util.Collection;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 
@@ -46,9 +47,11 @@ import javax.annotation.Nullable;
 
 import org.apache.kafka.clients.consumer.KafkaConsumer;
 import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.common.PartitionInfo;
 import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.serialization.ByteArrayDeserializer;
 import org.apache.kafka.common.serialization.ByteArraySerializer;
+import org.apache.kafka.common.serialization.Deserializer;
 import org.apache.kafka.common.serialization.StringDeserializer;
 import org.apache.kafka.common.serialization.StringSerializer;
 import org.apache.sling.distribution.journal.HandlerAdapter;
@@ -111,8 +114,7 @@ public class KafkaClientProvider implements MessagingProvider, Closeable {
 
     @Override
     public Closeable createPoller(String topicName, Reset reset, @Nullable String assign, HandlerAdapter<?>... adapters) {
-        String consumerGroupId = UUID.randomUUID().toString();
-        KafkaConsumer<String, byte[]> consumer = new KafkaConsumer<>(consumerConfig(ByteArrayDeserializer.class, consumerGroupId, reset));
+        KafkaConsumer<String, byte[]> consumer = createConsumer(ByteArrayDeserializer.class, reset);
         TopicPartition topicPartition = new TopicPartition(topicName, PARTITION);
         Collection<TopicPartition> topicPartitions = singleton(topicPartition);
         consumer.assign(topicPartitions);
@@ -124,7 +126,7 @@ public class KafkaClientProvider implements MessagingProvider, Closeable {
             consumer.seekToEnd(topicPartitions);
         }
         Closeable poller = new KafkaMessagePoller(consumer, adapters);
-        LOG.info(format("Created poller for consumerGroupId %s, reset %s, topicName %s, assign %s", consumerGroupId, reset, topicName, assign));
+        LOG.info("Created poller for reset {}, topicName {}, assign {}", reset, topicName, assign);
         return poller;
     }
 
@@ -135,8 +137,7 @@ public class KafkaClientProvider implements MessagingProvider, Closeable {
 
     @Override
     public <T> Closeable createJsonPoller(String topicName, Reset reset, MessageHandler<T> handler, Class<T> type) {
-        String consumerGroupId = UUID.randomUUID().toString();
-        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(consumerConfig(StringDeserializer.class, consumerGroupId, reset));
+        KafkaConsumer<String, String> consumer = createConsumer(StringDeserializer.class, reset);
         TopicPartition topicPartition = new TopicPartition(topicName, PARTITION);
         Collection<TopicPartition> topicPartitions = singleton(topicPartition);
         consumer.assign(topicPartitions);
@@ -150,30 +151,33 @@ public class KafkaClientProvider implements MessagingProvider, Closeable {
 
     @Override
     public void assertTopic(String topic) throws MessagingException {
-        String consumerGroupId = UUID.randomUUID().toString();
-        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(consumerConfig(StringDeserializer.class, consumerGroupId, Reset.latest))) {
-            if (! consumer.listTopics().containsKey(topic)) {
-                throw new MessagingException(format("Topic %s does not exist", topic));
-            }
+        Map<String, List<PartitionInfo>> topics;
+        try (KafkaConsumer<String, String> consumer = createConsumer(StringDeserializer.class, Reset.latest)) {
+            topics = consumer.listTopics();
         } catch (Exception e) {
             throw new MessagingException(format("Unable to load topic stats for %s", topic), e);
         }
+        if (! topics.containsKey(topic)) {
+            throw new MessagingException(format("Topic %s does not exist", topic));
+        }
     }
 
     @Override
     public long retrieveOffset(String topicName, Reset reset) {
-        String groupId = UUID.randomUUID().toString();
-        KafkaConsumer<String, byte[]> consumer = new KafkaConsumer<>(consumerConfig(ByteArrayDeserializer.class, groupId, reset));
-        TopicPartition topicPartition = new TopicPartition(topicName, PARTITION);
-        Collection<TopicPartition> topicPartitions = singleton(topicPartition);
-        final Map<TopicPartition, Long> offsets;
-        if (reset == Reset.earliest) {
-            offsets = consumer.beginningOffsets(topicPartitions);
-        } else {
-            offsets = consumer.endOffsets(topicPartitions);
+        try (KafkaConsumer<String, String> consumer = createConsumer(StringDeserializer.class, reset)) {;
+            TopicPartition topicPartition = new TopicPartition(topicName, PARTITION);
+            Map<TopicPartition, Long> offsets = getOffsets(reset, consumer, topicPartition);
+            Long offset = offsets.get(topicPartition);
+            return offset;
         }
-        consumer.close();
-        return offsets.get(topicPartition);
+    }
+
+    private Map<TopicPartition, Long> getOffsets(Reset reset, KafkaConsumer<String, String> consumer,
+            TopicPartition topicPartition) {
+        Collection<TopicPartition> topicPartitions = singleton(topicPartition);
+        return (reset == Reset.earliest) //
+                ? consumer.beginningOffsets(topicPartitions)
+                : consumer.endOffsets(topicPartitions);
     }
 
     @Override
@@ -181,6 +185,11 @@ public class KafkaClientProvider implements MessagingProvider, Closeable {
         return format("%s:%s", PARTITION, offset);
     }
 
+    protected <T> KafkaConsumer<String, T> createConsumer(Class<? extends Deserializer<?>> deserializer, Reset reset) {
+        String groupId = UUID.randomUUID().toString();
+        return new KafkaConsumer<>(consumerConfig(deserializer, groupId, reset));
+    }
+
     private void closeQuietly(final Closeable closeable) {
         try {
             if (closeable != null) {
diff --git a/src/test/java/org/apache/sling/distribution/journal/kafka/KafkaClientProviderTest.java b/src/test/java/org/apache/sling/distribution/journal/kafka/KafkaClientProviderTest.java
new file mode 100644
index 0000000..29448f8
--- /dev/null
+++ b/src/test/java/org/apache/sling/distribution/journal/kafka/KafkaClientProviderTest.java
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+package org.apache.sling.distribution.journal.kafka;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.when;
+import static org.osgi.util.converter.Converters.standardConverter;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.PartitionInfo;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.sling.distribution.journal.MessagingException;
+import org.apache.sling.distribution.journal.Reset;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.Spy;
+import org.mockito.runners.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class KafkaClientProviderTest {
+    private static final String TOPIC = "topic";
+    
+    @Spy
+    private KafkaClientProvider provider;
+    
+    @Mock
+    private KafkaConsumer<String, Object> consumer;
+    
+    @Before
+    public void before() {
+        doReturn(consumer).when(provider).createConsumer(Mockito.any(), Mockito.any());
+        KafkaEndpoint config = createConfig();
+        provider.activate(config);
+    }
+
+    @Test
+    public void testAssertTopicWhenDoesNotExist() throws Exception {
+        when(consumer.listTopics()).thenReturn(Collections.emptyMap());
+        try {
+            provider.assertTopic(TOPIC);
+            Assert.fail();
+        } catch (MessagingException e) {
+            assertThat(e.getMessage(), equalTo("Topic topic does not exist"));
+        }
+    }
+
+    @Test
+    public void testAssertTopicWhenError() throws Exception {
+        when(consumer.listTopics()).thenThrow(new RuntimeException("Expected"));
+        try {
+            provider.assertTopic(TOPIC);
+            Assert.fail();
+        } catch (MessagingException e) {
+            assertThat(e.getMessage(), equalTo("Unable to load topic stats for topic"));
+        }
+    }
+    
+    @Test
+    public void testAssertTopic() throws Exception {
+        Map<String, List<PartitionInfo>> topics = new HashMap<>();
+        topics.put(TOPIC, Collections.emptyList());
+        when(consumer.listTopics()).thenReturn(topics);
+        provider.assertTopic(TOPIC);
+    }
+    
+    @Test
+    public void testRetrieveEarliestOffset() throws Exception {
+        Map<TopicPartition, Long> offsets = new HashMap<>();
+        offsets.put(new TopicPartition(TOPIC, 0), 1l);
+        when(consumer.beginningOffsets(Mockito.any())).thenReturn(offsets);
+        long offset = provider.retrieveOffset(TOPIC, Reset.earliest);
+        assertThat(offset, equalTo(1l));
+    }
+    
+    @Test
+    public void testRetrieveLatestOffset() throws Exception {
+        Map<TopicPartition, Long> offsets = new HashMap<>();
+        offsets.put(new TopicPartition(TOPIC, 0), 1l);
+        when(consumer.endOffsets(Mockito.any())).thenReturn(offsets);
+        long offset = provider.retrieveOffset(TOPIC, Reset.latest);
+        assertThat(offset, equalTo(1l));
+    }
+    
+    @Test
+    public void testAssignTo() throws Exception {
+        String assign = provider.assignTo(1l);
+        assertThat(assign, equalTo("0:1"));
+    }
+
+    private KafkaEndpoint createConfig() {
+        Map<String, String> props = new HashMap<>();
+        KafkaEndpoint config = standardConverter().convert(props).to(KafkaEndpoint.class);
+        return config;
+    }
+}
diff --git a/src/test/java/org/apache/sling/distribution/journal/kafka/KafkaMessageInfoTest.java b/src/test/java/org/apache/sling/distribution/journal/kafka/KafkaMessageInfoTest.java
new file mode 100644
index 0000000..75a385b
--- /dev/null
+++ b/src/test/java/org/apache/sling/distribution/journal/kafka/KafkaMessageInfoTest.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+package org.apache.sling.distribution.journal.kafka;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.when;
+
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class KafkaMessageInfoTest {
+    private static final int PARTITION = 0;
+    private static final long OFFSET = 1l;
+    private static final long TIMESTAMP = 2l;
+    private static final String TOPIC = "topic";
+    
+    @Mock
+    private ConsumerRecord<String, String> record;
+
+    @Test
+    public void test() {
+        when(record.offset()).thenReturn(OFFSET);
+        when(record.partition()).thenReturn(PARTITION);
+        when(record.timestamp()).thenReturn(TIMESTAMP);
+        when(record.topic()).thenReturn(TOPIC);
+
+        KafkaMessageInfo info = new KafkaMessageInfo(record);
+        
+        assertThat(info.getOffset(), equalTo(OFFSET));
+        assertThat(info.getPartition(), equalTo(PARTITION));
+        assertThat(info.getTopic(), equalTo(TOPIC));
+        assertThat(info.getCreateTime(), equalTo(TIMESTAMP));
+        assertThat(info.toString(), equalTo("Topic: topic, Partition: 0, Offset: 1, CreateTime: 2"));
+    }
+}
diff --git a/src/test/java/org/apache/sling/distribution/journal/kafka/KafkaMessageSenderTest.java b/src/test/java/org/apache/sling/distribution/journal/kafka/KafkaMessageSenderTest.java
new file mode 100644
index 0000000..eee5a22
--- /dev/null
+++ b/src/test/java/org/apache/sling/distribution/journal/kafka/KafkaMessageSenderTest.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+package org.apache.sling.distribution.journal.kafka;
+
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.RecordMetadata;
+import org.apache.sling.distribution.journal.MessagingException;
+import org.apache.sling.distribution.journal.messages.Messages.ClearCommand;
+import org.apache.sling.distribution.journal.messages.Messages.PingMessage;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+
+import com.google.protobuf.GeneratedMessage;
+
+@RunWith(MockitoJUnitRunner.class)
+public class KafkaMessageSenderTest {
+
+    private static final String TOPIC = "topic";
+
+    @Mock
+    private KafkaProducer<String, byte[]> producer;
+    
+    @InjectMocks
+    private KafkaMessageSender<GeneratedMessage> sender;
+
+    @Mock
+    private Future<RecordMetadata> record;
+    
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testNoMapping() throws Exception {
+        GeneratedMessage payload = ClearCommand.newBuilder().setOffset(0l).build();
+        sender.send(TOPIC, payload);
+    }
+    
+    @Test(expected = MessagingException.class)
+    public void testSendError() throws Exception {
+        when(producer.send(Mockito.any())).thenReturn(record);
+        when(record.get()).thenThrow(new ExecutionException(new IOException("Expected")));
+        GeneratedMessage payload = PingMessage.newBuilder().build();
+        sender.send(TOPIC, payload);
+    }
+}