1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRecord;
5 import org.apache.kafka.clients.consumer.KafkaConsumer;
6 import org.apache.kafka.clients.producer.KafkaProducer;
7 import org.apache.kafka.clients.producer.ProducerRecord;
8 import org.apache.kafka.common.TopicPartition;
9 import org.apache.kafka.common.errors.RecordDeserializationException;
10 import org.apache.kafka.common.serialization.BytesDeserializer;
11 import org.apache.kafka.common.serialization.BytesSerializer;
12 import org.apache.kafka.common.serialization.LongSerializer;
13 import org.apache.kafka.common.serialization.StringSerializer;
14 import org.apache.kafka.common.utils.Bytes;
15 import org.junit.jupiter.api.*;
16 import org.springframework.beans.factory.annotation.Autowired;
17 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
18 import org.springframework.boot.test.context.TestConfiguration;
19 import org.springframework.context.annotation.Bean;
20 import org.springframework.context.annotation.Import;
21 import org.springframework.kafka.test.context.EmbeddedKafka;
22 import org.springframework.test.context.TestPropertySource;
23 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
25 import java.time.Duration;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.ExecutorService;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import java.util.stream.IntStream;
35 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
36 import static de.juplo.kafka.ApplicationTests.TOPIC;
37 import static org.assertj.core.api.Assertions.assertThat;
38 import static org.awaitility.Awaitility.*;
39 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
40 import static org.junit.jupiter.api.Assertions.assertThrows;
43 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
44 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
47 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
48 "consumer.topic=" + TOPIC })
49 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
51 class ApplicationTests
53 public static final String TOPIC = "FOO";
54 public static final int PARTITIONS = 10;
57 StringSerializer stringSerializer = new StringSerializer();
58 LongSerializer longSerializer = new LongSerializer();
61 KafkaProducer<String, Bytes> kafkaProducer;
63 KafkaConsumer<String, Long> kafkaConsumer;
65 KafkaConsumer<Bytes, Bytes> offsetConsumer;
67 ApplicationProperties properties;
69 ExecutorService executor;
71 Consumer<ConsumerRecord<String, Long>> testHandler;
72 EndlessConsumer<String, Long> endlessConsumer;
73 Map<TopicPartition, Long> oldOffsets;
74 Map<TopicPartition, Long> newOffsets;
75 Set<ConsumerRecord<String, Long>> receivedRecords;
81 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
82 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
84 send100Messages(i -> new Bytes(longSerializer.serialize(TOPIC, i)));
86 await("100 records received")
87 .atMost(Duration.ofSeconds(30))
88 .until(() -> receivedRecords.size() >= 100);
90 await("Offsets committed")
91 .atMost(Duration.ofSeconds(10))
94 checkSeenOffsetsForProgress();
95 compareToCommitedOffsets(newOffsets);
99 IllegalStateException.class,
100 () -> endlessConsumer.exitStatus(),
101 "Consumer should still be running");
106 void commitsOffsetOfErrorForReprocessingOnError()
108 send100Messages(counter ->
110 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
111 : new Bytes(longSerializer.serialize(TOPIC, counter)));
113 await("Consumer failed")
114 .atMost(Duration.ofSeconds(30))
115 .until(() -> !endlessConsumer.running());
117 checkSeenOffsetsForProgress();
118 compareToCommitedOffsets(newOffsets);
120 endlessConsumer.start();
121 await("Consumer failed")
122 .atMost(Duration.ofSeconds(30))
123 .until(() -> !endlessConsumer.running());
125 checkSeenOffsetsForProgress();
126 compareToCommitedOffsets(newOffsets);
127 assertThat(receivedRecords.size())
128 .describedAs("Received not all sent events")
132 () -> endlessConsumer.exitStatus(),
133 "Consumer should not be running");
134 assertThat(endlessConsumer.exitStatus())
135 .describedAs("Consumer should have exited abnormally")
136 .containsInstanceOf(RecordDeserializationException.class);
140 /** Helper methods for the verification of expectations */
142 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
144 doForCurrentOffsets((tp, offset) ->
146 Long expected = offsetsToCheck.get(tp) + 1;
147 log.debug("Checking, if the offset for {} is {}", tp, expected);
149 .describedAs("Committed offset corresponds to the offset of the consumer")
150 .isEqualTo(expected);
154 void checkSeenOffsetsForProgress()
156 // Be sure, that some messages were consumed...!
157 Set<TopicPartition> withProgress = new HashSet<>();
158 partitions().forEach(tp ->
160 Long oldOffset = oldOffsets.get(tp);
161 Long newOffset = newOffsets.get(tp);
162 if (!oldOffset.equals(newOffset))
164 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
165 withProgress.add(tp);
168 assertThat(withProgress)
169 .describedAs("Some offsets must have changed, compared to the old offset-positions")
174 /** Helper methods for setting up and running the tests */
176 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
178 offsetConsumer.assign(partitions());
179 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
180 offsetConsumer.unsubscribe();
183 List<TopicPartition> partitions()
187 .range(0, PARTITIONS)
188 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
189 .collect(Collectors.toList());
193 void send100Messages(Function<Long, Bytes> messageGenerator)
197 for (int partition = 0; partition < 10; partition++)
199 for (int key = 0; key < 10; key++)
201 Bytes value = messageGenerator.apply(++i);
203 ProducerRecord<String, Bytes> record =
204 new ProducerRecord<>(
207 Integer.toString(key%2),
210 kafkaProducer.send(record, (metadata, e) ->
212 if (metadata != null)
216 metadata.partition(),
224 "Exception for {}={}: {}",
238 testHandler = record -> {} ;
240 oldOffsets = new HashMap<>();
241 newOffsets = new HashMap<>();
242 receivedRecords = new HashSet<>();
244 doForCurrentOffsets((tp, offset) ->
246 oldOffsets.put(tp, offset - 1);
247 newOffsets.put(tp, offset - 1);
250 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
254 new TopicPartition(record.topic(), record.partition()),
256 receivedRecords.add(record);
257 testHandler.accept(record);
261 new EndlessConsumer<>(
263 properties.getClientId(),
264 properties.getTopic(),
266 captureOffsetAndExecuteTestHandler);
268 endlessConsumer.start();
276 endlessConsumer.stop();
280 log.info("Exception while stopping the consumer: {}", e.toString());
286 @Import(ApplicationConfiguration.class)
287 public static class Configuration
290 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
292 Properties props = new Properties();
293 props.put("bootstrap.servers", properties.getBootstrapServer());
294 props.put("linger.ms", 100);
295 props.put("key.serializer", StringSerializer.class.getName());
296 props.put("value.serializer", BytesSerializer.class.getName());
298 return new KafkaProducer<>(props);
302 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
304 Properties props = new Properties();
305 props.put("bootstrap.servers", properties.getBootstrapServer());
306 props.put("client.id", "OFFSET-CONSUMER");
307 props.put("group.id", properties.getGroupId());
308 props.put("key.deserializer", BytesDeserializer.class.getName());
309 props.put("value.deserializer", BytesDeserializer.class.getName());
311 return new KafkaConsumer<>(props);