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