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((partition, key, counter) ->
83 Bytes value = serialize(key, counter);
84 return new ProducerRecord<>(TOPIC, partition, key, value);
87 await("100 records received")
88 .atMost(Duration.ofSeconds(30))
89 .until(() -> receivedRecords.size() >= 100);
91 await("Offsets committed")
92 .atMost(Duration.ofSeconds(10))
95 checkSeenOffsetsForProgress();
96 compareToCommitedOffsets(newOffsets);
99 assertThatExceptionOfType(IllegalStateException.class)
100 .isThrownBy(() -> endlessConsumer.exitStatus())
101 .describedAs("Consumer should still be running");
106 void commitsOffsetOfErrorForReprocessingOnError()
108 send100Messages((partition, key, counter) ->
110 Bytes value = counter == 77
111 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
112 : serialize(key, counter);
113 return new ProducerRecord<>(TOPIC, partition, key, value);
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 public interface RecordGenerator<K, V>
198 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
201 void send100Messages(RecordGenerator recordGenerator)
205 for (int partition = 0; partition < 10; partition++)
207 for (int key = 0; key < 10; key++)
209 ProducerRecord<String, Bytes> record =
210 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
212 record.headers().add("__TypeId__", "message".getBytes());
213 kafkaProducer.send(record, (metadata, e) ->
215 if (metadata != null)
219 metadata.partition(),
227 "Exception for {}={}: {}",
237 Bytes serialize(String key, Long value)
239 ClientMessage message = new ClientMessage();
240 message.setClient(key);
241 message.setMessage(value.toString());
242 return new Bytes(valueSerializer.serialize(TOPIC, message));
249 testHandler = record -> {} ;
251 oldOffsets = new HashMap<>();
252 newOffsets = new HashMap<>();
253 receivedRecords = new HashSet<>();
255 doForCurrentOffsets((tp, offset) ->
257 oldOffsets.put(tp, offset - 1);
258 newOffsets.put(tp, offset - 1);
261 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsetAndExecuteTestHandler =
265 new TopicPartition(record.topic(), record.partition()),
267 receivedRecords.add(record);
268 testHandler.accept(record);
272 new EndlessConsumer<>(
274 properties.getClientId(),
275 properties.getTopic(),
277 captureOffsetAndExecuteTestHandler);
279 endlessConsumer.start();
287 endlessConsumer.stop();
291 log.info("Exception while stopping the consumer: {}", e.toString());
297 @Import(ApplicationConfiguration.class)
298 public static class Configuration
301 Serializer<ClientMessage> serializer()
303 return new JsonSerializer<>();
307 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
309 Properties props = new Properties();
310 props.put("bootstrap.servers", properties.getBootstrapServer());
311 props.put("linger.ms", 100);
312 props.put("key.serializer", StringSerializer.class.getName());
313 props.put("value.serializer", BytesSerializer.class.getName());
315 return new KafkaProducer<>(props);
319 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
321 Properties props = new Properties();
322 props.put("bootstrap.servers", properties.getBootstrapServer());
323 props.put("client.id", "OFFSET-CONSUMER");
324 props.put("group.id", properties.getGroupId());
325 props.put("key.deserializer", BytesDeserializer.class.getName());
326 props.put("value.deserializer", BytesDeserializer.class.getName());
328 return new KafkaConsumer<>(props);