Das Speichern der Daten und Offsets erfolgt nicht mehr nach jedem `poll()`
[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.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.EnableAutoConfiguration;
15 import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
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.kafka.test.context.EmbeddedKafka;
21 import org.springframework.test.context.TestPropertySource;
22 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
23
24 import java.time.Clock;
25 import java.time.Duration;
26 import java.util.*;
27 import java.util.concurrent.ExecutionException;
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;
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.*;
38 import static org.awaitility.Awaitility.*;
39
40
41 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
42 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
43 @TestPropertySource(
44                 properties = {
45                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
46                                 "consumer.topic=" + TOPIC,
47                                 "consumer.commit-interval=1s",
48                                 "spring.mongodb.embedded.version=4.4.13" })
49 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
50 @EnableAutoConfiguration
51 @AutoConfigureDataMongo
52 @Slf4j
53 class ApplicationTests
54 {
55         public static final String TOPIC = "FOO";
56         public static final int PARTITIONS = 10;
57
58
59         StringSerializer stringSerializer = new StringSerializer();
60
61         @Autowired
62         Serializer valueSerializer;
63         @Autowired
64         KafkaProducer<String, Bytes> kafkaProducer;
65         @Autowired
66         KafkaConsumer<String, Long> kafkaConsumer;
67         @Autowired
68         PartitionStatisticsRepository partitionStatisticsRepository;
69         @Autowired
70         ApplicationProperties properties;
71         @Autowired
72         ExecutorService executor;
73         @Autowired
74         PartitionStatisticsRepository repository;
75
76         Consumer<ConsumerRecord<String, Long>> testHandler;
77         EndlessConsumer<String, Long> endlessConsumer;
78         Map<TopicPartition, Long> oldOffsets;
79         Map<TopicPartition, Long> newOffsets;
80         Set<ConsumerRecord<String, Long>> receivedRecords;
81
82
83         /** Tests methods */
84
85         @Test
86         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
87         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
88         {
89                 send100Messages(i ->  new Bytes(valueSerializer.serialize(TOPIC, i)));
90
91                 await("100 records received")
92                                 .atMost(Duration.ofSeconds(30))
93                                 .until(() -> receivedRecords.size() >= 100);
94
95                 await("Offsets committed")
96                                 .atMost(Duration.ofSeconds(10))
97                                 .untilAsserted(() ->
98                                 {
99                                         checkSeenOffsetsForProgress();
100                                         compareToCommitedOffsets(newOffsets);
101                                 });
102
103                 assertThatExceptionOfType(IllegalStateException.class)
104                                 .isThrownBy(() -> endlessConsumer.exitStatus())
105                                 .describedAs("Consumer should still be running");
106         }
107
108         @Test
109         @Order(2)
110         void commitsOffsetOfErrorForReprocessingOnError()
111         {
112                 send100Messages(counter ->
113                                 counter == 77
114                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
115                                                 : new Bytes(valueSerializer.serialize(TOPIC, counter)));
116
117                 await("Consumer failed")
118                                 .atMost(Duration.ofSeconds(30))
119                                 .until(() -> !endlessConsumer.running());
120
121                 checkSeenOffsetsForProgress();
122                 compareToCommitedOffsets(newOffsets);
123
124                 endlessConsumer.start();
125                 await("Consumer failed")
126                                 .atMost(Duration.ofSeconds(30))
127                                 .until(() -> !endlessConsumer.running());
128
129                 checkSeenOffsetsForProgress();
130                 compareToCommitedOffsets(newOffsets);
131                 assertThat(receivedRecords.size())
132                                 .describedAs("Received not all sent events")
133                                 .isLessThan(100);
134
135                 assertThatNoException()
136                                 .describedAs("Consumer should not be running")
137                                 .isThrownBy(() -> endlessConsumer.exitStatus());
138                 assertThat(endlessConsumer.exitStatus())
139                                 .describedAs("Consumer should have exited abnormally")
140                                 .containsInstanceOf(RecordDeserializationException.class);
141         }
142
143
144         /** Helper methods for the verification of expectations */
145
146         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
147         {
148                 doForCurrentOffsets((tp, offset) ->
149                 {
150                         Long expected = offsetsToCheck.get(tp) + 1;
151                         log.debug("Checking, if the offset for {} is {}", tp, expected);
152                         assertThat(offset)
153                                         .describedAs("Committed offset corresponds to the offset of the consumer")
154                                         .isEqualTo(expected);
155                 });
156         }
157
158         void checkSeenOffsetsForProgress()
159         {
160                 // Be sure, that some messages were consumed...!
161                 Set<TopicPartition> withProgress = new HashSet<>();
162                 partitions().forEach(tp ->
163                 {
164                         Long oldOffset = oldOffsets.get(tp);
165                         Long newOffset = newOffsets.get(tp);
166                         if (!oldOffset.equals(newOffset))
167                         {
168                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
169                                 withProgress.add(tp);
170                         }
171                 });
172                 assertThat(withProgress)
173                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
174                                 .isNotEmpty();
175         }
176
177
178         /** Helper methods for setting up and running the tests */
179
180         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
181         {
182                 partitions().forEach(tp ->
183                 {
184                         String partition = Integer.toString(tp.partition());
185                         Optional<Long> offset = partitionStatisticsRepository.findById(partition).map(document -> document.offset);
186                         consumer.accept(tp, offset.orElse(0l));
187                 });
188         }
189
190         List<TopicPartition> partitions()
191         {
192                 return
193                                 IntStream
194                                                 .range(0, PARTITIONS)
195                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
196                                                 .collect(Collectors.toList());
197         }
198
199
200         void send100Messages(Function<Long, Bytes> messageGenerator)
201         {
202                 long i = 0;
203
204                 for (int partition = 0; partition < 10; partition++)
205                 {
206                         for (int key = 0; key < 10; key++)
207                         {
208                                 Bytes value = messageGenerator.apply(++i);
209
210                                 ProducerRecord<String, Bytes> record =
211                                                 new ProducerRecord<>(
212                                                                 TOPIC,
213                                                                 partition,
214                                                                 Integer.toString(key%2),
215                                                                 value);
216
217                                 kafkaProducer.send(record, (metadata, e) ->
218                                 {
219                                         if (metadata != null)
220                                         {
221                                                 log.debug(
222                                                                 "{}|{} - {}={}",
223                                                                 metadata.partition(),
224                                                                 metadata.offset(),
225                                                                 record.key(),
226                                                                 record.value());
227                                         }
228                                         else
229                                         {
230                                                 log.warn(
231                                                                 "Exception for {}={}: {}",
232                                                                 record.key(),
233                                                                 record.value(),
234                                                                 e.toString());
235                                         }
236                                 });
237                         }
238                 }
239         }
240
241
242         @BeforeEach
243         public void init()
244         {
245                 testHandler = record -> {} ;
246
247                 oldOffsets = new HashMap<>();
248                 newOffsets = new HashMap<>();
249                 receivedRecords = new HashSet<>();
250
251                 doForCurrentOffsets((tp, offset) ->
252                 {
253                         oldOffsets.put(tp, offset - 1);
254                         newOffsets.put(tp, offset - 1);
255                 });
256
257                 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
258                                 record ->
259                                 {
260                                         newOffsets.put(
261                                                         new TopicPartition(record.topic(), record.partition()),
262                                                         record.offset());
263                                         receivedRecords.add(record);
264                                         testHandler.accept(record);
265                                 };
266
267                 endlessConsumer =
268                                 new EndlessConsumer<>(
269                                                 executor,
270                                                 repository,
271                                                 properties.getClientId(),
272                                                 properties.getTopic(),
273                                                 Clock.systemDefaultZone(),
274                                                 properties.getCommitInterval(),
275                                                 kafkaConsumer,
276                                                 captureOffsetAndExecuteTestHandler);
277
278                 endlessConsumer.start();
279         }
280
281         @AfterEach
282         public void deinit()
283         {
284                 try
285                 {
286                         endlessConsumer.stop();
287                 }
288                 catch (Exception e)
289                 {
290                         log.info("Exception while stopping the consumer: {}", e.toString());
291                 }
292         }
293
294
295         @TestConfiguration
296         @Import(ApplicationConfiguration.class)
297         public static class Configuration
298         {
299                 @Bean
300                 Serializer<Long> serializer()
301                 {
302                         return new LongSerializer();
303                 }
304
305                 @Bean
306                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
307                 {
308                         Properties props = new Properties();
309                         props.put("bootstrap.servers", properties.getBootstrapServer());
310                         props.put("linger.ms", 100);
311                         props.put("key.serializer", StringSerializer.class.getName());
312                         props.put("value.serializer", BytesSerializer.class.getName());
313
314                         return new KafkaProducer<>(props);
315                 }
316         }
317 }