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.kafka.KafkaProperties;
15 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
16 import org.springframework.boot.test.context.TestConfiguration;
17 import org.springframework.context.annotation.Bean;
18 import org.springframework.context.annotation.Import;
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;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.ExecutorService;
27 import java.util.function.BiConsumer;
28 import java.util.function.Consumer;
29 import java.util.function.Function;
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 "spring.kafka.consumer.bootstrap-servers=${spring.embedded.kafka.brokers}",
44 "consumer.topic=" + TOPIC })
45 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
47 class ApplicationTests
49 public static final String TOPIC = "FOO";
50 public static final int PARTITIONS = 10;
53 StringSerializer stringSerializer = new StringSerializer();
56 Serializer valueSerializer;
58 KafkaProducer<String, Bytes> kafkaProducer;
60 KafkaConsumer<String, Long> kafkaConsumer;
62 KafkaConsumer<Bytes, Bytes> offsetConsumer;
64 ApplicationProperties applicationProperties;
66 KafkaProperties kafkaProperties;
68 ExecutorService executor;
70 Consumer<ConsumerRecord<String, Long>> testHandler;
71 EndlessConsumer<String, Long> endlessConsumer;
72 Map<TopicPartition, Long> oldOffsets;
73 Map<TopicPartition, Long> newOffsets;
74 Set<ConsumerRecord<String, Long>> receivedRecords;
80 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
81 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
83 send100Messages(i -> new Bytes(valueSerializer.serialize(TOPIC, i)));
85 await("100 records received")
86 .atMost(Duration.ofSeconds(30))
87 .until(() -> receivedRecords.size() >= 100);
89 await("Offsets committed")
90 .atMost(Duration.ofSeconds(10))
93 checkSeenOffsetsForProgress();
94 compareToCommitedOffsets(newOffsets);
97 assertThatExceptionOfType(IllegalStateException.class)
98 .isThrownBy(() -> endlessConsumer.exitStatus())
99 .describedAs("Consumer should still be running");
104 void commitsOffsetOfErrorForReprocessingOnError()
106 send100Messages(counter ->
108 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
109 : new Bytes(valueSerializer.serialize(TOPIC, counter)));
111 await("Consumer failed")
112 .atMost(Duration.ofSeconds(30))
113 .until(() -> !endlessConsumer.running());
115 checkSeenOffsetsForProgress();
116 compareToCommitedOffsets(newOffsets);
118 endlessConsumer.start();
119 await("Consumer failed")
120 .atMost(Duration.ofSeconds(30))
121 .until(() -> !endlessConsumer.running());
123 checkSeenOffsetsForProgress();
124 compareToCommitedOffsets(newOffsets);
125 assertThat(receivedRecords.size())
126 .describedAs("Received not all sent events")
129 assertThatNoException()
130 .describedAs("Consumer should not be running")
131 .isThrownBy(() -> endlessConsumer.exitStatus());
132 assertThat(endlessConsumer.exitStatus())
133 .describedAs("Consumer should have exited abnormally")
134 .containsInstanceOf(RecordDeserializationException.class);
138 /** Helper methods for the verification of expectations */
140 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
142 doForCurrentOffsets((tp, offset) ->
144 Long expected = offsetsToCheck.get(tp) + 1;
145 log.debug("Checking, if the offset for {} is {}", tp, expected);
147 .describedAs("Committed offset corresponds to the offset of the consumer")
148 .isEqualTo(expected);
152 void checkSeenOffsetsForProgress()
154 // Be sure, that some messages were consumed...!
155 Set<TopicPartition> withProgress = new HashSet<>();
156 partitions().forEach(tp ->
158 Long oldOffset = oldOffsets.get(tp);
159 Long newOffset = newOffsets.get(tp);
160 if (!oldOffset.equals(newOffset))
162 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
163 withProgress.add(tp);
166 assertThat(withProgress)
167 .describedAs("Some offsets must have changed, compared to the old offset-positions")
172 /** Helper methods for setting up and running the tests */
174 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
176 offsetConsumer.assign(partitions());
177 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
178 offsetConsumer.unsubscribe();
181 List<TopicPartition> partitions()
185 .range(0, PARTITIONS)
186 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
187 .collect(Collectors.toList());
191 void send100Messages(Function<Long, Bytes> messageGenerator)
195 for (int partition = 0; partition < 10; partition++)
197 for (int key = 0; key < 10; key++)
199 Bytes value = messageGenerator.apply(++i);
201 ProducerRecord<String, Bytes> record =
202 new ProducerRecord<>(
205 Integer.toString(key%2),
208 kafkaProducer.send(record, (metadata, e) ->
210 if (metadata != null)
214 metadata.partition(),
222 "Exception for {}={}: {}",
236 testHandler = record -> {} ;
238 oldOffsets = new HashMap<>();
239 newOffsets = new HashMap<>();
240 receivedRecords = new HashSet<>();
242 doForCurrentOffsets((tp, offset) ->
244 oldOffsets.put(tp, offset - 1);
245 newOffsets.put(tp, offset - 1);
248 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
252 new TopicPartition(record.topic(), record.partition()),
254 receivedRecords.add(record);
255 testHandler.accept(record);
259 new EndlessConsumer<>(
261 kafkaProperties.getConsumer().getClientId(),
262 applicationProperties.getTopic(),
264 captureOffsetAndExecuteTestHandler);
266 endlessConsumer.start();
274 endlessConsumer.stop();
278 log.info("Exception while stopping the consumer: {}", e.toString());
284 @Import(ApplicationConfiguration.class)
285 public static class Configuration
288 Serializer<Long> serializer()
290 return new LongSerializer();
294 KafkaProducer<String, Bytes> kafkaProducer(KafkaProperties properties)
296 Properties props = new Properties();
297 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
298 props.put("linger.ms", 100);
299 props.put("key.serializer", StringSerializer.class.getName());
300 props.put("value.serializer", BytesSerializer.class.getName());
302 return new KafkaProducer<>(props);
306 KafkaConsumer<Bytes, Bytes> offsetConsumer(KafkaProperties properties)
308 Properties props = new Properties();
309 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
310 props.put("client.id", "OFFSET-CONSUMER");
311 props.put("group.id", properties.getConsumer().getGroupId());
312 props.put("key.deserializer", BytesDeserializer.class.getName());
313 props.put("value.deserializer", BytesDeserializer.class.getName());
315 return new KafkaConsumer<>(props);