Verhalten des Testfalls kontrollierbarer gemacht
[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.test.context.ConfigDataApplicationContextInitializer;
15 import org.springframework.boot.test.context.TestConfiguration;
16 import org.springframework.context.annotation.Bean;
17 import org.springframework.context.annotation.Import;
18 import org.springframework.kafka.test.context.EmbeddedKafka;
19 import org.springframework.test.context.TestPropertySource;
20 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
21
22 import java.time.Duration;
23 import java.util.*;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.ExecutorService;
26 import java.util.function.BiConsumer;
27 import java.util.function.Consumer;
28 import java.util.stream.Collectors;
29 import java.util.stream.IntStream;
30
31 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
32 import static de.juplo.kafka.ApplicationTests.TOPIC;
33 import static org.assertj.core.api.Assertions.*;
34 import static org.awaitility.Awaitility.*;
35
36
37 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
38 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
39 @TestPropertySource(
40                 properties = {
41                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
42                                 "consumer.topic=" + TOPIC,
43                                 "consumer.commit-interval=1s" })
44 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
45 @Slf4j
46 class ApplicationTests
47 {
48         public static final String TOPIC = "FOO";
49         public static final int PARTITIONS = 10;
50
51
52         StringSerializer stringSerializer = new StringSerializer();
53
54         @Autowired
55         Serializer valueSerializer;
56         @Autowired
57         KafkaProducer<String, Bytes> kafkaProducer;
58         @Autowired
59         KafkaConsumer<String, Long> kafkaConsumer;
60         @Autowired
61         KafkaConsumer<Bytes, Bytes> offsetConsumer;
62         @Autowired
63         ApplicationProperties properties;
64         @Autowired
65         ExecutorService executor;
66
67         Consumer<ConsumerRecord<String, Long>> testHandler;
68         EndlessConsumer<String, Long> endlessConsumer;
69         Map<TopicPartition, Long> oldOffsets;
70         Map<TopicPartition, Long> newOffsets;
71         Set<ConsumerRecord<String, Long>> receivedRecords;
72
73
74         /** Tests methods */
75
76         @Test
77         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
78         {
79                 send100Messages((partition, key, counter) ->
80                 {
81                         Bytes value = new Bytes(valueSerializer.serialize(TOPIC, counter));
82                         return new ProducerRecord<>(TOPIC, partition, key, value);
83                 });
84
85                 await("100 records received")
86                                 .atMost(Duration.ofSeconds(30))
87                                 .pollInterval(Duration.ofSeconds(1))
88                                 .until(() -> receivedRecords.size() >= 100);
89
90                 await("Offsets committed")
91                                 .atMost(Duration.ofSeconds(10))
92                                 .pollInterval(Duration.ofSeconds(1))
93                                 .untilAsserted(() ->
94                                 {
95                                         checkSeenOffsetsForProgress();
96                                         compareToCommitedOffsets(newOffsets);
97                                 });
98
99                 assertThatExceptionOfType(IllegalStateException.class)
100                                 .isThrownBy(() -> endlessConsumer.exitStatus())
101                                 .describedAs("Consumer should still be running");
102         }
103
104         @Test
105         void commitsOffsetOfErrorForReprocessingOnDeserializationError()
106         {
107                 send100Messages((partition, key, counter) ->
108                 {
109                         Bytes value = counter == 77
110                                         ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
111                                         : new Bytes(valueSerializer.serialize(TOPIC, counter));
112                         return new ProducerRecord<>(TOPIC, partition, key, value);
113                 });
114
115                 await("Consumer failed")
116                                 .atMost(Duration.ofSeconds(30))
117                                 .pollInterval(Duration.ofSeconds(1))
118                                 .until(() -> !endlessConsumer.running());
119
120                 checkSeenOffsetsForProgress();
121                 compareToCommitedOffsets(newOffsets);
122
123                 endlessConsumer.start();
124                 await("Consumer failed")
125                                 .atMost(Duration.ofSeconds(30))
126                                 .pollInterval(Duration.ofSeconds(1))
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) + 1;
165                         Long newOffset = newOffsets.get(tp) + 1;
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 seekToEnd()
181         {
182                 offsetConsumer.assign(partitions());
183                 offsetConsumer.seekToEnd(partitions());
184                 partitions().forEach(tp ->
185                 {
186                         // seekToEnd() works lazily: it only takes effect on poll()/position()
187                         Long offset = offsetConsumer.position(tp);
188                         log.info("New position for {}: {}", tp, offset);
189                 });
190                 // The new positions must be commited!
191                 offsetConsumer.commitSync();
192                 offsetConsumer.unsubscribe();
193         }
194
195         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
196         {
197                 offsetConsumer.assign(partitions());
198                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
199                 offsetConsumer.unsubscribe();
200         }
201
202         List<TopicPartition> partitions()
203         {
204                 return
205                                 IntStream
206                                                 .range(0, PARTITIONS)
207                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
208                                                 .collect(Collectors.toList());
209         }
210
211
212         public interface RecordGenerator<K, V>
213         {
214                 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
215         }
216
217         void send100Messages(RecordGenerator recordGenerator)
218         {
219                 long i = 0;
220
221                 for (int partition = 0; partition < 10; partition++)
222                 {
223                         for (int key = 0; key < 10; key++)
224                         {
225                                 ProducerRecord<String, Bytes> record =
226                                                 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
227
228                                 kafkaProducer.send(record, (metadata, e) ->
229                                 {
230                                         if (metadata != null)
231                                         {
232                                                 log.debug(
233                                                                 "{}|{} - {}={}",
234                                                                 metadata.partition(),
235                                                                 metadata.offset(),
236                                                                 record.key(),
237                                                                 record.value());
238                                         }
239                                         else
240                                         {
241                                                 log.warn(
242                                                                 "Exception for {}={}: {}",
243                                                                 record.key(),
244                                                                 record.value(),
245                                                                 e.toString());
246                                         }
247                                 });
248                         }
249                 }
250         }
251
252
253         @BeforeEach
254         public void init()
255         {
256                 testHandler = record -> {} ;
257
258                 seekToEnd();
259
260                 oldOffsets = new HashMap<>();
261                 newOffsets = new HashMap<>();
262                 receivedRecords = new HashSet<>();
263
264                 doForCurrentOffsets((tp, offset) ->
265                 {
266                         oldOffsets.put(tp, offset - 1);
267                         newOffsets.put(tp, offset - 1);
268                 });
269
270                 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
271                                 record ->
272                                 {
273                                         newOffsets.put(
274                                                         new TopicPartition(record.topic(), record.partition()),
275                                                         record.offset());
276                                         receivedRecords.add(record);
277                                         testHandler.accept(record);
278                                 };
279
280                 endlessConsumer =
281                                 new EndlessConsumer<>(
282                                                 executor,
283                                                 properties.getClientId(),
284                                                 properties.getTopic(),
285                                                 kafkaConsumer,
286                                                 captureOffsetAndExecuteTestHandler);
287
288                 endlessConsumer.start();
289         }
290
291         @AfterEach
292         public void deinit()
293         {
294                 try
295                 {
296                         endlessConsumer.stop();
297                 }
298                 catch (Exception e)
299                 {
300                         log.info("Exception while stopping the consumer: {}", e.toString());
301                 }
302         }
303
304
305         @TestConfiguration
306         @Import(ApplicationConfiguration.class)
307         public static class Configuration
308         {
309                 @Bean
310                 Serializer<Long> serializer()
311                 {
312                         return new LongSerializer();
313                 }
314
315                 @Bean
316                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
317                 {
318                         Properties props = new Properties();
319                         props.put("bootstrap.servers", properties.getBootstrapServer());
320                         props.put("linger.ms", 100);
321                         props.put("key.serializer", StringSerializer.class.getName());
322                         props.put("value.serializer", BytesSerializer.class.getName());
323
324                         return new KafkaProducer<>(props);
325                 }
326
327                 @Bean
328                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
329                 {
330                         Properties props = new Properties();
331                         props.put("bootstrap.servers", properties.getBootstrapServer());
332                         props.put("client.id", "OFFSET-CONSUMER");
333                         props.put("group.id", properties.getGroupId());
334                         props.put("key.deserializer", BytesDeserializer.class.getName());
335                         props.put("value.deserializer", BytesDeserializer.class.getName());
336
337                         return new KafkaConsumer<>(props);
338                 }
339         }
340 }