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 @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, ValidMessage> kafkaConsumer;
62 KafkaConsumer<Bytes, Bytes> offsetConsumer;
64 ApplicationProperties properties;
66 ExecutorService executor;
68 Consumer<ConsumerRecord<String, ValidMessage>> testHandler;
69 EndlessConsumer<String, ValidMessage> endlessConsumer;
70 Map<TopicPartition, Long> oldOffsets;
71 Map<TopicPartition, Long> newOffsets;
72 Set<ConsumerRecord<String, ValidMessage>> receivedRecords;
78 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
79 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
81 send100Messages((partition, key, counter) ->
88 value = serializeClientMessage(key, counter);
92 value = serializeGreeting(key, counter);
96 return toRecord(partition, key, value, type);
99 await("100 records received")
100 .atMost(Duration.ofSeconds(30))
101 .until(() -> receivedRecords.size() >= 100);
103 await("Offsets committed")
104 .atMost(Duration.ofSeconds(10))
107 checkSeenOffsetsForProgress();
108 compareToCommitedOffsets(newOffsets);
111 assertThatExceptionOfType(IllegalStateException.class)
112 .isThrownBy(() -> endlessConsumer.exitStatus())
113 .describedAs("Consumer should still be running");
118 void commitsOffsetOfErrorForReprocessingOnError()
120 send100Messages((partition, key, counter) ->
127 value = serializeFooMessage(key, counter);
134 value = serializeClientMessage(key, counter);
138 value = serializeGreeting(key, counter);
143 return toRecord(partition, key, value, type);
146 await("Consumer failed")
147 .atMost(Duration.ofSeconds(30))
148 .until(() -> !endlessConsumer.running());
150 checkSeenOffsetsForProgress();
151 compareToCommitedOffsets(newOffsets);
153 endlessConsumer.start();
154 await("Consumer failed")
155 .atMost(Duration.ofSeconds(30))
156 .until(() -> !endlessConsumer.running());
158 checkSeenOffsetsForProgress();
159 compareToCommitedOffsets(newOffsets);
160 assertThat(receivedRecords.size())
161 .describedAs("Received not all sent events")
164 assertThatNoException()
165 .describedAs("Consumer should not be running")
166 .isThrownBy(() -> endlessConsumer.exitStatus());
167 assertThat(endlessConsumer.exitStatus())
168 .describedAs("Consumer should have exited abnormally")
169 .containsInstanceOf(RecordDeserializationException.class);
173 /** Helper methods for the verification of expectations */
175 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
177 doForCurrentOffsets((tp, offset) ->
179 Long expected = offsetsToCheck.get(tp) + 1;
180 log.debug("Checking, if the offset for {} is {}", tp, expected);
182 .describedAs("Committed offset corresponds to the offset of the consumer")
183 .isEqualTo(expected);
187 void checkSeenOffsetsForProgress()
189 // Be sure, that some messages were consumed...!
190 Set<TopicPartition> withProgress = new HashSet<>();
191 partitions().forEach(tp ->
193 Long oldOffset = oldOffsets.get(tp);
194 Long newOffset = newOffsets.get(tp);
195 if (!oldOffset.equals(newOffset))
197 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
198 withProgress.add(tp);
201 assertThat(withProgress)
202 .describedAs("Some offsets must have changed, compared to the old offset-positions")
207 /** Helper methods for setting up and running the tests */
209 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
211 offsetConsumer.assign(partitions());
212 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
213 offsetConsumer.unsubscribe();
216 List<TopicPartition> partitions()
220 .range(0, PARTITIONS)
221 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
222 .collect(Collectors.toList());
226 public interface RecordGenerator<K, V>
228 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
231 void send100Messages(RecordGenerator recordGenerator)
235 for (int partition = 0; partition < 10; partition++)
237 for (int key = 0; key < 10; key++)
239 ProducerRecord<String, Bytes> record =
240 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
242 kafkaProducer.send(record, (metadata, e) ->
244 if (metadata != null)
248 metadata.partition(),
256 "Exception for {}={}: {}",
266 ProducerRecord<String, Bytes> toRecord(int partition, String key, Bytes value, String type)
268 ProducerRecord<String, Bytes> record =
269 new ProducerRecord<>(TOPIC, partition, key, value);
270 record.headers().add("__TypeId__", type.getBytes());
274 Bytes serializeClientMessage(String key, Long value)
276 TestClientMessage message = new TestClientMessage(key, value.toString());
277 return new Bytes(valueSerializer.serialize(TOPIC, message));
280 Bytes serializeGreeting(String key, Long value)
282 TestGreeting message = new TestGreeting(key, LocalDateTime.now());
283 return new Bytes(valueSerializer.serialize(TOPIC, message));
286 Bytes serializeFooMessage(String key, Long value)
288 TestFooMessage message = new TestFooMessage(key, value);
289 return new Bytes(valueSerializer.serialize(TOPIC, message));
295 testHandler = record -> {} ;
297 oldOffsets = new HashMap<>();
298 newOffsets = new HashMap<>();
299 receivedRecords = new HashSet<>();
301 doForCurrentOffsets((tp, offset) ->
303 oldOffsets.put(tp, offset - 1);
304 newOffsets.put(tp, offset - 1);
307 Consumer<ConsumerRecord<String, ValidMessage>> captureOffsetAndExecuteTestHandler =
311 new TopicPartition(record.topic(), record.partition()),
313 receivedRecords.add(record);
314 testHandler.accept(record);
318 new EndlessConsumer<>(
320 properties.getClientId(),
321 properties.getTopic(),
323 captureOffsetAndExecuteTestHandler);
325 endlessConsumer.start();
333 endlessConsumer.stop();
337 log.info("Exception while stopping the consumer: {}", e.toString());
343 @Import(ApplicationConfiguration.class)
344 public static class Configuration
347 Serializer<ValidMessage> serializer()
349 return new JsonSerializer<>();
353 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
355 Properties props = new Properties();
356 props.put("bootstrap.servers", properties.getBootstrapServer());
357 props.put("linger.ms", 100);
358 props.put("key.serializer", StringSerializer.class.getName());
359 props.put("value.serializer", BytesSerializer.class.getName());
361 return new KafkaProducer<>(props);
365 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
367 Properties props = new Properties();
368 props.put("bootstrap.servers", properties.getBootstrapServer());
369 props.put("client.id", "OFFSET-CONSUMER");
370 props.put("group.id", properties.getGroupId());
371 props.put("key.deserializer", BytesDeserializer.class.getName());
372 props.put("value.deserializer", BytesDeserializer.class.getName());
374 return new KafkaConsumer<>(props);