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.test.context.EmbeddedKafka;
19 import org.springframework.test.context.TestPropertySource;
20 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
22 import java.time.Duration;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.ExecutorService;
26 import java.util.function.BiConsumer;
27 import java.util.function.Consumer;
28 import java.util.stream.Collectors;
29 import java.util.stream.IntStream;
31 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
32 import static de.juplo.kafka.ApplicationTests.TOPIC;
33 import static org.assertj.core.api.Assertions.*;
34 import static org.awaitility.Awaitility.*;
37 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
38 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
41 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
42 "consumer.topic=" + TOPIC,
43 "consumer.commit-interval=1s" })
44 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
46 class ApplicationTests
48 public static final String TOPIC = "FOO";
49 public static final int PARTITIONS = 10;
52 StringSerializer stringSerializer = new StringSerializer();
55 Serializer valueSerializer;
57 KafkaProducer<String, Bytes> kafkaProducer;
59 KafkaConsumer<String, Long> kafkaConsumer;
61 KafkaConsumer<Bytes, Bytes> offsetConsumer;
63 ApplicationProperties properties;
65 ExecutorService executor;
67 Consumer<ConsumerRecord<String, Long>> testHandler;
68 EndlessConsumer<String, Long> endlessConsumer;
69 Map<TopicPartition, Long> oldOffsets;
70 Map<TopicPartition, Long> newOffsets;
71 Set<ConsumerRecord<String, Long>> receivedRecords;
77 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
79 send100Messages((partition, key, counter) ->
81 Bytes value = new Bytes(valueSerializer.serialize(TOPIC, counter));
82 return new ProducerRecord<>(TOPIC, partition, key, value);
85 await("100 records received")
86 .atMost(Duration.ofSeconds(30))
87 .pollInterval(Duration.ofSeconds(1))
88 .until(() -> receivedRecords.size() >= 100);
90 await("Offsets committed")
91 .atMost(Duration.ofSeconds(10))
92 .pollInterval(Duration.ofSeconds(1))
95 checkSeenOffsetsForProgress();
96 compareToCommitedOffsets(newOffsets);
99 assertThatExceptionOfType(IllegalStateException.class)
100 .isThrownBy(() -> endlessConsumer.exitStatus())
101 .describedAs("Consumer should still be running");
105 void commitsOffsetOfErrorForReprocessingOnDeserializationError()
107 send100Messages((partition, key, counter) ->
109 Bytes value = counter == 77
110 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
111 : new Bytes(valueSerializer.serialize(TOPIC, counter));
112 return new ProducerRecord<>(TOPIC, partition, key, value);
115 await("Consumer failed")
116 .atMost(Duration.ofSeconds(30))
117 .pollInterval(Duration.ofSeconds(1))
118 .until(() -> !endlessConsumer.running());
120 checkSeenOffsetsForProgress();
121 compareToCommitedOffsets(newOffsets);
123 endlessConsumer.start();
124 await("Consumer failed")
125 .atMost(Duration.ofSeconds(30))
126 .pollInterval(Duration.ofSeconds(1))
127 .until(() -> !endlessConsumer.running());
129 checkSeenOffsetsForProgress();
130 compareToCommitedOffsets(newOffsets);
131 assertThat(receivedRecords.size())
132 .describedAs("Received not all sent events")
135 assertThatNoException()
136 .describedAs("Consumer should not be running")
137 .isThrownBy(() -> endlessConsumer.exitStatus());
138 assertThat(endlessConsumer.exitStatus())
139 .describedAs("Consumer should have exited abnormally")
140 .containsInstanceOf(RecordDeserializationException.class);
144 /** Helper methods for the verification of expectations */
146 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
148 doForCurrentOffsets((tp, offset) ->
150 Long expected = offsetsToCheck.get(tp) + 1;
151 log.debug("Checking, if the offset for {} is {}", tp, expected);
153 .describedAs("Committed offset corresponds to the offset of the consumer")
154 .isEqualTo(expected);
158 void checkSeenOffsetsForProgress()
160 // Be sure, that some messages were consumed...!
161 Set<TopicPartition> withProgress = new HashSet<>();
162 partitions().forEach(tp ->
164 Long oldOffset = oldOffsets.get(tp) + 1;
165 Long newOffset = newOffsets.get(tp) + 1;
166 if (!oldOffset.equals(newOffset))
168 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
169 withProgress.add(tp);
172 assertThat(withProgress)
173 .describedAs("Some offsets must have changed, compared to the old offset-positions")
178 /** Helper methods for setting up and running the tests */
182 offsetConsumer.assign(partitions());
183 offsetConsumer.seekToEnd(partitions());
184 partitions().forEach(tp ->
186 // seekToEnd() works lazily: it only takes effect on poll()/position()
187 Long offset = offsetConsumer.position(tp);
188 log.info("New position for {}: {}", tp, offset);
190 // The new positions must be commited!
191 offsetConsumer.commitSync();
192 offsetConsumer.unsubscribe();
195 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
197 offsetConsumer.assign(partitions());
198 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
199 offsetConsumer.unsubscribe();
202 List<TopicPartition> partitions()
206 .range(0, PARTITIONS)
207 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
208 .collect(Collectors.toList());
212 public interface RecordGenerator<K, V>
214 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
217 void send100Messages(RecordGenerator recordGenerator)
221 for (int partition = 0; partition < 10; partition++)
223 for (int key = 0; key < 10; key++)
225 ProducerRecord<String, Bytes> record =
226 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
228 kafkaProducer.send(record, (metadata, e) ->
230 if (metadata != null)
234 metadata.partition(),
242 "Exception for {}={}: {}",
256 testHandler = record -> {} ;
260 oldOffsets = new HashMap<>();
261 newOffsets = new HashMap<>();
262 receivedRecords = new HashSet<>();
264 doForCurrentOffsets((tp, offset) ->
266 oldOffsets.put(tp, offset - 1);
267 newOffsets.put(tp, offset - 1);
270 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
274 new TopicPartition(record.topic(), record.partition()),
276 receivedRecords.add(record);
277 testHandler.accept(record);
281 new EndlessConsumer<>(
283 properties.getClientId(),
284 properties.getTopic(),
286 captureOffsetAndExecuteTestHandler);
288 endlessConsumer.start();
296 endlessConsumer.stop();
300 log.info("Exception while stopping the consumer: {}", e.toString());
306 @Import(ApplicationConfiguration.class)
307 public static class Configuration
310 Serializer<Long> serializer()
312 return new LongSerializer();
316 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
318 Properties props = new Properties();
319 props.put("bootstrap.servers", properties.getBootstrapServer());
320 props.put("linger.ms", 100);
321 props.put("key.serializer", StringSerializer.class.getName());
322 props.put("value.serializer", BytesSerializer.class.getName());
324 return new KafkaProducer<>(props);
328 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
330 Properties props = new Properties();
331 props.put("bootstrap.servers", properties.getBootstrapServer());
332 props.put("client.id", "OFFSET-CONSUMER");
333 props.put("group.id", properties.getGroupId());
334 props.put("key.deserializer", BytesDeserializer.class.getName());
335 props.put("value.deserializer", BytesDeserializer.class.getName());
337 return new KafkaConsumer<>(props);