Springify: Kernfunktion von EndlessConsumer über Spring-Kafka
[demos/kafka/training] / src / test / java / de / juplo / kafka / ApplicationTests.java
1 package de.juplo.kafka;
2
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.serialization.BytesDeserializer;
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.*;
15 import org.springframework.beans.factory.annotation.Autowired;
16 import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
17 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
18 import org.springframework.boot.test.context.TestConfiguration;
19 import org.springframework.context.annotation.Bean;
20 import org.springframework.context.annotation.Import;
21 import org.springframework.context.annotation.Primary;
22 import org.springframework.kafka.test.context.EmbeddedKafka;
23 import org.springframework.test.context.TestPropertySource;
24 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
25
26 import java.time.Duration;
27 import java.util.*;
28 import java.util.concurrent.ExecutionException;
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;
34
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;
38 import static org.awaitility.Awaitility.*;
39
40
41 @SpringJUnitConfig(
42                 initializers = ConfigDataApplicationContextInitializer.class,
43     classes = {
44                                 EndlessConsumer.class,
45                                 KafkaAutoConfiguration.class,
46                                 ApplicationTests.Configuration.class })
47 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
48 @TestPropertySource(
49                 properties = {
50                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
51                                 "consumer.topic=" + TOPIC })
52 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
53 @Slf4j
54 class ApplicationTests
55 {
56         public static final String TOPIC = "FOO";
57         public static final int PARTITIONS = 10;
58
59
60         StringSerializer stringSerializer = new StringSerializer();
61         LongSerializer longSerializer = new LongSerializer();
62
63         @Autowired
64         KafkaProducer<String, Bytes> kafkaProducer;
65         @Autowired
66         KafkaConsumer<Bytes, Bytes> offsetConsumer;
67         @Autowired
68         ApplicationProperties properties;
69         @Autowired
70         RecordHandler recordHandler;
71
72         Map<TopicPartition, Long> oldOffsets;
73         Map<TopicPartition, Long> newOffsets;
74
75
76         /** Tests methods */
77
78         @Test
79         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
80         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
81         {
82                 send100Messages(i ->  new Bytes(longSerializer.serialize(TOPIC, i)));
83
84                 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
85                 recordHandler.testHandler = record -> received.add(record);
86
87                 await("100 records received")
88                                 .atMost(Duration.ofSeconds(30))
89                                 .until(() -> received.size() >= 100);
90
91                 await("Offsets committed")
92                                 .atMost(Duration.ofSeconds(10))
93                                 .untilAsserted(() ->
94                                 {
95                                         checkSeenOffsetsForProgress();
96                                         compareToCommitedOffsets(newOffsets);
97                                 });
98         }
99
100         @Test
101         @Order(2)
102         void commitsOffsetOfErrorForReprocessingOnError()
103         {
104                 send100Messages(counter ->
105                                 counter == 77
106                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
107                                                 : new Bytes(longSerializer.serialize(TOPIC, counter)));
108
109                 await("Consumer failed")
110                                 .atMost(Duration.ofSeconds(30))
111                                 .untilAsserted(() -> checkSeenOffsetsForProgress());
112
113                 compareToCommitedOffsets(newOffsets);
114         }
115
116
117         /** Helper methods for the verification of expectations */
118
119         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
120         {
121                 doForCurrentOffsets((tp, offset) ->
122                 {
123                         Long expected = offsetsToCheck.get(tp) + 1;
124                         log.debug("Checking, if the offset for {} is {}", tp, expected);
125                         assertThat(offset).isEqualTo(expected);
126                 });
127         }
128
129         void checkSeenOffsetsForProgress()
130         {
131                 // Be sure, that some messages were consumed...!
132                 Set<TopicPartition> withProgress = new HashSet<>();
133                 partitions().forEach(tp ->
134                 {
135                         Long oldOffset = oldOffsets.get(tp);
136                         Long newOffset = newOffsets.get(tp);
137                         if (!oldOffset.equals(newOffset))
138                         {
139                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
140                                 withProgress.add(tp);
141                         }
142                 });
143                 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
144         }
145
146
147         /** Helper methods for setting up and running the tests */
148
149         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
150         {
151                 offsetConsumer.assign(partitions());
152                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
153                 offsetConsumer.unsubscribe();
154         }
155
156         List<TopicPartition> partitions()
157         {
158                 return
159                                 IntStream
160                                                 .range(0, PARTITIONS)
161                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
162                                                 .collect(Collectors.toList());
163         }
164
165
166         void send100Messages(Function<Long, Bytes> messageGenerator)
167         {
168                 long i = 0;
169
170                 for (int partition = 0; partition < 10; partition++)
171                 {
172                         for (int key = 0; key < 10; key++)
173                         {
174                                 Bytes value = messageGenerator.apply(++i);
175
176                                 ProducerRecord<String, Bytes> record =
177                                                 new ProducerRecord<>(
178                                                                 TOPIC,
179                                                                 partition,
180                                                                 Integer.toString(key%2),
181                                                                 value);
182
183                                 kafkaProducer.send(record, (metadata, e) ->
184                                 {
185                                         if (metadata != null)
186                                         {
187                                                 log.debug(
188                                                                 "{}|{} - {}={}",
189                                                                 metadata.partition(),
190                                                                 metadata.offset(),
191                                                                 record.key(),
192                                                                 record.value());
193                                         }
194                                         else
195                                         {
196                                                 log.warn(
197                                                                 "Exception for {}={}: {}",
198                                                                 record.key(),
199                                                                 record.value(),
200                                                                 e.toString());
201                                         }
202                                 });
203                         }
204                 }
205         }
206
207
208         @BeforeEach
209         public void init()
210         {
211                 recordHandler.testHandler = (record) -> {};
212
213                 oldOffsets = new HashMap<>();
214                 newOffsets = new HashMap<>();
215
216                 doForCurrentOffsets((tp, offset) ->
217                 {
218                         oldOffsets.put(tp, offset - 1);
219                         newOffsets.put(tp, offset - 1);
220                 });
221
222                 recordHandler.captureOffsets =
223                                 record ->
224                                         newOffsets.put(
225                                                         new TopicPartition(record.topic(), record.partition()),
226                                                         record.offset());
227         }
228
229
230         public static class RecordHandler implements Consumer<ConsumerRecord<String, Long>>
231         {
232                 Consumer<ConsumerRecord<String, Long>> captureOffsets;
233                 Consumer<ConsumerRecord<String, Long>> testHandler;
234
235
236                 @Override
237                 public void accept(ConsumerRecord<String, Long> record)
238                 {
239                         captureOffsets
240                                         .andThen(testHandler)
241                                         .accept(record);
242                 }
243         }
244
245         @TestConfiguration
246         @Import(ApplicationConfiguration.class)
247         public static class Configuration
248         {
249                 @Primary
250                 @Bean
251                 public Consumer<ConsumerRecord<String, Long>> testHandler()
252                 {
253                         return new RecordHandler();
254                 }
255
256                 @Bean
257                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
258                 {
259                         Properties props = new Properties();
260                         props.put("bootstrap.servers", properties.getBootstrapServer());
261                         props.put("linger.ms", 100);
262                         props.put("key.serializer", StringSerializer.class.getName());
263                         props.put("value.serializer", BytesSerializer.class.getName());
264
265                         return new KafkaProducer<>(props);
266                 }
267
268                 @Bean
269                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
270                 {
271                         Properties props = new Properties();
272                         props.put("bootstrap.servers", properties.getBootstrapServer());
273                         props.put("client.id", "OFFSET-CONSUMER");
274                         props.put("group.id", properties.getGroupId());
275                         props.put("key.deserializer", BytesDeserializer.class.getName());
276                         props.put("value.deserializer", BytesDeserializer.class.getName());
277
278                         return new KafkaConsumer<>(props);
279                 }
280         }
281 }