Springify: ROT - Merge des verschärften Tests aus der Vanilla-Version
[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         EndlessConsumer endlessConsumer;
71         @Autowired
72         RecordHandler recordHandler;
73
74         Map<TopicPartition, Long> oldOffsets;
75         Map<TopicPartition, Long> newOffsets;
76         Set<ConsumerRecord<String, Long>> receivedRecords;
77
78
79         /** Tests methods */
80
81         @Test
82         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
83         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
84         {
85                 send100Messages(i ->  new Bytes(longSerializer.serialize(TOPIC, i)));
86
87                 await("100 records received")
88                                 .atMost(Duration.ofSeconds(30))
89                                 .until(() -> receivedRecords.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                 assertThat(receivedRecords.size())
115                                 .describedAs("Received not all sent events")
116                                 .isLessThan(100);
117         }
118
119
120         /** Helper methods for the verification of expectations */
121
122         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
123         {
124                 doForCurrentOffsets((tp, offset) ->
125                 {
126                         Long expected = offsetsToCheck.get(tp) + 1;
127                         log.debug("Checking, if the offset for {} is {}", tp, expected);
128                         assertThat(offset)
129                                         .describedAs("Committed offset corresponds to the offset of the consumer")
130                                         .isEqualTo(expected);
131                 });
132         }
133
134         void checkSeenOffsetsForProgress()
135         {
136                 // Be sure, that some messages were consumed...!
137                 Set<TopicPartition> withProgress = new HashSet<>();
138                 partitions().forEach(tp ->
139                 {
140                         Long oldOffset = oldOffsets.get(tp);
141                         Long newOffset = newOffsets.get(tp);
142                         if (!oldOffset.equals(newOffset))
143                         {
144                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
145                                 withProgress.add(tp);
146                         }
147                 });
148                 assertThat(withProgress)
149                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
150                                 .isNotEmpty();
151         }
152
153
154         /** Helper methods for setting up and running the tests */
155
156         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
157         {
158                 offsetConsumer.assign(partitions());
159                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
160                 offsetConsumer.unsubscribe();
161         }
162
163         List<TopicPartition> partitions()
164         {
165                 return
166                                 IntStream
167                                                 .range(0, PARTITIONS)
168                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
169                                                 .collect(Collectors.toList());
170         }
171
172
173         void send100Messages(Function<Long, Bytes> messageGenerator)
174         {
175                 long i = 0;
176
177                 for (int partition = 0; partition < 10; partition++)
178                 {
179                         for (int key = 0; key < 10; key++)
180                         {
181                                 Bytes value = messageGenerator.apply(++i);
182
183                                 ProducerRecord<String, Bytes> record =
184                                                 new ProducerRecord<>(
185                                                                 TOPIC,
186                                                                 partition,
187                                                                 Integer.toString(key%2),
188                                                                 value);
189
190                                 kafkaProducer.send(record, (metadata, e) ->
191                                 {
192                                         if (metadata != null)
193                                         {
194                                                 log.debug(
195                                                                 "{}|{} - {}={}",
196                                                                 metadata.partition(),
197                                                                 metadata.offset(),
198                                                                 record.key(),
199                                                                 record.value());
200                                         }
201                                         else
202                                         {
203                                                 log.warn(
204                                                                 "Exception for {}={}: {}",
205                                                                 record.key(),
206                                                                 record.value(),
207                                                                 e.toString());
208                                         }
209                                 });
210                         }
211                 }
212         }
213
214
215         @BeforeEach
216         public void init()
217         {
218                 recordHandler.testHandler = (record) -> {};
219
220                 oldOffsets = new HashMap<>();
221                 newOffsets = new HashMap<>();
222                 receivedRecords = new HashSet<>();
223
224                 doForCurrentOffsets((tp, offset) ->
225                 {
226                         oldOffsets.put(tp, offset - 1);
227                         newOffsets.put(tp, offset - 1);
228                 });
229
230                 recordHandler.captureOffsets =
231                                 record ->
232                                 {
233                                         receivedRecords.add(record);
234                                         newOffsets.put(
235                                                         new TopicPartition(record.topic(), record.partition()),
236                                                         record.offset());
237                                 };
238
239                 endlessConsumer.start();
240         }
241
242         @AfterEach
243         public void deinit()
244         {
245                 try
246                 {
247                         endlessConsumer.stop();
248                 }
249                 catch (Exception e)
250                 {
251                         log.info("Exception while stopping the consumer: {}", e.toString());
252                 }
253         }
254
255         public static class RecordHandler implements Consumer<ConsumerRecord<String, Long>>
256         {
257                 Consumer<ConsumerRecord<String, Long>> captureOffsets;
258                 Consumer<ConsumerRecord<String, Long>> testHandler;
259
260
261                 @Override
262                 public void accept(ConsumerRecord<String, Long> record)
263                 {
264                         captureOffsets
265                                         .andThen(testHandler)
266                                         .accept(record);
267                 }
268         }
269
270         @TestConfiguration
271         @Import(ApplicationConfiguration.class)
272         public static class Configuration
273         {
274                 @Primary
275                 @Bean
276                 public Consumer<ConsumerRecord<String, Long>> testHandler()
277                 {
278                         return new RecordHandler();
279                 }
280
281                 @Bean
282                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
283                 {
284                         Properties props = new Properties();
285                         props.put("bootstrap.servers", properties.getBootstrapServer());
286                         props.put("linger.ms", 100);
287                         props.put("key.serializer", StringSerializer.class.getName());
288                         props.put("value.serializer", BytesSerializer.class.getName());
289
290                         return new KafkaProducer<>(props);
291                 }
292
293                 @Bean
294                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
295                 {
296                         Properties props = new Properties();
297                         props.put("bootstrap.servers", properties.getBootstrapServer());
298                         props.put("client.id", "OFFSET-CONSUMER");
299                         props.put("group.id", properties.getGroupId());
300                         props.put("key.deserializer", BytesDeserializer.class.getName());
301                         props.put("value.deserializer", BytesDeserializer.class.getName());
302
303                         return new KafkaConsumer<>(props);
304                 }
305         }
306 }