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