Typisierbare Basis-Klasse `GenericApplicationTests` eingeführt
[demos/kafka/training] / src / test / java / de / juplo / kafka / GenericApplicationTest.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.Import;
17 import org.springframework.kafka.test.context.EmbeddedKafka;
18 import org.springframework.test.context.TestPropertySource;
19 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
20
21 import java.time.Duration;
22 import java.util.*;
23 import java.util.concurrent.ExecutorService;
24 import java.util.function.BiConsumer;
25 import java.util.function.Consumer;
26 import java.util.stream.Collectors;
27 import java.util.stream.IntStream;
28
29 import static de.juplo.kafka.GenericApplicationTest.PARTITIONS;
30 import static de.juplo.kafka.GenericApplicationTest.TOPIC;
31 import static org.assertj.core.api.Assertions.*;
32 import static org.awaitility.Awaitility.*;
33
34
35 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
36 @TestPropertySource(
37                 properties = {
38                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
39                                 "consumer.topic=" + TOPIC,
40                                 "consumer.commit-interval=1s" })
41 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
42 @Slf4j
43 abstract class GenericApplicationTest<K, V>
44 {
45         public static final String TOPIC = "FOO";
46         public static final int PARTITIONS = 10;
47
48
49         @Autowired
50         KafkaConsumer<K, V> kafkaConsumer;
51         @Autowired
52         ApplicationProperties properties;
53         @Autowired
54         ExecutorService executor;
55
56         KafkaProducer<K, Bytes> testRecordProducer;
57         KafkaConsumer<Bytes, Bytes> offsetConsumer;
58         Consumer<ConsumerRecord<K, V>> testHandler;
59         EndlessConsumer<K, V> endlessConsumer;
60         Map<TopicPartition, Long> oldOffsets;
61         Map<TopicPartition, Long> newOffsets;
62         Set<ConsumerRecord<K, V>> receivedRecords;
63
64
65         final Serializer<K> keySerializer;
66         final RecordGenerator<K> recordGenerator;
67         final Consumer<ProducerRecord<K, Bytes>> messageSender;
68
69         public GenericApplicationTest(
70                         Serializer<K> keySerializer,
71                         RecordGenerator<K> recordGenerator)
72         {
73                 this.keySerializer = keySerializer;
74                 this.recordGenerator = recordGenerator;
75                 this.messageSender = (record) -> sendMessage(record);
76         }
77
78
79         /** Tests methods */
80
81         @Test
82         void commitsCurrentOffsetsOnSuccess()
83         {
84                 recordGenerator.generate(100, Set.of(), messageSender);
85
86                 await("100 records received")
87                                 .atMost(Duration.ofSeconds(30))
88                                 .pollInterval(Duration.ofSeconds(1))
89                                 .until(() -> receivedRecords.size() >= 100);
90
91                 await("Offsets committed")
92                                 .atMost(Duration.ofSeconds(10))
93                                 .pollInterval(Duration.ofSeconds(1))
94                                 .untilAsserted(() ->
95                                 {
96                                         checkSeenOffsetsForProgress();
97                                         compareToCommitedOffsets(newOffsets);
98                                 });
99
100                 assertThatExceptionOfType(IllegalStateException.class)
101                                 .isThrownBy(() -> endlessConsumer.exitStatus())
102                                 .describedAs("Consumer should still be running");
103         }
104
105         @Test
106         void commitsOffsetOfErrorForReprocessingOnDeserializationError()
107         {
108                 recordGenerator.generate(100, Set.of(77), messageSender);
109
110                 await("Consumer failed")
111                                 .atMost(Duration.ofSeconds(30))
112                                 .pollInterval(Duration.ofSeconds(1))
113                                 .until(() -> !endlessConsumer.running());
114
115                 checkSeenOffsetsForProgress();
116                 compareToCommitedOffsets(newOffsets);
117
118                 endlessConsumer.start();
119                 await("Consumer failed")
120                                 .atMost(Duration.ofSeconds(30))
121                                 .pollInterval(Duration.ofSeconds(1))
122                                 .until(() -> !endlessConsumer.running());
123
124                 checkSeenOffsetsForProgress();
125                 compareToCommitedOffsets(newOffsets);
126                 assertThat(receivedRecords.size())
127                                 .describedAs("Received not all sent events")
128                                 .isLessThan(100);
129
130                 assertThatNoException()
131                                 .describedAs("Consumer should not be running")
132                                 .isThrownBy(() -> endlessConsumer.exitStatus());
133                 assertThat(endlessConsumer.exitStatus())
134                                 .describedAs("Consumer should have exited abnormally")
135                                 .containsInstanceOf(RecordDeserializationException.class);
136         }
137
138
139         /** Helper methods for the verification of expectations */
140
141         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
142         {
143                 doForCurrentOffsets((tp, offset) ->
144                 {
145                         Long expected = offsetsToCheck.get(tp) + 1;
146                         log.debug("Checking, if the offset for {} is {}", tp, expected);
147                         assertThat(offset)
148                                         .describedAs("Committed offset corresponds to the offset of the consumer")
149                                         .isEqualTo(expected);
150                 });
151         }
152
153         void checkSeenOffsetsForProgress()
154         {
155                 // Be sure, that some messages were consumed...!
156                 Set<TopicPartition> withProgress = new HashSet<>();
157                 partitions().forEach(tp ->
158                 {
159                         Long oldOffset = oldOffsets.get(tp) + 1;
160                         Long newOffset = newOffsets.get(tp) + 1;
161                         if (!oldOffset.equals(newOffset))
162                         {
163                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
164                                 withProgress.add(tp);
165                         }
166                 });
167                 assertThat(withProgress)
168                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
169                                 .isNotEmpty();
170         }
171
172
173         /** Helper methods for setting up and running the tests */
174
175         void seekToEnd()
176         {
177                 offsetConsumer.assign(partitions());
178                 offsetConsumer.seekToEnd(partitions());
179                 partitions().forEach(tp ->
180                 {
181                         // seekToEnd() works lazily: it only takes effect on poll()/position()
182                         Long offset = offsetConsumer.position(tp);
183                         log.info("New position for {}: {}", tp, offset);
184                 });
185                 // The new positions must be commited!
186                 offsetConsumer.commitSync();
187                 offsetConsumer.unsubscribe();
188         }
189
190         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
191         {
192                 offsetConsumer.assign(partitions());
193                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
194                 offsetConsumer.unsubscribe();
195         }
196
197         List<TopicPartition> partitions()
198         {
199                 return
200                                 IntStream
201                                                 .range(0, PARTITIONS)
202                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
203                                                 .collect(Collectors.toList());
204         }
205
206
207         public interface RecordGenerator<K>
208         {
209                 void generate(
210                                 int numberOfMessagesToGenerate,
211                                 Set<Integer> poistionPills,
212                                 Consumer<ProducerRecord<K, Bytes>> messageSender);
213         }
214
215         void sendMessage(ProducerRecord<K, Bytes> record)
216         {
217                 testRecordProducer.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         @BeforeEach
241         public void init()
242         {
243                 Properties props;
244                 props = new Properties();
245                 props.put("bootstrap.servers", properties.getBootstrapServer());
246                 props.put("linger.ms", 100);
247                 props.put("key.serializer", keySerializer.getClass().getName());
248                 props.put("value.serializer", BytesSerializer.class.getName());
249                 testRecordProducer = new KafkaProducer<>(props);
250
251                 props = new Properties();
252                 props.put("bootstrap.servers", properties.getBootstrapServer());
253                 props.put("client.id", "OFFSET-CONSUMER");
254                 props.put("group.id", properties.getGroupId());
255                 props.put("key.deserializer", BytesDeserializer.class.getName());
256                 props.put("value.deserializer", BytesDeserializer.class.getName());
257                 offsetConsumer = new KafkaConsumer<>(props);
258
259                 testHandler = record -> {} ;
260
261                 seekToEnd();
262
263                 oldOffsets = new HashMap<>();
264                 newOffsets = new HashMap<>();
265                 receivedRecords = new HashSet<>();
266
267                 doForCurrentOffsets((tp, offset) ->
268                 {
269                         oldOffsets.put(tp, offset - 1);
270                         newOffsets.put(tp, offset - 1);
271                 });
272
273                 Consumer<ConsumerRecord<K, V>> captureOffsetAndExecuteTestHandler =
274                                 record ->
275                                 {
276                                         newOffsets.put(
277                                                         new TopicPartition(record.topic(), record.partition()),
278                                                         record.offset());
279                                         receivedRecords.add(record);
280                                         testHandler.accept(record);
281                                 };
282
283                 endlessConsumer =
284                                 new EndlessConsumer<>(
285                                                 executor,
286                                                 properties.getClientId(),
287                                                 properties.getTopic(),
288                                                 kafkaConsumer,
289                                                 captureOffsetAndExecuteTestHandler);
290
291                 endlessConsumer.start();
292         }
293
294         @AfterEach
295         public void deinit()
296         {
297                 try
298                 {
299                         endlessConsumer.stop();
300                         testRecordProducer.close();
301                         offsetConsumer.close();
302                 }
303                 catch (Exception e)
304                 {
305                         log.info("Exception while stopping the consumer: {}", e.toString());
306                 }
307         }
308
309
310         @TestConfiguration
311         @Import(ApplicationConfiguration.class)
312         public static class Configuration {}
313 }