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