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.WakeupException;
10 import org.apache.kafka.common.serialization.BytesSerializer;
11 import org.apache.kafka.common.serialization.LongSerializer;
12 import org.apache.kafka.common.serialization.StringSerializer;
13 import org.apache.kafka.common.utils.Bytes;
14 import org.junit.jupiter.api.MethodOrderer;
15 import org.junit.jupiter.api.Order;
16 import org.junit.jupiter.api.Test;
17 import org.junit.jupiter.api.TestMethodOrder;
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
20 import org.springframework.boot.test.context.TestConfiguration;
21 import org.springframework.context.annotation.Bean;
22 import org.springframework.context.annotation.Import;
23 import org.springframework.kafka.test.context.EmbeddedKafka;
24 import org.springframework.test.context.TestPropertySource;
25 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
28 import java.util.concurrent.ExecutorService;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.function.Function;
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.assertThat;
40 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
41 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
44 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
45 "consumer.topic=" + TOPIC })
46 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
48 class ApplicationTests
50 public static final String TOPIC = "FOO";
51 public static final int PARTITIONS = 10;
54 StringSerializer stringSerializer = new StringSerializer();
55 LongSerializer longSerializer = new LongSerializer();
58 KafkaProducer<String, Bytes> kafkaProducer;
60 KafkaConsumer<String, Long> kafkaConsumer;
62 ApplicationProperties properties;
64 ExecutorService executor;
68 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
69 void commitsCurrentOffsetsOnSuccess()
71 send100Messages(i -> new Bytes(longSerializer.serialize(TOPIC, i)));
73 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
74 Map<TopicPartition, Long> offsets = runEndlessConsumer(record ->
77 if (received.size() == 100)
78 throw new WakeupException();
86 void commitsNoOffsetsOnError()
88 send100Messages(counter ->
90 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
91 : new Bytes(longSerializer.serialize(TOPIC, counter)));
93 Map<TopicPartition, Long> oldOffsets = new HashMap<>();
94 doForCurrentOffsets((tp, offset) -> oldOffsets.put(tp, offset -1));
95 Map<TopicPartition, Long> newOffsets = runEndlessConsumer((record) -> {});
101 void send100Messages(Function<Long, Bytes> messageGenerator)
105 for (int partition = 0; partition < 10; partition++)
107 for (int key = 0; key < 10; key++)
109 Bytes value = messageGenerator.apply(++i);
111 ProducerRecord<String, Bytes> record =
112 new ProducerRecord<>(
115 Integer.toString(key%2),
118 kafkaProducer.send(record, (metadata, e) ->
120 if (metadata != null)
124 metadata.partition(),
132 "Exception for {}={}: {}",
142 Map<TopicPartition, Long> runEndlessConsumer(Consumer<ConsumerRecord<String, Long>> consumer)
144 Map<TopicPartition, Long> offsets = new HashMap<>();
145 doForCurrentOffsets((tp, offset) -> offsets.put(tp, offset -1));
146 Consumer<ConsumerRecord<String, Long>> captureOffset =
149 new TopicPartition(record.topic(), record.partition()),
151 EndlessConsumer<String, Long> endlessConsumer =
152 new EndlessConsumer<>(
154 properties.getClientId(),
155 properties.getTopic(),
157 captureOffset.andThen(consumer));
159 endlessConsumer.run();
164 List<TopicPartition> partitions()
168 .range(0, PARTITIONS)
169 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
170 .collect(Collectors.toList());
173 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
175 kafkaConsumer.assign(partitions());
176 partitions().forEach(tp -> consumer.accept(tp, kafkaConsumer.position(tp)));
177 kafkaConsumer.unsubscribe();
180 void check(Map<TopicPartition, Long> offsets)
182 doForCurrentOffsets((tp, offset) ->
184 Long expected = offsets.get(tp) + 1;
185 log.debug("Checking, if the offset for {} is {}", tp, expected);
186 assertThat(offset).isEqualTo(expected);
192 @Import(ApplicationConfiguration.class)
193 public static class Configuration
196 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
198 Properties props = new Properties();
199 props.put("bootstrap.servers", properties.getBootstrapServer());
200 props.put("linger.ms", 100);
201 props.put("key.serializer", StringSerializer.class.getName());
202 props.put("value.serializer", BytesSerializer.class.getName());
204 return new KafkaProducer<>(props);