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.listener.MessageListenerContainer;
22 import org.springframework.kafka.support.serializer.JsonSerializer;
23 import org.springframework.kafka.test.context.EmbeddedKafka;
24 import org.springframework.test.context.TestPropertySource;
25 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
27 import java.time.Duration;
29 import java.util.concurrent.ExecutionException;
30 import java.util.function.BiConsumer;
31 import java.util.function.BiFunction;
32 import java.util.function.Consumer;
33 import java.util.stream.Collectors;
34 import java.util.stream.IntStream;
36 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
37 import static de.juplo.kafka.ApplicationTests.TOPIC;
38 import static org.assertj.core.api.Assertions.*;
39 import static org.awaitility.Awaitility.*;
43 initializers = ConfigDataApplicationContextInitializer.class,
45 EndlessConsumer.class,
46 KafkaAutoConfiguration.class,
47 ApplicationTests.Configuration.class })
48 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
51 "spring.kafka.consumer.bootstrap-servers=${spring.embedded.kafka.brokers}",
52 "spring.kafka.producer.bootstrap-servers=${spring.embedded.kafka.brokers}",
53 "consumer.topic=" + TOPIC })
54 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
56 class ApplicationTests
58 public static final String TOPIC = "FOO";
59 public static final int PARTITIONS = 10;
62 StringSerializer stringSerializer = new StringSerializer();
65 Serializer valueSerializer;
67 KafkaProducer<String, Bytes> kafkaProducer;
69 org.apache.kafka.clients.consumer.Consumer<String, ClientMessage> kafkaConsumer;
71 KafkaConsumer<Bytes, Bytes> offsetConsumer;
73 ApplicationProperties applicationProperties;
75 KafkaProperties kafkaProperties;
77 EndlessConsumer endlessConsumer;
79 RecordHandler recordHandler;
81 Map<TopicPartition, Long> oldOffsets;
82 Map<TopicPartition, Long> newOffsets;
83 Set<ConsumerRecord<String, ClientMessage>> receivedRecords;
89 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
90 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
92 send100Messages((key, counter) -> serialize(key, counter));
94 await("100 records received")
95 .atMost(Duration.ofSeconds(30))
96 .until(() -> receivedRecords.size() == 100);
98 await("Offsets committed")
99 .atMost(Duration.ofSeconds(10))
102 checkSeenOffsetsForProgress();
103 compareToCommitedOffsets(newOffsets);
106 assertThat(endlessConsumer.isRunning())
107 .describedAs("Consumer should still be running")
113 void commitsCurrentOffsetsOnError()
115 send100Messages((key, counter) ->
117 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
118 : serialize(key, counter));
120 await("99 records received")
121 .atMost(Duration.ofSeconds(30))
122 .until(() -> receivedRecords.size() == 99);
124 await("Offsets committed")
125 .atMost(Duration.ofSeconds(10))
129 // Funktioniert nur, weil nach der Nachrichten, die den
130 // Deserialisierungs-Fehler auslöst noch valide Nachrichten
133 // Der MessageHandler sieht den Offset der Fehlerhaften
135 checkSeenOffsetsForProgress();
136 compareToCommitedOffsets(newOffsets);
139 assertThat(endlessConsumer.isRunning())
140 .describedAs("Consumer should still be running")
145 /** Helper methods for the verification of expectations */
147 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
149 doForCurrentOffsets((tp, offset) ->
151 Long expected = offsetsToCheck.get(tp) + 1;
152 log.debug("TEST: Comparing the expected offset of {} for {} to {}", expected, tp, offset);
154 .describedAs("Committed offset corresponds to the offset of the consumer")
155 .isEqualTo(expected);
159 void checkSeenOffsetsForProgress()
161 // Be sure, that some messages were consumed...!
162 Set<TopicPartition> withProgress = new HashSet<>();
163 partitions().forEach(tp ->
165 Long oldOffset = oldOffsets.get(tp);
166 Long newOffset = newOffsets.get(tp);
167 if (!oldOffset.equals(newOffset))
169 log.debug("TEST: Progress for {}: {} -> {}", tp, oldOffset, newOffset);
170 withProgress.add(tp);
173 log.debug("TEST: Offsets with progress: {}", withProgress);
174 assertThat(withProgress)
175 .describedAs("Some offsets must have changed, compared to the old offset-positions")
180 /** Helper methods for setting up and running the tests */
182 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
184 offsetConsumer.assign(partitions());
185 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
186 offsetConsumer.unsubscribe();
189 List<TopicPartition> partitions()
193 .range(0, PARTITIONS)
194 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
195 .collect(Collectors.toList());
199 void send100Messages(BiFunction<Integer, Long, Bytes> messageGenerator)
203 for (int partition = 0; partition < 10; partition++)
205 for (int key = 0; key < 10; key++)
207 Bytes value = messageGenerator.apply(key, ++i);
209 ProducerRecord<String, Bytes> record =
210 new ProducerRecord<>(
213 Integer.toString(key%2),
216 record.headers().add("__TypeId__", "message".getBytes());
217 kafkaProducer.send(record, (metadata, e) ->
219 if (metadata != null)
222 "TEST: Sending partition={}, offset={} - {}={}",
223 metadata.partition(),
231 "TEST: Exception for {}={}: {}",
241 Bytes serialize(Integer key, Long value)
243 ClientMessage message = new ClientMessage();
244 message.setClient(key.toString());
245 message.setMessage(value.toString());
246 return new Bytes(valueSerializer.serialize(TOPIC, message));
253 recordHandler.testHandler = (record) -> {};
255 oldOffsets = new HashMap<>();
256 newOffsets = new HashMap<>();
257 receivedRecords = new HashSet<>();
259 doForCurrentOffsets((tp, offset) ->
261 oldOffsets.put(tp, offset - 1);
262 newOffsets.put(tp, offset - 1);
265 recordHandler.captureOffsets =
268 receivedRecords.add(record);
269 log.debug("TEST: Processing record #{}: {}", receivedRecords.size(), record.value());
271 new TopicPartition(record.topic(), record.partition()),
275 endlessConsumer.start();
283 endlessConsumer.stop();
287 log.info("TEST: Exception while stopping the consumer: {}", e.toString());
291 public static class RecordHandler implements Consumer<ConsumerRecord<String, ClientMessage>>
293 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsets;
294 Consumer<ConsumerRecord<String, ClientMessage>> testHandler;
298 public void accept(ConsumerRecord<String, ClientMessage> record)
301 .andThen(testHandler)
307 @Import(ApplicationConfiguration.class)
308 public static class Configuration
312 public Consumer<ConsumerRecord<String, ClientMessage>> testHandler()
314 return new RecordHandler();
318 Serializer<ClientMessage> serializer()
320 return new JsonSerializer<>();
324 KafkaProducer<String, Bytes> kafkaProducer(KafkaProperties properties)
326 Properties props = new Properties();
327 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
328 props.put("linger.ms", 100);
329 props.put("key.serializer", StringSerializer.class.getName());
330 props.put("value.serializer", BytesSerializer.class.getName());
332 return new KafkaProducer<>(props);
336 KafkaConsumer<Bytes, Bytes> offsetConsumer(KafkaProperties properties)
338 Properties props = new Properties();
339 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
340 props.put("client.id", "OFFSET-CONSUMER");
341 props.put("group.id", properties.getConsumer().getGroupId());
342 props.put("key.deserializer", BytesDeserializer.class.getName());
343 props.put("value.deserializer", BytesDeserializer.class.getName());
345 return new KafkaConsumer<>(props);