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.*;
11 import org.apache.kafka.common.utils.Bytes;
12 import org.assertj.core.api.OptionalAssert;
13 import org.junit.jupiter.api.*;
14 import org.springframework.beans.factory.annotation.Autowired;
15 import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
16 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
17 import org.springframework.boot.test.context.TestConfiguration;
18 import org.springframework.context.annotation.Bean;
19 import org.springframework.context.annotation.Import;
20 import org.springframework.context.annotation.Primary;
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.function.BiConsumer;
29 import java.util.function.Consumer;
30 import java.util.function.Function;
31 import java.util.stream.Collectors;
32 import java.util.stream.IntStream;
34 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
35 import static de.juplo.kafka.ApplicationTests.TOPIC;
36 import static org.assertj.core.api.Assertions.*;
37 import static org.awaitility.Awaitility.*;
41 initializers = ConfigDataApplicationContextInitializer.class,
43 EndlessConsumer.class,
44 KafkaAutoConfiguration.class,
45 ApplicationTests.Configuration.class })
46 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
49 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
50 "consumer.topic=" + TOPIC })
51 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
53 class ApplicationTests
55 public static final String TOPIC = "FOO";
56 public static final int PARTITIONS = 10;
59 StringSerializer stringSerializer = new StringSerializer();
62 Serializer valueSerializer;
64 KafkaProducer<String, Bytes> kafkaProducer;
66 KafkaConsumer<Bytes, Bytes> offsetConsumer;
68 ApplicationProperties properties;
70 EndlessConsumer endlessConsumer;
72 RecordHandler recordHandler;
74 Map<TopicPartition, Long> oldOffsets;
75 Map<TopicPartition, Long> newOffsets;
76 Set<ConsumerRecord<String, Long>> receivedRecords;
82 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
83 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
85 send100Messages(i -> new Bytes(valueSerializer.serialize(TOPIC, i)));
87 await("100 records received")
88 .atMost(Duration.ofSeconds(30))
89 .until(() -> receivedRecords.size() >= 100);
91 await("Offsets committed")
92 .atMost(Duration.ofSeconds(10))
95 checkSeenOffsetsForProgress();
96 compareToCommitedOffsets(newOffsets);
99 assertThatExceptionOfType(IllegalStateException.class)
100 .isThrownBy(() -> endlessConsumer.exitStatus())
101 .describedAs("Consumer should still be running");
106 void commitsOffsetOfErrorForReprocessingOnError()
108 send100Messages(counter ->
110 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
111 : new Bytes(valueSerializer.serialize(TOPIC, counter)));
113 await("Consumer failed")
114 .atMost(Duration.ofSeconds(30))
115 .untilAsserted(() -> checkSeenOffsetsForProgress());
117 compareToCommitedOffsets(newOffsets);
118 assertThat(receivedRecords.size())
119 .describedAs("Received not all sent events")
122 assertThatNoException()
123 .describedAs("Consumer should not be running")
124 .isThrownBy(() -> endlessConsumer.exitStatus());
125 ((OptionalAssert<Exception>)assertThat(endlessConsumer.exitStatus()))
126 .describedAs("Consumer should have exited abnormally")
127 .containsInstanceOf(RecordDeserializationException.class);
131 /** Helper methods for the verification of expectations */
133 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
135 doForCurrentOffsets((tp, offset) ->
137 Long expected = offsetsToCheck.get(tp) + 1;
138 log.debug("Checking, if the offset for {} is {}", tp, expected);
140 .describedAs("Committed offset corresponds to the offset of the consumer")
141 .isEqualTo(expected);
145 void checkSeenOffsetsForProgress()
147 // Be sure, that some messages were consumed...!
148 Set<TopicPartition> withProgress = new HashSet<>();
149 partitions().forEach(tp ->
151 Long oldOffset = oldOffsets.get(tp);
152 Long newOffset = newOffsets.get(tp);
153 if (!oldOffset.equals(newOffset))
155 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
156 withProgress.add(tp);
159 assertThat(withProgress)
160 .describedAs("Some offsets must have changed, compared to the old offset-positions")
165 /** Helper methods for setting up and running the tests */
167 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
169 offsetConsumer.assign(partitions());
170 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
171 offsetConsumer.unsubscribe();
174 List<TopicPartition> partitions()
178 .range(0, PARTITIONS)
179 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
180 .collect(Collectors.toList());
184 void send100Messages(Function<Long, Bytes> messageGenerator)
188 for (int partition = 0; partition < 10; partition++)
190 for (int key = 0; key < 10; key++)
192 Bytes value = messageGenerator.apply(++i);
194 ProducerRecord<String, Bytes> record =
195 new ProducerRecord<>(
198 Integer.toString(key%2),
201 kafkaProducer.send(record, (metadata, e) ->
203 if (metadata != null)
207 metadata.partition(),
215 "Exception for {}={}: {}",
229 recordHandler.testHandler = (record) -> {};
231 oldOffsets = new HashMap<>();
232 newOffsets = new HashMap<>();
233 receivedRecords = new HashSet<>();
235 doForCurrentOffsets((tp, offset) ->
237 oldOffsets.put(tp, offset - 1);
238 newOffsets.put(tp, offset - 1);
241 recordHandler.captureOffsets =
244 receivedRecords.add(record);
246 new TopicPartition(record.topic(), record.partition()),
250 endlessConsumer.start();
258 endlessConsumer.stop();
262 log.info("Exception while stopping the consumer: {}", e.toString());
266 public static class RecordHandler implements Consumer<ConsumerRecord<String, Long>>
268 Consumer<ConsumerRecord<String, Long>> captureOffsets;
269 Consumer<ConsumerRecord<String, Long>> testHandler;
273 public void accept(ConsumerRecord<String, Long> record)
276 .andThen(testHandler)
282 @Import(ApplicationConfiguration.class)
283 public static class Configuration
287 public Consumer<ConsumerRecord<String, Long>> testHandler()
289 return new RecordHandler();
293 Serializer<Long> serializer()
295 return new LongSerializer();
299 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
301 Properties props = new Properties();
302 props.put("bootstrap.servers", properties.getBootstrapServer());
303 props.put("linger.ms", 100);
304 props.put("key.serializer", StringSerializer.class.getName());
305 props.put("value.serializer", BytesSerializer.class.getName());
307 return new KafkaProducer<>(props);
311 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
313 Properties props = new Properties();
314 props.put("bootstrap.servers", properties.getBootstrapServer());
315 props.put("client.id", "OFFSET-CONSUMER");
316 props.put("group.id", properties.getGroupId());
317 props.put("key.deserializer", BytesDeserializer.class.getName());
318 props.put("value.deserializer", BytesDeserializer.class.getName());
320 return new KafkaConsumer<>(props);