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.KafkaAutoConfiguration;
15 import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
16 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
17 import org.springframework.boot.test.context.TestConfiguration;
18 import org.springframework.context.annotation.Bean;
19 import org.springframework.context.annotation.Import;
20 import org.springframework.kafka.test.context.EmbeddedKafka;
21 import org.springframework.test.context.TestPropertySource;
22 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
24 import java.time.Duration;
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.function.Function;
31 import java.util.stream.Collectors;
32 import java.util.stream.IntStream;
34 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
35 import static de.juplo.kafka.ApplicationTests.TOPIC;
36 import static org.assertj.core.api.Assertions.*;
37 import static org.awaitility.Awaitility.*;
41 initializers = ConfigDataApplicationContextInitializer.class,
43 KafkaAutoConfiguration.class,
44 ApplicationTests.Configuration.class })
45 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
48 "spring.kafka.consumer.bootstrap-servers=${spring.embedded.kafka.brokers}",
49 "consumer.topic=" + TOPIC })
50 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
52 class ApplicationTests
54 public static final String TOPIC = "FOO";
55 public static final int PARTITIONS = 10;
58 StringSerializer stringSerializer = new StringSerializer();
61 Serializer valueSerializer;
63 KafkaProducer<String, Bytes> kafkaProducer;
65 org.apache.kafka.clients.consumer.Consumer<String, Long> kafkaConsumer;
67 KafkaConsumer<Bytes, Bytes> offsetConsumer;
69 ApplicationProperties applicationProperties;
71 KafkaProperties kafkaProperties;
73 ExecutorService executor;
75 Consumer<ConsumerRecord<String, Long>> testHandler;
76 EndlessConsumer<String, Long> endlessConsumer;
77 Map<TopicPartition, Long> oldOffsets;
78 Map<TopicPartition, Long> newOffsets;
79 Set<ConsumerRecord<String, Long>> receivedRecords;
85 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
86 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
88 send100Messages(i -> new Bytes(valueSerializer.serialize(TOPIC, i)));
90 await("100 records received")
91 .atMost(Duration.ofSeconds(30))
92 .until(() -> receivedRecords.size() >= 100);
94 await("Offsets committed")
95 .atMost(Duration.ofSeconds(10))
98 checkSeenOffsetsForProgress();
99 compareToCommitedOffsets(newOffsets);
102 assertThatExceptionOfType(IllegalStateException.class)
103 .isThrownBy(() -> endlessConsumer.exitStatus())
104 .describedAs("Consumer should still be running");
109 void commitsOffsetOfErrorForReprocessingOnError()
111 send100Messages(counter ->
113 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
114 : new Bytes(valueSerializer.serialize(TOPIC, counter)));
116 await("Consumer failed")
117 .atMost(Duration.ofSeconds(30))
118 .until(() -> !endlessConsumer.running());
120 checkSeenOffsetsForProgress();
121 compareToCommitedOffsets(newOffsets);
123 endlessConsumer.start();
124 await("Consumer failed")
125 .atMost(Duration.ofSeconds(30))
126 .until(() -> !endlessConsumer.running());
128 checkSeenOffsetsForProgress();
129 compareToCommitedOffsets(newOffsets);
130 assertThat(receivedRecords.size())
131 .describedAs("Received not all sent events")
134 assertThatNoException()
135 .describedAs("Consumer should not be running")
136 .isThrownBy(() -> endlessConsumer.exitStatus());
137 assertThat(endlessConsumer.exitStatus())
138 .describedAs("Consumer should have exited abnormally")
139 .containsInstanceOf(RecordDeserializationException.class);
143 /** Helper methods for the verification of expectations */
145 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
147 doForCurrentOffsets((tp, offset) ->
149 Long expected = offsetsToCheck.get(tp) + 1;
150 log.debug("Checking, if the offset for {} is {}", tp, expected);
152 .describedAs("Committed offset corresponds to the offset of the consumer")
153 .isEqualTo(expected);
157 void checkSeenOffsetsForProgress()
159 // Be sure, that some messages were consumed...!
160 Set<TopicPartition> withProgress = new HashSet<>();
161 partitions().forEach(tp ->
163 Long oldOffset = oldOffsets.get(tp);
164 Long newOffset = newOffsets.get(tp);
165 if (!oldOffset.equals(newOffset))
167 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
168 withProgress.add(tp);
171 assertThat(withProgress)
172 .describedAs("Some offsets must have changed, compared to the old offset-positions")
177 /** Helper methods for setting up and running the tests */
179 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
181 offsetConsumer.assign(partitions());
182 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
183 offsetConsumer.unsubscribe();
186 List<TopicPartition> partitions()
190 .range(0, PARTITIONS)
191 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
192 .collect(Collectors.toList());
196 void send100Messages(Function<Long, Bytes> messageGenerator)
200 for (int partition = 0; partition < 10; partition++)
202 for (int key = 0; key < 10; key++)
204 Bytes value = messageGenerator.apply(++i);
206 ProducerRecord<String, Bytes> record =
207 new ProducerRecord<>(
210 Integer.toString(key%2),
213 kafkaProducer.send(record, (metadata, e) ->
215 if (metadata != null)
219 metadata.partition(),
227 "Exception for {}={}: {}",
241 testHandler = record -> {} ;
243 oldOffsets = new HashMap<>();
244 newOffsets = new HashMap<>();
245 receivedRecords = new HashSet<>();
247 doForCurrentOffsets((tp, offset) ->
249 oldOffsets.put(tp, offset - 1);
250 newOffsets.put(tp, offset - 1);
253 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
257 new TopicPartition(record.topic(), record.partition()),
259 receivedRecords.add(record);
260 testHandler.accept(record);
264 new EndlessConsumer<>(
266 kafkaProperties.getConsumer().getClientId(),
267 applicationProperties.getTopic(),
269 captureOffsetAndExecuteTestHandler);
271 endlessConsumer.start();
279 endlessConsumer.stop();
283 log.info("Exception while stopping the consumer: {}", e.toString());
289 @Import(ApplicationConfiguration.class)
290 public static class Configuration
293 Serializer<Long> serializer()
295 return new LongSerializer();
299 KafkaProducer<String, Bytes> kafkaProducer(KafkaProperties properties)
301 Properties props = new Properties();
302 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
303 props.put("linger.ms", 100);
304 props.put("key.serializer", StringSerializer.class.getName());
305 props.put("value.serializer", BytesSerializer.class.getName());
307 return new KafkaProducer<>(props);
311 KafkaConsumer<Bytes, Bytes> offsetConsumer(KafkaProperties properties)
313 Properties props = new Properties();
314 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
315 props.put("client.id", "OFFSET-CONSUMER");
316 props.put("group.id", properties.getConsumer().getGroupId());
317 props.put("key.deserializer", BytesDeserializer.class.getName());
318 props.put("value.deserializer", BytesDeserializer.class.getName());
320 return new KafkaConsumer<>(props);