Testfall überarbeitet
[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=100ms" })
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                                 .until(() -> receivedRecords.size() >= 100);
88
89                 await("Offsets committed")
90                                 .atMost(Duration.ofSeconds(10))
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         void commitsOffsetOfErrorForReprocessingOnDeserializationError()
104         {
105                 send100Messages((partition, key, counter) ->
106                 {
107                         Bytes value = counter == 77
108                                         ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
109                                         : new Bytes(valueSerializer.serialize(TOPIC, counter));
110                         return new ProducerRecord<>(TOPIC, partition, key, value);
111                 });
112
113                 await("Consumer failed")
114                                 .atMost(Duration.ofSeconds(30))
115                                 .until(() -> !endlessConsumer.running());
116
117                 checkSeenOffsetsForProgress();
118                 compareToCommitedOffsets(newOffsets);
119
120                 endlessConsumer.start();
121                 await("Consumer failed")
122                                 .atMost(Duration.ofSeconds(30))
123                                 .until(() -> !endlessConsumer.running());
124
125                 checkSeenOffsetsForProgress();
126                 compareToCommitedOffsets(newOffsets);
127                 assertThat(receivedRecords.size())
128                                 .describedAs("Received not all sent events")
129                                 .isLessThan(100);
130
131                 assertThatNoException()
132                                 .describedAs("Consumer should not be running")
133                                 .isThrownBy(() -> endlessConsumer.exitStatus());
134                 assertThat(endlessConsumer.exitStatus())
135                                 .describedAs("Consumer should have exited abnormally")
136                                 .containsInstanceOf(RecordDeserializationException.class);
137         }
138
139
140         /** Helper methods for the verification of expectations */
141
142         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
143         {
144                 doForCurrentOffsets((tp, offset) ->
145                 {
146                         Long expected = offsetsToCheck.get(tp) + 1;
147                         log.debug("Checking, if the offset for {} is {}", tp, expected);
148                         assertThat(offset)
149                                         .describedAs("Committed offset corresponds to the offset of the consumer")
150                                         .isEqualTo(expected);
151                 });
152         }
153
154         void checkSeenOffsetsForProgress()
155         {
156                 // Be sure, that some messages were consumed...!
157                 Set<TopicPartition> withProgress = new HashSet<>();
158                 partitions().forEach(tp ->
159                 {
160                         Long oldOffset = oldOffsets.get(tp) + 1;
161                         Long newOffset = newOffsets.get(tp) + 1;
162                         if (!oldOffset.equals(newOffset))
163                         {
164                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
165                                 withProgress.add(tp);
166                         }
167                 });
168                 assertThat(withProgress)
169                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
170                                 .isNotEmpty();
171         }
172
173
174         /** Helper methods for setting up and running the tests */
175
176         void seekToEnd()
177         {
178                 offsetConsumer.assign(partitions());
179                 offsetConsumer.seekToEnd(partitions());
180                 partitions().forEach(tp ->
181                 {
182                         // seekToEnd() works lazily: it only takes effect on poll()/position()
183                         Long offset = offsetConsumer.position(tp);
184                         log.info("New position for {}: {}", tp, offset);
185                 });
186                 // The new positions must be commited!
187                 offsetConsumer.commitSync();
188                 offsetConsumer.unsubscribe();
189         }
190
191         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
192         {
193                 offsetConsumer.assign(partitions());
194                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
195                 offsetConsumer.unsubscribe();
196         }
197
198         List<TopicPartition> partitions()
199         {
200                 return
201                                 IntStream
202                                                 .range(0, PARTITIONS)
203                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
204                                                 .collect(Collectors.toList());
205         }
206
207
208         public interface RecordGenerator<K, V>
209         {
210                 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
211         }
212
213         void send100Messages(RecordGenerator recordGenerator)
214         {
215                 long i = 0;
216
217                 for (int partition = 0; partition < 10; partition++)
218                 {
219                         for (int key = 0; key < 10; key++)
220                         {
221                                 ProducerRecord<String, Bytes> record =
222                                                 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
223
224                                 kafkaProducer.send(record, (metadata, e) ->
225                                 {
226                                         if (metadata != null)
227                                         {
228                                                 log.debug(
229                                                                 "{}|{} - {}={}",
230                                                                 metadata.partition(),
231                                                                 metadata.offset(),
232                                                                 record.key(),
233                                                                 record.value());
234                                         }
235                                         else
236                                         {
237                                                 log.warn(
238                                                                 "Exception for {}={}: {}",
239                                                                 record.key(),
240                                                                 record.value(),
241                                                                 e.toString());
242                                         }
243                                 });
244                         }
245                 }
246         }
247
248
249         @BeforeEach
250         public void init()
251         {
252                 testHandler = record -> {} ;
253
254                 seekToEnd();
255
256                 oldOffsets = new HashMap<>();
257                 newOffsets = new HashMap<>();
258                 receivedRecords = new HashSet<>();
259
260                 doForCurrentOffsets((tp, offset) ->
261                 {
262                         oldOffsets.put(tp, offset - 1);
263                         newOffsets.put(tp, offset - 1);
264                 });
265
266                 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
267                                 record ->
268                                 {
269                                         newOffsets.put(
270                                                         new TopicPartition(record.topic(), record.partition()),
271                                                         record.offset());
272                                         receivedRecords.add(record);
273                                         testHandler.accept(record);
274                                 };
275
276                 endlessConsumer =
277                                 new EndlessConsumer<>(
278                                                 executor,
279                                                 properties.getClientId(),
280                                                 properties.getTopic(),
281                                                 kafkaConsumer,
282                                                 captureOffsetAndExecuteTestHandler);
283
284                 endlessConsumer.start();
285         }
286
287         @AfterEach
288         public void deinit()
289         {
290                 try
291                 {
292                         endlessConsumer.stop();
293                 }
294                 catch (Exception e)
295                 {
296                         log.info("Exception while stopping the consumer: {}", e.toString());
297                 }
298         }
299
300
301         @TestConfiguration
302         @Import(ApplicationConfiguration.class)
303         public static class Configuration
304         {
305                 @Bean
306                 Serializer<Long> serializer()
307                 {
308                         return new LongSerializer();
309                 }
310
311                 @Bean
312                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
313                 {
314                         Properties props = new Properties();
315                         props.put("bootstrap.servers", properties.getBootstrapServer());
316                         props.put("linger.ms", 100);
317                         props.put("key.serializer", StringSerializer.class.getName());
318                         props.put("value.serializer", BytesSerializer.class.getName());
319
320                         return new KafkaProducer<>(props);
321                 }
322
323                 @Bean
324                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
325                 {
326                         Properties props = new Properties();
327                         props.put("bootstrap.servers", properties.getBootstrapServer());
328                         props.put("client.id", "OFFSET-CONSUMER");
329                         props.put("group.id", properties.getGroupId());
330                         props.put("key.deserializer", BytesDeserializer.class.getName());
331                         props.put("value.deserializer", BytesDeserializer.class.getName());
332
333                         return new KafkaConsumer<>(props);
334                 }
335         }
336 }