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.test.context.ConfigDataApplicationContextInitializer;
15 import org.springframework.boot.test.context.TestConfiguration;
16 import org.springframework.context.annotation.Bean;
17 import org.springframework.context.annotation.Import;
18 import org.springframework.kafka.support.serializer.JsonSerializer;
19 import org.springframework.kafka.test.context.EmbeddedKafka;
20 import org.springframework.test.context.TestPropertySource;
21 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
23 import java.time.Duration;
24 import java.time.LocalDateTime;
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.stream.Collectors;
31 import java.util.stream.IntStream;
33 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
34 import static de.juplo.kafka.ApplicationTests.TOPIC;
35 import static org.assertj.core.api.Assertions.*;
36 import static org.awaitility.Awaitility.*;
39 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
40 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
43 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
44 "consumer.topic=" + TOPIC,
45 "consumer.commit-interval=1s" })
46 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
48 class ApplicationTests
50 public static final String TOPIC = "FOO";
51 public static final int PARTITIONS = 10;
54 StringSerializer stringSerializer = new StringSerializer();
57 Serializer valueSerializer;
59 KafkaProducer<String, Bytes> kafkaProducer;
61 KafkaConsumer<String, ValidMessage> kafkaConsumer;
63 KafkaConsumer<Bytes, Bytes> offsetConsumer;
65 ApplicationProperties properties;
67 ExecutorService executor;
69 Consumer<ConsumerRecord<String, ValidMessage>> testHandler;
70 EndlessConsumer<String, ValidMessage> endlessConsumer;
71 Map<TopicPartition, Long> oldOffsets;
72 Map<TopicPartition, Long> newOffsets;
73 Set<ConsumerRecord<String, ValidMessage>> receivedRecords;
79 void commitsCurrentOffsetsOnSuccess()
81 send100Messages((partition, key, counter) ->
88 value = serializeClientMessage(key, counter);
92 value = serializeGreeting(key);
96 return toRecord(partition, key, value, Optional.of(type));
99 await("100 records received")
100 .atMost(Duration.ofSeconds(30))
101 .pollInterval(Duration.ofSeconds(1))
102 .until(() -> receivedRecords.size() >= 100);
104 await("Offsets committed")
105 .atMost(Duration.ofSeconds(10))
106 .pollInterval(Duration.ofSeconds(1))
109 checkSeenOffsetsForProgress();
110 compareToCommitedOffsets(newOffsets);
113 assertThatExceptionOfType(IllegalStateException.class)
114 .isThrownBy(() -> endlessConsumer.exitStatus())
115 .describedAs("Consumer should still be running");
119 void commitsOffsetOfErrorForReprocessingOnDeserializationErrorInvalidMessage()
121 send100Messages((partition, key, counter) ->
128 value = serializeFooMessage(key, counter);
135 value = serializeClientMessage(key, counter);
139 value = serializeGreeting(key);
144 return toRecord(partition, key, value, Optional.ofNullable(type));
147 await("Consumer failed")
148 .atMost(Duration.ofSeconds(30))
149 .pollInterval(Duration.ofSeconds(1))
150 .until(() -> !endlessConsumer.running());
152 checkSeenOffsetsForProgress();
153 compareToCommitedOffsets(newOffsets);
155 endlessConsumer.start();
156 await("Consumer failed")
157 .atMost(Duration.ofSeconds(30))
158 .pollInterval(Duration.ofSeconds(1))
159 .until(() -> !endlessConsumer.running());
161 checkSeenOffsetsForProgress();
162 compareToCommitedOffsets(newOffsets);
163 assertThat(receivedRecords.size())
164 .describedAs("Received not all sent events")
167 assertThatNoException()
168 .describedAs("Consumer should not be running")
169 .isThrownBy(() -> endlessConsumer.exitStatus());
170 assertThat(endlessConsumer.exitStatus())
171 .describedAs("Consumer should have exited abnormally")
172 .containsInstanceOf(RecordDeserializationException.class);
176 void commitsOffsetOfErrorForReprocessingOnDeserializationErrorOnUnknownMessage()
178 send100Messages((partition, key, counter) ->
185 value = serializeFooMessage(key, counter);
192 value = serializeClientMessage(key, counter);
196 value = serializeGreeting(key);
201 return toRecord(partition, key, value, Optional.of(type));
204 await("Consumer failed")
205 .atMost(Duration.ofSeconds(30))
206 .pollInterval(Duration.ofSeconds(1))
207 .until(() -> !endlessConsumer.running());
209 checkSeenOffsetsForProgress();
210 compareToCommitedOffsets(newOffsets);
212 endlessConsumer.start();
213 await("Consumer failed")
214 .atMost(Duration.ofSeconds(30))
215 .pollInterval(Duration.ofSeconds(1))
216 .until(() -> !endlessConsumer.running());
218 checkSeenOffsetsForProgress();
219 compareToCommitedOffsets(newOffsets);
220 assertThat(receivedRecords.size())
221 .describedAs("Received not all sent events")
224 assertThatNoException()
225 .describedAs("Consumer should not be running")
226 .isThrownBy(() -> endlessConsumer.exitStatus());
227 assertThat(endlessConsumer.exitStatus())
228 .describedAs("Consumer should have exited abnormally")
229 .containsInstanceOf(RecordDeserializationException.class);
233 /** Helper methods for the verification of expectations */
235 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
237 doForCurrentOffsets((tp, offset) ->
239 Long expected = offsetsToCheck.get(tp) + 1;
240 log.debug("Checking, if the offset for {} is {}", tp, expected);
242 .describedAs("Committed offset corresponds to the offset of the consumer")
243 .isEqualTo(expected);
247 void checkSeenOffsetsForProgress()
249 // Be sure, that some messages were consumed...!
250 Set<TopicPartition> withProgress = new HashSet<>();
251 partitions().forEach(tp ->
253 Long oldOffset = oldOffsets.get(tp) + 1;
254 Long newOffset = newOffsets.get(tp) + 1;
255 if (!oldOffset.equals(newOffset))
257 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
258 withProgress.add(tp);
261 assertThat(withProgress)
262 .describedAs("Some offsets must have changed, compared to the old offset-positions")
267 /** Helper methods for setting up and running the tests */
271 offsetConsumer.assign(partitions());
272 offsetConsumer.seekToEnd(partitions());
273 partitions().forEach(tp ->
275 // seekToEnd() works lazily: it only takes effect on poll()/position()
276 Long offset = offsetConsumer.position(tp);
277 log.info("New position for {}: {}", tp, offset);
279 // The new positions must be commited!
280 offsetConsumer.commitSync();
281 offsetConsumer.unsubscribe();
284 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
286 offsetConsumer.assign(partitions());
287 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
288 offsetConsumer.unsubscribe();
291 List<TopicPartition> partitions()
295 .range(0, PARTITIONS)
296 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
297 .collect(Collectors.toList());
301 public interface RecordGenerator<K, V>
303 public ProducerRecord<String, Bytes> generate(int partition, String key, int counter);
306 void send100Messages(RecordGenerator recordGenerator)
310 for (int partition = 0; partition < 10; partition++)
312 for (int key = 0; key < 10; key++)
314 ProducerRecord<String, Bytes> record =
315 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
317 kafkaProducer.send(record, (metadata, e) ->
319 if (metadata != null)
323 metadata.partition(),
331 "Exception for {}={}: {}",
341 ProducerRecord<String, Bytes> toRecord(int partition, String key, Bytes value, Optional<String> type)
343 ProducerRecord<String, Bytes> record =
344 new ProducerRecord<>(TOPIC, partition, key, value);
346 type.ifPresent(typeId -> record.headers().add("__TypeId__", typeId.getBytes()));
350 Bytes serializeClientMessage(String key, int value)
352 TestClientMessage message = new TestClientMessage(key, Integer.toString(value));
353 return new Bytes(valueSerializer.serialize(TOPIC, message));
356 Bytes serializeGreeting(String key)
358 TestGreeting message = new TestGreeting(key, LocalDateTime.now());
359 return new Bytes(valueSerializer.serialize(TOPIC, message));
362 Bytes serializeFooMessage(String key, int value)
364 TestFooMessage message = new TestFooMessage(key, (long)value);
365 return new Bytes(valueSerializer.serialize(TOPIC, message));
371 testHandler = record -> {} ;
375 oldOffsets = new HashMap<>();
376 newOffsets = new HashMap<>();
377 receivedRecords = new HashSet<>();
379 doForCurrentOffsets((tp, offset) ->
381 oldOffsets.put(tp, offset - 1);
382 newOffsets.put(tp, offset - 1);
385 Consumer<ConsumerRecord<String, ValidMessage>> captureOffsetAndExecuteTestHandler =
389 new TopicPartition(record.topic(), record.partition()),
391 receivedRecords.add(record);
392 testHandler.accept(record);
396 new EndlessConsumer<>(
398 properties.getClientId(),
399 properties.getTopic(),
401 captureOffsetAndExecuteTestHandler);
403 endlessConsumer.start();
411 endlessConsumer.stop();
415 log.info("Exception while stopping the consumer: {}", e.toString());
421 @Import(ApplicationConfiguration.class)
422 public static class Configuration
425 Serializer<ValidMessage> serializer()
427 return new JsonSerializer<>();
431 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
433 Properties props = new Properties();
434 props.put("bootstrap.servers", properties.getBootstrapServer());
435 props.put("linger.ms", 100);
436 props.put("key.serializer", StringSerializer.class.getName());
437 props.put("value.serializer", BytesSerializer.class.getName());
439 return new KafkaProducer<>(props);
443 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
445 Properties props = new Properties();
446 props.put("bootstrap.servers", properties.getBootstrapServer());
447 props.put("client.id", "OFFSET-CONSUMER");
448 props.put("group.id", properties.getGroupId());
449 props.put("key.deserializer", BytesDeserializer.class.getName());
450 props.put("value.deserializer", BytesDeserializer.class.getName());
452 return new KafkaConsumer<>(props);