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=100ms" })
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 .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");
103 void commitsOffsetOfErrorForReprocessingOnDeserializationError()
105 send100Messages((partition, key, counter) ->
107 Bytes value = counter == 77
108 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
109 : new Bytes(valueSerializer.serialize(TOPIC, counter));
110 return new ProducerRecord<>(TOPIC, partition, key, value);
113 await("Consumer failed")
114 .atMost(Duration.ofSeconds(30))
115 .until(() -> !endlessConsumer.running());
117 checkSeenOffsetsForProgress();
118 compareToCommitedOffsets(newOffsets);
120 endlessConsumer.start();
121 await("Consumer failed")
122 .atMost(Duration.ofSeconds(30))
123 .until(() -> !endlessConsumer.running());
125 checkSeenOffsetsForProgress();
126 compareToCommitedOffsets(newOffsets);
127 assertThat(receivedRecords.size())
128 .describedAs("Received not all sent events")
131 assertThatNoException()
132 .describedAs("Consumer should not be running")
133 .isThrownBy(() -> endlessConsumer.exitStatus());
134 assertThat(endlessConsumer.exitStatus())
135 .describedAs("Consumer should have exited abnormally")
136 .containsInstanceOf(RecordDeserializationException.class);
140 /** Helper methods for the verification of expectations */
142 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
144 doForCurrentOffsets((tp, offset) ->
146 Long expected = offsetsToCheck.get(tp) + 1;
147 log.debug("Checking, if the offset for {} is {}", tp, expected);
149 .describedAs("Committed offset corresponds to the offset of the consumer")
150 .isEqualTo(expected);
154 void checkSeenOffsetsForProgress()
156 // Be sure, that some messages were consumed...!
157 Set<TopicPartition> withProgress = new HashSet<>();
158 partitions().forEach(tp ->
160 Long oldOffset = oldOffsets.get(tp) + 1;
161 Long newOffset = newOffsets.get(tp) + 1;
162 if (!oldOffset.equals(newOffset))
164 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
165 withProgress.add(tp);
168 assertThat(withProgress)
169 .describedAs("Some offsets must have changed, compared to the old offset-positions")
174 /** Helper methods for setting up and running the tests */
178 offsetConsumer.assign(partitions());
179 offsetConsumer.seekToEnd(partitions());
180 partitions().forEach(tp ->
182 // seekToEnd() works lazily: it only takes effect on poll()/position()
183 Long offset = offsetConsumer.position(tp);
184 log.info("New position for {}: {}", tp, offset);
186 // The new positions must be commited!
187 offsetConsumer.commitSync();
188 offsetConsumer.unsubscribe();
191 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
193 offsetConsumer.assign(partitions());
194 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
195 offsetConsumer.unsubscribe();
198 List<TopicPartition> partitions()
202 .range(0, PARTITIONS)
203 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
204 .collect(Collectors.toList());
208 public interface RecordGenerator<K, V>
210 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
213 void send100Messages(RecordGenerator recordGenerator)
217 for (int partition = 0; partition < 10; partition++)
219 for (int key = 0; key < 10; key++)
221 ProducerRecord<String, Bytes> record =
222 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
224 kafkaProducer.send(record, (metadata, e) ->
226 if (metadata != null)
230 metadata.partition(),
238 "Exception for {}={}: {}",
252 testHandler = record -> {} ;
256 oldOffsets = new HashMap<>();
257 newOffsets = new HashMap<>();
258 receivedRecords = new HashSet<>();
260 doForCurrentOffsets((tp, offset) ->
262 oldOffsets.put(tp, offset - 1);
263 newOffsets.put(tp, offset - 1);
266 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
270 new TopicPartition(record.topic(), record.partition()),
272 receivedRecords.add(record);
273 testHandler.accept(record);
277 new EndlessConsumer<>(
279 properties.getClientId(),
280 properties.getTopic(),
282 captureOffsetAndExecuteTestHandler);
284 endlessConsumer.start();
292 endlessConsumer.stop();
296 log.info("Exception while stopping the consumer: {}", e.toString());
302 @Import(ApplicationConfiguration.class)
303 public static class Configuration
306 Serializer<Long> serializer()
308 return new LongSerializer();
312 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
314 Properties props = new Properties();
315 props.put("bootstrap.servers", properties.getBootstrapServer());
316 props.put("linger.ms", 100);
317 props.put("key.serializer", StringSerializer.class.getName());
318 props.put("value.serializer", BytesSerializer.class.getName());
320 return new KafkaProducer<>(props);
324 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
326 Properties props = new Properties();
327 props.put("bootstrap.servers", properties.getBootstrapServer());
328 props.put("client.id", "OFFSET-CONSUMER");
329 props.put("group.id", properties.getGroupId());
330 props.put("key.deserializer", BytesDeserializer.class.getName());
331 props.put("value.deserializer", BytesDeserializer.class.getName());
333 return new KafkaConsumer<>(props);