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.context.annotation.Primary;
21 import org.springframework.kafka.support.serializer.JsonSerializer;
22 import org.springframework.kafka.test.context.EmbeddedKafka;
23 import org.springframework.test.context.TestPropertySource;
24 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
26 import java.time.Duration;
28 import java.util.concurrent.ExecutionException;
29 import java.util.function.BiConsumer;
30 import java.util.function.BiFunction;
31 import java.util.function.Consumer;
32 import java.util.stream.Collectors;
33 import java.util.stream.IntStream;
35 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
36 import static de.juplo.kafka.ApplicationTests.TOPIC;
37 import static org.assertj.core.api.Assertions.*;
38 import static org.awaitility.Awaitility.*;
42 initializers = ConfigDataApplicationContextInitializer.class,
44 EndlessConsumer.class,
45 KafkaAutoConfiguration.class,
46 ApplicationTests.Configuration.class })
47 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
50 "spring.kafka.consumer.bootstrap-servers=${spring.embedded.kafka.brokers}",
51 "consumer.topic=" + TOPIC })
52 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
54 class ApplicationTests
56 public static final String TOPIC = "FOO";
57 public static final int PARTITIONS = 10;
60 StringSerializer stringSerializer = new StringSerializer();
63 Serializer valueSerializer;
65 KafkaProducer<String, Bytes> kafkaProducer;
67 org.apache.kafka.clients.consumer.Consumer<String, ClientMessage> kafkaConsumer;
69 KafkaConsumer<Bytes, Bytes> offsetConsumer;
71 ApplicationProperties applicationProperties;
73 KafkaProperties kafkaProperties;
75 EndlessConsumer endlessConsumer;
77 RecordHandler recordHandler;
79 Map<TopicPartition, Long> oldOffsets;
80 Map<TopicPartition, Long> newOffsets;
81 Set<ConsumerRecord<String, ClientMessage>> receivedRecords;
87 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
88 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
90 send100Messages((key, counter) -> serialize(key, counter));
92 await("100 records received")
93 .atMost(Duration.ofSeconds(30))
94 .until(() -> receivedRecords.size() >= 100);
96 await("Offsets committed")
97 .atMost(Duration.ofSeconds(10))
100 checkSeenOffsetsForProgress();
101 compareToCommitedOffsets(newOffsets);
104 assertThatExceptionOfType(IllegalStateException.class)
105 .isThrownBy(() -> endlessConsumer.exitStatus())
106 .describedAs("Consumer should still be running");
111 void commitsOffsetOfErrorForReprocessingOnError()
113 send100Messages((key, counter) ->
115 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
116 : serialize(key, counter));
118 await("Consumer failed")
119 .atMost(Duration.ofSeconds(30))
120 .untilAsserted(() -> checkSeenOffsetsForProgress());
122 compareToCommitedOffsets(newOffsets);
123 assertThat(receivedRecords.size())
124 .describedAs("Received not all sent events")
127 assertThatNoException()
128 .describedAs("Consumer should not be running")
129 .isThrownBy(() -> endlessConsumer.exitStatus());
130 assertThat(endlessConsumer.exitStatus())
131 .containsInstanceOf(RecordDeserializationException.class)
132 .describedAs("Consumer should have exited abnormally");
136 /** Helper methods for the verification of expectations */
138 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
140 doForCurrentOffsets((tp, offset) ->
142 Long expected = offsetsToCheck.get(tp) + 1;
143 log.debug("Checking, if the offset for {} is {}", tp, expected);
145 .describedAs("Committed offset corresponds to the offset of the consumer")
146 .isEqualTo(expected);
150 void checkSeenOffsetsForProgress()
152 // Be sure, that some messages were consumed...!
153 Set<TopicPartition> withProgress = new HashSet<>();
154 partitions().forEach(tp ->
156 Long oldOffset = oldOffsets.get(tp);
157 Long newOffset = newOffsets.get(tp);
158 if (!oldOffset.equals(newOffset))
160 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
161 withProgress.add(tp);
164 assertThat(withProgress)
165 .describedAs("Some offsets must have changed, compared to the old offset-positions")
170 /** Helper methods for setting up and running the tests */
172 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
174 offsetConsumer.assign(partitions());
175 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
176 offsetConsumer.unsubscribe();
179 List<TopicPartition> partitions()
183 .range(0, PARTITIONS)
184 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
185 .collect(Collectors.toList());
189 void send100Messages(BiFunction<Integer, Long, Bytes> messageGenerator)
193 for (int partition = 0; partition < 10; partition++)
195 for (int key = 0; key < 10; key++)
197 Bytes value = messageGenerator.apply(key, ++i);
199 ProducerRecord<String, Bytes> record =
200 new ProducerRecord<>(
203 Integer.toString(key%2),
206 record.headers().add("__TypeId__", "message".getBytes());
207 kafkaProducer.send(record, (metadata, e) ->
209 if (metadata != null)
213 metadata.partition(),
221 "Exception for {}={}: {}",
231 Bytes serialize(Integer key, Long value)
233 ClientMessage message = new ClientMessage();
234 message.setClient(key.toString());
235 message.setMessage(value.toString());
236 return new Bytes(valueSerializer.serialize(TOPIC, message));
243 recordHandler.testHandler = (record) -> {};
245 oldOffsets = new HashMap<>();
246 newOffsets = new HashMap<>();
247 receivedRecords = new HashSet<>();
249 doForCurrentOffsets((tp, offset) ->
251 oldOffsets.put(tp, offset - 1);
252 newOffsets.put(tp, offset - 1);
255 recordHandler.captureOffsets =
258 receivedRecords.add(record);
260 new TopicPartition(record.topic(), record.partition()),
264 endlessConsumer.start();
272 endlessConsumer.stop();
276 log.info("Exception while stopping the consumer: {}", e.toString());
280 public static class RecordHandler implements Consumer<ConsumerRecord<String, ClientMessage>>
282 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsets;
283 Consumer<ConsumerRecord<String, ClientMessage>> testHandler;
287 public void accept(ConsumerRecord<String, ClientMessage> record)
290 .andThen(testHandler)
296 @Import(ApplicationConfiguration.class)
297 public static class Configuration
301 public Consumer<ConsumerRecord<String, ClientMessage>> testHandler()
303 return new RecordHandler();
307 Serializer<ClientMessage> serializer()
309 return new JsonSerializer<>();
313 KafkaProducer<String, Bytes> kafkaProducer(KafkaProperties properties)
315 Properties props = new Properties();
316 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
317 props.put("linger.ms", 100);
318 props.put("key.serializer", StringSerializer.class.getName());
319 props.put("value.serializer", BytesSerializer.class.getName());
321 return new KafkaProducer<>(props);
325 KafkaConsumer<Bytes, Bytes> offsetConsumer(KafkaProperties properties)
327 Properties props = new Properties();
328 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
329 props.put("client.id", "OFFSET-CONSUMER");
330 props.put("group.id", properties.getConsumer().getGroupId());
331 props.put("key.deserializer", BytesDeserializer.class.getName());
332 props.put("value.deserializer", BytesDeserializer.class.getName());
334 return new KafkaConsumer<>(props);