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.junit.jupiter.api.*;
13 import org.springframework.beans.factory.annotation.Autowired;
14 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
15 import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
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.kafka.test.context.EmbeddedKafka;
21 import org.springframework.test.context.TestPropertySource;
22 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
24 import java.time.Duration;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
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.*;
40 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
41 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
44 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
45 "consumer.topic=" + TOPIC,
46 "spring.mongodb.embedded.version=4.4.13" })
47 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
48 @EnableAutoConfiguration
49 @AutoConfigureDataMongo
51 class ApplicationTests
53 public static final String TOPIC = "FOO";
54 public static final int PARTITIONS = 10;
57 StringSerializer stringSerializer = new StringSerializer();
60 Serializer valueSerializer;
62 KafkaProducer<String, Bytes> kafkaProducer;
64 KafkaConsumer<String, Long> kafkaConsumer;
66 KafkaConsumer<Bytes, Bytes> offsetConsumer;
68 ApplicationProperties properties;
70 ExecutorService executor;
72 PartitionStatisticsRepository repository;
74 Consumer<ConsumerRecord<String, Long>> testHandler;
75 EndlessConsumer<String, Long> endlessConsumer;
76 Map<TopicPartition, Long> oldOffsets;
77 Map<TopicPartition, Long> newOffsets;
78 Set<ConsumerRecord<String, Long>> receivedRecords;
84 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
85 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
87 send100Messages(i -> new Bytes(valueSerializer.serialize(TOPIC, i)));
89 await("100 records received")
90 .atMost(Duration.ofSeconds(30))
91 .until(() -> receivedRecords.size() >= 100);
93 await("Offsets committed")
94 .atMost(Duration.ofSeconds(10))
97 checkSeenOffsetsForProgress();
98 compareToCommitedOffsets(newOffsets);
101 assertThatExceptionOfType(IllegalStateException.class)
102 .isThrownBy(() -> endlessConsumer.exitStatus())
103 .describedAs("Consumer should still be running");
108 void commitsOffsetOfErrorForReprocessingOnError()
110 send100Messages(counter ->
112 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
113 : new Bytes(valueSerializer.serialize(TOPIC, counter)));
115 await("Consumer failed")
116 .atMost(Duration.ofSeconds(30))
117 .until(() -> !endlessConsumer.running());
119 checkSeenOffsetsForProgress();
120 compareToCommitedOffsets(newOffsets);
122 endlessConsumer.start();
123 await("Consumer failed")
124 .atMost(Duration.ofSeconds(30))
125 .until(() -> !endlessConsumer.running());
127 checkSeenOffsetsForProgress();
128 compareToCommitedOffsets(newOffsets);
129 assertThat(receivedRecords.size())
130 .describedAs("Received not all sent events")
133 assertThatNoException()
134 .describedAs("Consumer should not be running")
135 .isThrownBy(() -> endlessConsumer.exitStatus());
136 assertThat(endlessConsumer.exitStatus())
137 .describedAs("Consumer should have exited abnormally")
138 .containsInstanceOf(RecordDeserializationException.class);
142 /** Helper methods for the verification of expectations */
144 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
146 doForCurrentOffsets((tp, offset) ->
148 Long expected = offsetsToCheck.get(tp) + 1;
149 log.debug("Checking, if the offset for {} is {}", tp, expected);
151 .describedAs("Committed offset corresponds to the offset of the consumer")
152 .isEqualTo(expected);
156 void checkSeenOffsetsForProgress()
158 // Be sure, that some messages were consumed...!
159 Set<TopicPartition> withProgress = new HashSet<>();
160 partitions().forEach(tp ->
162 Long oldOffset = oldOffsets.get(tp);
163 Long newOffset = newOffsets.get(tp);
164 if (!oldOffset.equals(newOffset))
166 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
167 withProgress.add(tp);
170 assertThat(withProgress)
171 .describedAs("Some offsets must have changed, compared to the old offset-positions")
176 /** Helper methods for setting up and running the tests */
178 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
180 offsetConsumer.assign(partitions());
181 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
182 offsetConsumer.unsubscribe();
185 List<TopicPartition> partitions()
189 .range(0, PARTITIONS)
190 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
191 .collect(Collectors.toList());
195 void send100Messages(Function<Long, Bytes> messageGenerator)
199 for (int partition = 0; partition < 10; partition++)
201 for (int key = 0; key < 10; key++)
203 Bytes value = messageGenerator.apply(++i);
205 ProducerRecord<String, Bytes> record =
206 new ProducerRecord<>(
209 Integer.toString(key%2),
212 kafkaProducer.send(record, (metadata, e) ->
214 if (metadata != null)
218 metadata.partition(),
226 "Exception for {}={}: {}",
240 testHandler = record -> {} ;
242 oldOffsets = new HashMap<>();
243 newOffsets = new HashMap<>();
244 receivedRecords = new HashSet<>();
246 doForCurrentOffsets((tp, offset) ->
248 oldOffsets.put(tp, offset - 1);
249 newOffsets.put(tp, offset - 1);
252 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
256 new TopicPartition(record.topic(), record.partition()),
258 receivedRecords.add(record);
259 testHandler.accept(record);
263 new EndlessConsumer<>(
266 properties.getClientId(),
267 properties.getTopic(),
269 captureOffsetAndExecuteTestHandler);
271 endlessConsumer.start();
279 endlessConsumer.stop();
283 log.info("Exception while stopping the consumer: {}", e.toString());
289 @Import(ApplicationConfiguration.class)
290 public static class Configuration
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);