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.support.serializer.JsonSerializer;
19 import org.springframework.kafka.test.context.EmbeddedKafka;
20 import org.springframework.test.context.TestPropertySource;
21 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
23 import java.time.Duration;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.ExecutorService;
27 import java.util.function.BiConsumer;
28 import java.util.function.BiFunction;
29 import java.util.function.Consumer;
30 import java.util.stream.Collectors;
31 import java.util.stream.IntStream;
33 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
34 import static de.juplo.kafka.ApplicationTests.TOPIC;
35 import static org.assertj.core.api.Assertions.*;
36 import static org.awaitility.Awaitility.*;
39 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
40 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
43 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
44 "consumer.topic=" + TOPIC })
45 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
47 class ApplicationTests
49 public static final String TOPIC = "FOO";
50 public static final int PARTITIONS = 10;
53 StringSerializer stringSerializer = new StringSerializer();
56 Serializer valueSerializer;
58 KafkaProducer<String, Bytes> kafkaProducer;
60 KafkaConsumer<String, ClientMessage> kafkaConsumer;
62 KafkaConsumer<Bytes, Bytes> offsetConsumer;
64 ApplicationProperties properties;
66 ExecutorService executor;
68 Consumer<ConsumerRecord<String, ClientMessage>> testHandler;
69 EndlessConsumer<String, ClientMessage> endlessConsumer;
70 Map<TopicPartition, Long> oldOffsets;
71 Map<TopicPartition, Long> newOffsets;
72 Set<ConsumerRecord<String, ClientMessage>> receivedRecords;
78 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
79 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
81 send100Messages((key, counter) -> serialize(key, counter));
83 await("100 records received")
84 .atMost(Duration.ofSeconds(30))
85 .until(() -> receivedRecords.size() >= 100);
87 await("Offsets committed")
88 .atMost(Duration.ofSeconds(10))
91 checkSeenOffsetsForProgress();
92 compareToCommitedOffsets(newOffsets);
95 assertThatExceptionOfType(IllegalStateException.class)
96 .isThrownBy(() -> endlessConsumer.exitStatus())
97 .describedAs("Consumer should still be running");
102 void commitsOffsetOfErrorForReprocessingOnError()
104 send100Messages((key, counter) ->
106 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
107 : serialize(key, counter));
109 await("Consumer failed")
110 .atMost(Duration.ofSeconds(30))
111 .until(() -> !endlessConsumer.running());
113 checkSeenOffsetsForProgress();
114 compareToCommitedOffsets(newOffsets);
116 endlessConsumer.start();
117 await("Consumer failed")
118 .atMost(Duration.ofSeconds(30))
119 .until(() -> !endlessConsumer.running());
121 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 .describedAs("Consumer should have exited abnormally")
132 .containsInstanceOf(RecordDeserializationException.class);
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 kafkaProducer.send(record, (metadata, e) ->
208 if (metadata != null)
212 metadata.partition(),
220 "Exception for {}={}: {}",
230 Bytes serialize(Integer key, Long value)
232 ClientMessage message = new ClientMessage();
233 message.setClient(key.toString());
234 message.setMessage(value.toString());
235 return new Bytes(valueSerializer.serialize(TOPIC, message));
242 testHandler = record -> {} ;
244 oldOffsets = new HashMap<>();
245 newOffsets = new HashMap<>();
246 receivedRecords = new HashSet<>();
248 doForCurrentOffsets((tp, offset) ->
250 oldOffsets.put(tp, offset - 1);
251 newOffsets.put(tp, offset - 1);
254 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsetAndExecuteTestHandler =
258 new TopicPartition(record.topic(), record.partition()),
260 receivedRecords.add(record);
261 testHandler.accept(record);
265 new EndlessConsumer<>(
267 properties.getClientId(),
268 properties.getTopic(),
270 captureOffsetAndExecuteTestHandler);
272 endlessConsumer.start();
280 endlessConsumer.stop();
284 log.info("Exception while stopping the consumer: {}", e.toString());
290 @Import(ApplicationConfiguration.class)
291 public static class Configuration
294 Serializer<ClientMessage> serializer()
296 return new JsonSerializer<>();
300 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
302 Properties props = new Properties();
303 props.put("bootstrap.servers", properties.getBootstrapServer());
304 props.put("linger.ms", 100);
305 props.put("key.serializer", StringSerializer.class.getName());
306 props.put("value.serializer", BytesSerializer.class.getName());
308 return new KafkaProducer<>(props);
312 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
314 Properties props = new Properties();
315 props.put("bootstrap.servers", properties.getBootstrapServer());
316 props.put("client.id", "OFFSET-CONSUMER");
317 props.put("group.id", properties.getGroupId());
318 props.put("key.deserializer", BytesDeserializer.class.getName());
319 props.put("value.deserializer", BytesDeserializer.class.getName());
321 return new KafkaConsumer<>(props);