Anzahl der erzeugten Test-Nachrichten wird vom `RecordGenerator` bestimmt
[demos/kafka/training] / src / test / java / de / juplo / kafka / GenericApplicationTests.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.GenericApplicationTests.PARTITIONS;
30 import static de.juplo.kafka.GenericApplicationTests.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 GenericApplicationTests<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         Consumer<ConsumerRecord<K, V>> consumer;
53         @Autowired
54         ApplicationProperties properties;
55         @Autowired
56         ExecutorService executor;
57
58         KafkaProducer<Bytes, Bytes> testRecordProducer;
59         KafkaConsumer<Bytes, Bytes> offsetConsumer;
60         EndlessConsumer<K, V> endlessConsumer;
61         Map<TopicPartition, Long> oldOffsets;
62         Map<TopicPartition, Long> newOffsets;
63         Set<ConsumerRecord<K, V>> receivedRecords;
64
65
66         final RecordGenerator recordGenerator;
67         final Consumer<ProducerRecord<Bytes, Bytes>> messageSender;
68
69         public GenericApplicationTests(RecordGenerator recordGenerator)
70         {
71                 this.recordGenerator = recordGenerator;
72                 this.messageSender = (record) -> sendMessage(record);
73         }
74
75
76         /** Tests methods */
77
78         @Test
79         void commitsCurrentOffsetsOnSuccess()
80         {
81                 recordGenerator.generate(100, Set.of(), Set.of(), messageSender);
82
83                 await("100 records received")
84                                 .atMost(Duration.ofSeconds(30))
85                                 .pollInterval(Duration.ofSeconds(1))
86                                 .until(() -> receivedRecords.size() >= 100);
87
88                 await("Offsets committed")
89                                 .atMost(Duration.ofSeconds(10))
90                                 .pollInterval(Duration.ofSeconds(1))
91                                 .untilAsserted(() ->
92                                 {
93                                         checkSeenOffsetsForProgress();
94                                         compareToCommitedOffsets(newOffsets);
95                                 });
96
97                 assertThatExceptionOfType(IllegalStateException.class)
98                                 .isThrownBy(() -> endlessConsumer.exitStatus())
99                                 .describedAs("Consumer should still be running");
100         }
101
102         @Test
103         @SkipWhenErrorCannotBeGenerated(poisonPill = true)
104         void commitsOffsetOfErrorForReprocessingOnDeserializationError()
105         {
106                 recordGenerator.generate(100, Set.of(77), Set.of(), messageSender);
107
108                 await("Consumer failed")
109                                 .atMost(Duration.ofSeconds(30))
110                                 .pollInterval(Duration.ofSeconds(1))
111                                 .until(() -> !endlessConsumer.running());
112
113                 checkSeenOffsetsForProgress();
114                 compareToCommitedOffsets(newOffsets);
115
116                 endlessConsumer.start();
117                 await("Consumer failed")
118                                 .atMost(Duration.ofSeconds(30))
119                                 .pollInterval(Duration.ofSeconds(1))
120                                 .until(() -> !endlessConsumer.running());
121
122                 checkSeenOffsetsForProgress();
123                 compareToCommitedOffsets(newOffsets);
124                 assertThat(receivedRecords.size())
125                                 .describedAs("Received not all sent events")
126                                 .isLessThan(100);
127
128                 assertThatNoException()
129                                 .describedAs("Consumer should not be running")
130                                 .isThrownBy(() -> endlessConsumer.exitStatus());
131                 assertThat(endlessConsumer.exitStatus())
132                                 .describedAs("Consumer should have exited abnormally")
133                                 .containsInstanceOf(RecordDeserializationException.class);
134         }
135
136         @Test
137         @SkipWhenErrorCannotBeGenerated(logicError = true)
138         void doesNotCommitOffsetsOnLogicError()
139         {
140                 recordGenerator.generate(100, Set.of(), Set.of(77), messageSender);
141
142                 await("Consumer failed")
143                                 .atMost(Duration.ofSeconds(30))
144                                 .pollInterval(Duration.ofSeconds(1))
145                                 .until(() -> !endlessConsumer.running());
146
147                 checkSeenOffsetsForProgress();
148                 compareToCommitedOffsets(oldOffsets);
149
150                 endlessConsumer.start();
151                 await("Consumer failed")
152                                 .atMost(Duration.ofSeconds(30))
153                                 .pollInterval(Duration.ofSeconds(1))
154                                 .until(() -> !endlessConsumer.running());
155
156                 checkSeenOffsetsForProgress();
157                 compareToCommitedOffsets(oldOffsets);
158                 assertThat(receivedRecords.size())
159                                 .describedAs("Received not all sent events")
160                                 .isLessThan(100);
161
162                 assertThatNoException()
163                                 .describedAs("Consumer should not be running")
164                                 .isThrownBy(() -> endlessConsumer.exitStatus());
165                 assertThat(endlessConsumer.exitStatus())
166                                 .describedAs("Consumer should have exited abnormally")
167                                 .containsInstanceOf(RuntimeException.class);
168         }
169
170
171         /** Helper methods for the verification of expectations */
172
173         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
174         {
175                 doForCurrentOffsets((tp, offset) ->
176                 {
177                         Long expected = offsetsToCheck.get(tp) + 1;
178                         log.debug("Checking, if the offset for {} is {}", tp, expected);
179                         assertThat(offset)
180                                         .describedAs("Committed offset corresponds to the offset of the consumer")
181                                         .isEqualTo(expected);
182                 });
183         }
184
185         void checkSeenOffsetsForProgress()
186         {
187                 // Be sure, that some messages were consumed...!
188                 Set<TopicPartition> withProgress = new HashSet<>();
189                 partitions().forEach(tp ->
190                 {
191                         Long oldOffset = oldOffsets.get(tp) + 1;
192                         Long newOffset = newOffsets.get(tp) + 1;
193                         if (!oldOffset.equals(newOffset))
194                         {
195                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
196                                 withProgress.add(tp);
197                         }
198                 });
199                 assertThat(withProgress)
200                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
201                                 .isNotEmpty();
202         }
203
204
205         /** Helper methods for setting up and running the tests */
206
207         void seekToEnd()
208         {
209                 offsetConsumer.assign(partitions());
210                 offsetConsumer.seekToEnd(partitions());
211                 partitions().forEach(tp ->
212                 {
213                         // seekToEnd() works lazily: it only takes effect on poll()/position()
214                         Long offset = offsetConsumer.position(tp);
215                         log.info("New position for {}: {}", tp, offset);
216                 });
217                 // The new positions must be commited!
218                 offsetConsumer.commitSync();
219                 offsetConsumer.unsubscribe();
220         }
221
222         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
223         {
224                 offsetConsumer.assign(partitions());
225                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
226                 offsetConsumer.unsubscribe();
227         }
228
229         List<TopicPartition> partitions()
230         {
231                 return
232                                 IntStream
233                                                 .range(0, PARTITIONS)
234                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
235                                                 .collect(Collectors.toList());
236         }
237
238
239         public interface RecordGenerator
240         {
241                 void generate(
242                                 Set<Integer> poisonPills,
243                                 Set<Integer> logicErrors,
244                                 Consumer<ProducerRecord<Bytes, Bytes>> messageSender);
245
246                 default boolean canGeneratePoisionPill()
247                 {
248                         return true;
249                 }
250
251                 default boolean canGenerateLogicError()
252                 {
253                         return true;
254                 }
255         }
256
257         void sendMessage(ProducerRecord<Bytes, Bytes> record)
258         {
259                 testRecordProducer.send(record, (metadata, e) ->
260                 {
261                         if (metadata != null)
262                         {
263                                 log.debug(
264                                                 "{}|{} - {}={}",
265                                                 metadata.partition(),
266                                                 metadata.offset(),
267                                                 record.key(),
268                                                 record.value());
269                         }
270                         else
271                         {
272                                 log.warn(
273                                                 "Exception for {}={}: {}",
274                                                 record.key(),
275                                                 record.value(),
276                                                 e.toString());
277                         }
278                 });
279         }
280
281
282         @BeforeEach
283         public void init()
284         {
285                 Properties props;
286                 props = new Properties();
287                 props.put("bootstrap.servers", properties.getBootstrapServer());
288                 props.put("linger.ms", 100);
289                 props.put("key.serializer", BytesSerializer.class.getName());
290                 props.put("value.serializer", BytesSerializer.class.getName());
291                 testRecordProducer = new KafkaProducer<>(props);
292
293                 props = new Properties();
294                 props.put("bootstrap.servers", properties.getBootstrapServer());
295                 props.put("client.id", "OFFSET-CONSUMER");
296                 props.put("group.id", properties.getGroupId());
297                 props.put("key.deserializer", BytesDeserializer.class.getName());
298                 props.put("value.deserializer", BytesDeserializer.class.getName());
299                 offsetConsumer = new KafkaConsumer<>(props);
300
301                 seekToEnd();
302
303                 oldOffsets = new HashMap<>();
304                 newOffsets = new HashMap<>();
305                 receivedRecords = new HashSet<>();
306
307                 doForCurrentOffsets((tp, offset) ->
308                 {
309                         oldOffsets.put(tp, offset - 1);
310                         newOffsets.put(tp, offset - 1);
311                 });
312
313                 Consumer<ConsumerRecord<K, V>> captureOffsetAndExecuteTestHandler =
314                                 record ->
315                                 {
316                                         newOffsets.put(
317                                                         new TopicPartition(record.topic(), record.partition()),
318                                                         record.offset());
319                                         receivedRecords.add(record);
320                                         consumer.accept(record);
321                                 };
322
323                 endlessConsumer =
324                                 new EndlessConsumer<>(
325                                                 executor,
326                                                 properties.getClientId(),
327                                                 properties.getTopic(),
328                                                 kafkaConsumer,
329                                                 captureOffsetAndExecuteTestHandler);
330
331                 endlessConsumer.start();
332         }
333
334         @AfterEach
335         public void deinit()
336         {
337                 try
338                 {
339                         endlessConsumer.stop();
340                         testRecordProducer.close();
341                         offsetConsumer.close();
342                 }
343                 catch (Exception e)
344                 {
345                         log.info("Exception while stopping the consumer: {}", e.toString());
346                 }
347         }
348
349
350         @TestConfiguration
351         @Import(ApplicationConfiguration.class)
352         public static class Configuration
353         {
354         }
355 }