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.test.context.ConfigDataApplicationContextInitializer;
16 import org.springframework.boot.test.context.TestConfiguration;
17 import org.springframework.context.annotation.Bean;
18 import org.springframework.context.annotation.Import;
19 import org.springframework.context.annotation.Primary;
20 import org.springframework.kafka.support.serializer.JsonSerializer;
21 import org.springframework.kafka.test.context.EmbeddedKafka;
22 import org.springframework.test.context.TestPropertySource;
23 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
25 import java.time.Duration;
27 import java.util.concurrent.ExecutionException;
28 import java.util.function.BiConsumer;
29 import java.util.function.BiFunction;
30 import java.util.function.Consumer;
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 EndlessConsumer.class,
44 KafkaAutoConfiguration.class,
45 ApplicationTests.Configuration.class })
46 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
49 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
50 "consumer.topic=" + TOPIC })
51 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
53 class ApplicationTests
55 public static final String TOPIC = "FOO";
56 public static final int PARTITIONS = 10;
59 StringSerializer stringSerializer = new StringSerializer();
62 Serializer valueSerializer;
64 KafkaProducer<String, Bytes> kafkaProducer;
66 KafkaConsumer<String, ClientMessage> kafkaConsumer;
68 KafkaConsumer<Bytes, Bytes> offsetConsumer;
70 ApplicationProperties properties;
72 EndlessConsumer endlessConsumer;
74 RecordHandler recordHandler;
76 Map<TopicPartition, Long> oldOffsets;
77 Map<TopicPartition, Long> newOffsets;
78 Set<ConsumerRecord<String, ClientMessage>> receivedRecords;
84 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
85 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
87 send100Messages((key, counter) -> serialize(key, counter));
89 await("100 records received")
90 .atMost(Duration.ofSeconds(30))
91 .until(() -> receivedRecords.size() >= 100);
93 await("Offsets committed")
94 .atMost(Duration.ofSeconds(10))
97 checkSeenOffsetsForProgress();
98 compareToCommitedOffsets(newOffsets);
101 assertThatExceptionOfType(IllegalStateException.class)
102 .isThrownBy(() -> endlessConsumer.exitStatus())
103 .describedAs("Consumer should still be running");
108 void commitsOffsetOfErrorForReprocessingOnError()
110 send100Messages((key, counter) ->
112 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
113 : serialize(key, counter));
115 await("Consumer failed")
116 .atMost(Duration.ofSeconds(30))
117 .untilAsserted(() -> checkSeenOffsetsForProgress());
119 compareToCommitedOffsets(newOffsets);
120 assertThat(receivedRecords.size())
121 .describedAs("Received not all sent events")
124 assertThatNoException()
125 .describedAs("Consumer should not be running")
126 .isThrownBy(() -> endlessConsumer.exitStatus());
127 assertThat(endlessConsumer.exitStatus())
128 .containsInstanceOf(RecordDeserializationException.class)
129 .describedAs("Consumer should have exited abnormally");
133 /** Helper methods for the verification of expectations */
135 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
137 doForCurrentOffsets((tp, offset) ->
139 Long expected = offsetsToCheck.get(tp) + 1;
140 log.debug("Checking, if the offset for {} is {}", tp, expected);
142 .describedAs("Committed offset corresponds to the offset of the consumer")
143 .isEqualTo(expected);
147 void checkSeenOffsetsForProgress()
149 // Be sure, that some messages were consumed...!
150 Set<TopicPartition> withProgress = new HashSet<>();
151 partitions().forEach(tp ->
153 Long oldOffset = oldOffsets.get(tp);
154 Long newOffset = newOffsets.get(tp);
155 if (!oldOffset.equals(newOffset))
157 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
158 withProgress.add(tp);
161 assertThat(withProgress)
162 .describedAs("Some offsets must have changed, compared to the old offset-positions")
167 /** Helper methods for setting up and running the tests */
169 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
171 offsetConsumer.assign(partitions());
172 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
173 offsetConsumer.unsubscribe();
176 List<TopicPartition> partitions()
180 .range(0, PARTITIONS)
181 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
182 .collect(Collectors.toList());
186 void send100Messages(BiFunction<Integer, Long, Bytes> messageGenerator)
190 for (int partition = 0; partition < 10; partition++)
192 for (int key = 0; key < 10; key++)
194 Bytes value = messageGenerator.apply(key, ++i);
196 ProducerRecord<String, Bytes> record =
197 new ProducerRecord<>(
200 Integer.toString(key%2),
203 record.headers().add("__TypeId__", "message".getBytes());
204 kafkaProducer.send(record, (metadata, e) ->
206 if (metadata != null)
210 metadata.partition(),
218 "Exception for {}={}: {}",
228 Bytes serialize(Integer key, Long value)
230 ClientMessage message = new ClientMessage();
231 message.setClient(key.toString());
232 message.setMessage(value.toString());
233 return new Bytes(valueSerializer.serialize(TOPIC, message));
240 recordHandler.testHandler = (record) -> {};
242 oldOffsets = new HashMap<>();
243 newOffsets = new HashMap<>();
244 receivedRecords = new HashSet<>();
246 doForCurrentOffsets((tp, offset) ->
248 oldOffsets.put(tp, offset - 1);
249 newOffsets.put(tp, offset - 1);
252 recordHandler.captureOffsets =
255 receivedRecords.add(record);
257 new TopicPartition(record.topic(), record.partition()),
261 endlessConsumer.start();
269 endlessConsumer.stop();
273 log.info("Exception while stopping the consumer: {}", e.toString());
277 public static class RecordHandler implements Consumer<ConsumerRecord<String, ClientMessage>>
279 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsets;
280 Consumer<ConsumerRecord<String, ClientMessage>> testHandler;
284 public void accept(ConsumerRecord<String, ClientMessage> record)
287 .andThen(testHandler)
293 @Import(ApplicationConfiguration.class)
294 public static class Configuration
298 public Consumer<ConsumerRecord<String, ClientMessage>> testHandler()
300 return new RecordHandler();
304 Serializer<ClientMessage> serializer()
306 return new JsonSerializer<>();
310 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
312 Properties props = new Properties();
313 props.put("bootstrap.servers", properties.getBootstrapServer());
314 props.put("linger.ms", 100);
315 props.put("key.serializer", StringSerializer.class.getName());
316 props.put("value.serializer", BytesSerializer.class.getName());
318 return new KafkaProducer<>(props);
322 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
324 Properties props = new Properties();
325 props.put("bootstrap.servers", properties.getBootstrapServer());
326 props.put("client.id", "OFFSET-CONSUMER");
327 props.put("group.id", properties.getGroupId());
328 props.put("key.deserializer", BytesDeserializer.class.getName());
329 props.put("value.deserializer", BytesDeserializer.class.getName());
331 return new KafkaConsumer<>(props);