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.serialization.BytesDeserializer;
10 import org.apache.kafka.common.serialization.BytesSerializer;
11 import org.apache.kafka.common.serialization.LongSerializer;
12 import org.apache.kafka.common.serialization.StringSerializer;
13 import org.apache.kafka.common.utils.Bytes;
14 import org.junit.jupiter.api.*;
15 import org.springframework.beans.factory.annotation.Autowired;
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.assertThat;
37 import static org.awaitility.Awaitility.*;
40 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
41 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
44 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
45 "consumer.topic=" + TOPIC })
46 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
48 class ApplicationTests
50 public static final String TOPIC = "FOO";
51 public static final int PARTITIONS = 10;
54 StringSerializer stringSerializer = new StringSerializer();
55 LongSerializer longSerializer = new LongSerializer();
58 KafkaProducer<String, Bytes> kafkaProducer;
60 KafkaConsumer<String, Long> kafkaConsumer;
62 KafkaConsumer<Bytes, Bytes> offsetConsumer;
64 ApplicationProperties properties;
66 ExecutorService executor;
68 Consumer<ConsumerRecord<String, Long>> testHandler;
69 EndlessConsumer<String, Long> endlessConsumer;
70 Map<TopicPartition, Long> oldOffsets;
71 Map<TopicPartition, Long> newOffsets;
77 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
78 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
80 send100Messages(i -> new Bytes(longSerializer.serialize(TOPIC, i)));
82 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
83 testHandler = record -> received.add(record);
85 await("100 records received")
86 .atMost(Duration.ofSeconds(30))
87 .until(() -> received.size() >= 100);
89 await("Offsets committed")
90 .atMost(Duration.ofSeconds(10))
93 checkSeenOffsetsForProgress();
94 compareToCommitedOffsets(newOffsets);
100 void commitsOffsetOfErrorForReprocessingOnError()
102 send100Messages(counter ->
104 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
105 : new Bytes(longSerializer.serialize(TOPIC, counter)));
107 await("Consumer failed")
108 .atMost(Duration.ofSeconds(30))
109 .until(() -> !endlessConsumer.running());
111 checkSeenOffsetsForProgress();
112 compareToCommitedOffsets(newOffsets);
114 endlessConsumer.start();
115 await("Consumer failed")
116 .atMost(Duration.ofSeconds(30))
117 .until(() -> !endlessConsumer.running());
119 checkSeenOffsetsForProgress();
120 compareToCommitedOffsets(newOffsets);
124 /** Helper methods for the verification of expectations */
126 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
128 doForCurrentOffsets((tp, offset) ->
130 Long expected = offsetsToCheck.get(tp) + 1;
131 log.debug("Checking, if the offset for {} is {}", tp, expected);
132 assertThat(offset).isEqualTo(expected);
136 void checkSeenOffsetsForProgress()
138 // Be sure, that some messages were consumed...!
139 Set<TopicPartition> withProgress = new HashSet<>();
140 partitions().forEach(tp ->
142 Long oldOffset = oldOffsets.get(tp);
143 Long newOffset = newOffsets.get(tp);
144 if (!oldOffset.equals(newOffset))
146 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
147 withProgress.add(tp);
150 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
154 /** Helper methods for setting up and running the tests */
156 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
158 offsetConsumer.assign(partitions());
159 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
160 offsetConsumer.unsubscribe();
163 List<TopicPartition> partitions()
167 .range(0, PARTITIONS)
168 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
169 .collect(Collectors.toList());
173 void send100Messages(Function<Long, Bytes> messageGenerator)
177 for (int partition = 0; partition < 10; partition++)
179 for (int key = 0; key < 10; key++)
181 Bytes value = messageGenerator.apply(++i);
183 ProducerRecord<String, Bytes> record =
184 new ProducerRecord<>(
187 Integer.toString(key%2),
190 kafkaProducer.send(record, (metadata, e) ->
192 if (metadata != null)
196 metadata.partition(),
204 "Exception for {}={}: {}",
218 testHandler = record -> {} ;
220 oldOffsets = new HashMap<>();
221 newOffsets = new HashMap<>();
223 doForCurrentOffsets((tp, offset) ->
225 oldOffsets.put(tp, offset - 1);
226 newOffsets.put(tp, offset - 1);
229 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
233 new TopicPartition(record.topic(), record.partition()),
235 testHandler.accept(record);
239 new EndlessConsumer<>(
241 properties.getClientId(),
242 properties.getTopic(),
244 captureOffsetAndExecuteTestHandler);
246 endlessConsumer.start();
254 endlessConsumer.stop();
258 log.info("Exception while stopping the consumer: {}", e.toString());
264 @Import(ApplicationConfiguration.class)
265 public static class Configuration
268 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
270 Properties props = new Properties();
271 props.put("bootstrap.servers", properties.getBootstrapServer());
272 props.put("linger.ms", 100);
273 props.put("key.serializer", StringSerializer.class.getName());
274 props.put("value.serializer", BytesSerializer.class.getName());
276 return new KafkaProducer<>(props);
280 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
282 Properties props = new Properties();
283 props.put("bootstrap.servers", properties.getBootstrapServer());
284 props.put("client.id", "OFFSET-CONSUMER");
285 props.put("group.id", properties.getGroupId());
286 props.put("key.deserializer", BytesDeserializer.class.getName());
287 props.put("value.deserializer", BytesDeserializer.class.getName());
289 return new KafkaConsumer<>(props);