Tests: Fehlerfall-Test prüft, dass nicht alle Nachrichten gelesen wurden
[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.serialization.BytesDeserializer;
10 import org.apache.kafka.common.serialization.BytesSerializer;
11 import org.apache.kafka.common.serialization.LongSerializer;
12 import org.apache.kafka.common.serialization.StringSerializer;
13 import org.apache.kafka.common.utils.Bytes;
14 import org.junit.jupiter.api.*;
15 import org.springframework.beans.factory.annotation.Autowired;
16 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
17 import org.springframework.boot.test.context.TestConfiguration;
18 import org.springframework.context.annotation.Bean;
19 import org.springframework.context.annotation.Import;
20 import org.springframework.kafka.test.context.EmbeddedKafka;
21 import org.springframework.test.context.TestPropertySource;
22 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
23
24 import java.time.Duration;
25 import java.util.*;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.function.BiConsumer;
29 import java.util.function.Consumer;
30 import java.util.function.Function;
31 import java.util.stream.Collectors;
32 import java.util.stream.IntStream;
33
34 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
35 import static de.juplo.kafka.ApplicationTests.TOPIC;
36 import static org.assertj.core.api.Assertions.assertThat;
37 import static org.awaitility.Awaitility.*;
38
39
40 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
41 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
42 @TestPropertySource(
43                 properties = {
44                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
45                                 "consumer.topic=" + TOPIC })
46 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
47 @Slf4j
48 class ApplicationTests
49 {
50         public static final String TOPIC = "FOO";
51         public static final int PARTITIONS = 10;
52
53
54         StringSerializer stringSerializer = new StringSerializer();
55         LongSerializer longSerializer = new LongSerializer();
56
57         @Autowired
58         KafkaProducer<String, Bytes> kafkaProducer;
59         @Autowired
60         KafkaConsumer<String, Long> kafkaConsumer;
61         @Autowired
62         KafkaConsumer<Bytes, Bytes> offsetConsumer;
63         @Autowired
64         ApplicationProperties properties;
65         @Autowired
66         ExecutorService executor;
67
68         Consumer<ConsumerRecord<String, Long>> testHandler;
69         EndlessConsumer<String, Long> endlessConsumer;
70         Map<TopicPartition, Long> oldOffsets;
71         Map<TopicPartition, Long> newOffsets;
72
73
74         /** Tests methods */
75
76         @Test
77         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
78         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
79         {
80                 send100Messages(i ->  new Bytes(longSerializer.serialize(TOPIC, i)));
81
82                 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
83                 testHandler = record -> received.add(record);
84
85                 endlessConsumer.start();
86
87                 await("100 records received")
88                                 .atMost(Duration.ofSeconds(30))
89                                 .until(() -> received.size() >= 100);
90
91                 await("Offsets committed")
92                                 .atMost(Duration.ofSeconds(10))
93                                 .untilAsserted(() ->
94                                 {
95                                         checkSeenOffsetsForProgress();
96                                         compareToCommitedOffsets(newOffsets);
97                                 });
98         }
99
100         @Test
101         @Order(2)
102         void commitsOffsetOfErrorForReprocessingOnError()
103         {
104                 send100Messages(counter ->
105                                 counter == 77
106                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
107                                                 : new Bytes(longSerializer.serialize(TOPIC, counter)));
108
109                 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
110                 testHandler = record -> received.add(record);
111
112                 endlessConsumer.start();
113
114                 await("Consumer failed")
115                                 .atMost(Duration.ofSeconds(30))
116                                 .until(() -> !endlessConsumer.running());
117
118                 checkSeenOffsetsForProgress();
119                 compareToCommitedOffsets(newOffsets);
120
121                 endlessConsumer.start();
122                 await("Consumer failed")
123                                 .atMost(Duration.ofSeconds(30))
124                                 .until(() -> !endlessConsumer.running());
125
126                 checkSeenOffsetsForProgress();
127                 compareToCommitedOffsets(newOffsets);
128                 assertThat(received.size())
129                                 .describedAs("Received not all sent events")
130                                 .isLessThan(100);
131         }
132
133
134         /** Helper methods for the verification of expectations */
135
136         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
137         {
138                 doForCurrentOffsets((tp, offset) ->
139                 {
140                         Long expected = offsetsToCheck.get(tp) + 1;
141                         log.debug("Checking, if the offset for {} is {}", tp, expected);
142                         assertThat(offset)
143                                         .describedAs("Committed offset corresponds to the offset of the consumer")
144                                         .isEqualTo(expected);
145                 });
146         }
147
148         void checkSeenOffsetsForProgress()
149         {
150                 // Be sure, that some messages were consumed...!
151                 Set<TopicPartition> withProgress = new HashSet<>();
152                 partitions().forEach(tp ->
153                 {
154                         Long oldOffset = oldOffsets.get(tp);
155                         Long newOffset = newOffsets.get(tp);
156                         if (!oldOffset.equals(newOffset))
157                         {
158                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
159                                 withProgress.add(tp);
160                         }
161                 });
162                 assertThat(withProgress)
163                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
164                                 .isNotEmpty();
165         }
166
167
168         /** Helper methods for setting up and running the tests */
169
170         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
171         {
172                 offsetConsumer.assign(partitions());
173                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
174                 offsetConsumer.unsubscribe();
175         }
176
177         List<TopicPartition> partitions()
178         {
179                 return
180                                 IntStream
181                                                 .range(0, PARTITIONS)
182                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
183                                                 .collect(Collectors.toList());
184         }
185
186
187         void send100Messages(Function<Long, Bytes> messageGenerator)
188         {
189                 long i = 0;
190
191                 for (int partition = 0; partition < 10; partition++)
192                 {
193                         for (int key = 0; key < 10; key++)
194                         {
195                                 Bytes value = messageGenerator.apply(++i);
196
197                                 ProducerRecord<String, Bytes> record =
198                                                 new ProducerRecord<>(
199                                                                 TOPIC,
200                                                                 partition,
201                                                                 Integer.toString(key%2),
202                                                                 value);
203
204                                 kafkaProducer.send(record, (metadata, e) ->
205                                 {
206                                         if (metadata != null)
207                                         {
208                                                 log.debug(
209                                                                 "{}|{} - {}={}",
210                                                                 metadata.partition(),
211                                                                 metadata.offset(),
212                                                                 record.key(),
213                                                                 record.value());
214                                         }
215                                         else
216                                         {
217                                                 log.warn(
218                                                                 "Exception for {}={}: {}",
219                                                                 record.key(),
220                                                                 record.value(),
221                                                                 e.toString());
222                                         }
223                                 });
224                         }
225                 }
226         }
227
228
229         @BeforeEach
230         public void init()
231         {
232                 testHandler = record -> {} ;
233
234                 oldOffsets = new HashMap<>();
235                 newOffsets = new HashMap<>();
236
237                 doForCurrentOffsets((tp, offset) ->
238                 {
239                         oldOffsets.put(tp, offset - 1);
240                         newOffsets.put(tp, offset - 1);
241                 });
242
243                 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
244                                 record ->
245                                 {
246                                         newOffsets.put(
247                                                         new TopicPartition(record.topic(), record.partition()),
248                                                         record.offset());
249                                         testHandler.accept(record);
250                                 };
251
252                 endlessConsumer =
253                                 new EndlessConsumer<>(
254                                                 executor,
255                                                 properties.getClientId(),
256                                                 properties.getTopic(),
257                                                 kafkaConsumer,
258                                                 captureOffsetAndExecuteTestHandler);
259         }
260
261         @AfterEach
262         public void deinit()
263         {
264                 try
265                 {
266                         endlessConsumer.stop();
267                 }
268                 catch (Exception e)
269                 {
270                         log.info("Exception while stopping the consumer: {}", e.toString());
271                 }
272         }
273
274
275         @TestConfiguration
276         @Import(ApplicationConfiguration.class)
277         public static class Configuration
278         {
279                 @Bean
280                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
281                 {
282                         Properties props = new Properties();
283                         props.put("bootstrap.servers", properties.getBootstrapServer());
284                         props.put("linger.ms", 100);
285                         props.put("key.serializer", StringSerializer.class.getName());
286                         props.put("value.serializer", BytesSerializer.class.getName());
287
288                         return new KafkaProducer<>(props);
289                 }
290
291                 @Bean
292                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
293                 {
294                         Properties props = new Properties();
295                         props.put("bootstrap.servers", properties.getBootstrapServer());
296                         props.put("client.id", "OFFSET-CONSUMER");
297                         props.put("group.id", properties.getGroupId());
298                         props.put("key.deserializer", BytesDeserializer.class.getName());
299                         props.put("value.deserializer", BytesDeserializer.class.getName());
300
301                         return new KafkaConsumer<>(props);
302                 }
303         }
304 }