Tests: Tests prüfen den Status des Consumers
[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.BytesDeserializer;
11 import org.apache.kafka.common.serialization.BytesSerializer;
12 import org.apache.kafka.common.serialization.LongSerializer;
13 import org.apache.kafka.common.serialization.StringSerializer;
14 import org.apache.kafka.common.utils.Bytes;
15 import org.junit.jupiter.api.*;
16 import org.springframework.beans.factory.annotation.Autowired;
17 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
18 import org.springframework.boot.test.context.TestConfiguration;
19 import org.springframework.context.annotation.Bean;
20 import org.springframework.context.annotation.Import;
21 import org.springframework.kafka.test.context.EmbeddedKafka;
22 import org.springframework.test.context.TestPropertySource;
23 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
24
25 import java.time.Duration;
26 import java.util.*;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.ExecutorService;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import java.util.stream.IntStream;
34
35 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
36 import static de.juplo.kafka.ApplicationTests.TOPIC;
37 import static org.assertj.core.api.Assertions.assertThat;
38 import static org.awaitility.Awaitility.*;
39 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
40 import static org.junit.jupiter.api.Assertions.assertThrows;
41
42
43 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
44 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
45 @TestPropertySource(
46                 properties = {
47                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
48                                 "consumer.topic=" + TOPIC })
49 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
50 @Slf4j
51 class ApplicationTests
52 {
53         public static final String TOPIC = "FOO";
54         public static final int PARTITIONS = 10;
55
56
57         StringSerializer stringSerializer = new StringSerializer();
58         LongSerializer longSerializer = new LongSerializer();
59
60         @Autowired
61         KafkaProducer<String, Bytes> kafkaProducer;
62         @Autowired
63         KafkaConsumer<String, Long> kafkaConsumer;
64         @Autowired
65         KafkaConsumer<Bytes, Bytes> offsetConsumer;
66         @Autowired
67         ApplicationProperties properties;
68         @Autowired
69         ExecutorService executor;
70
71         Consumer<ConsumerRecord<String, Long>> testHandler;
72         EndlessConsumer<String, Long> endlessConsumer;
73         Map<TopicPartition, Long> oldOffsets;
74         Map<TopicPartition, Long> newOffsets;
75         Set<ConsumerRecord<String, Long>> receivedRecords;
76
77
78         /** Tests methods */
79
80         @Test
81         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
82         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
83         {
84                 send100Messages(i ->  new Bytes(longSerializer.serialize(TOPIC, i)));
85
86                 await("100 records received")
87                                 .atMost(Duration.ofSeconds(30))
88                                 .until(() -> receivedRecords.size() >= 100);
89
90                 await("Offsets committed")
91                                 .atMost(Duration.ofSeconds(10))
92                                 .untilAsserted(() ->
93                                 {
94                                         checkSeenOffsetsForProgress();
95                                         compareToCommitedOffsets(newOffsets);
96                                 });
97
98                 assertThrows(
99                                 IllegalStateException.class,
100                                 () -> endlessConsumer.exitStatus(),
101                                 "Consumer should still be running");
102         }
103
104         @Test
105         @Order(2)
106         void commitsOffsetOfErrorForReprocessingOnError()
107         {
108                 send100Messages(counter ->
109                                 counter == 77
110                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
111                                                 : new Bytes(longSerializer.serialize(TOPIC, counter)));
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                 assertDoesNotThrow(
132                                 () -> endlessConsumer.exitStatus(),
133                                 "Consumer should not be running");
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);
161                         Long newOffset = newOffsets.get(tp);
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 doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
177         {
178                 offsetConsumer.assign(partitions());
179                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
180                 offsetConsumer.unsubscribe();
181         }
182
183         List<TopicPartition> partitions()
184         {
185                 return
186                                 IntStream
187                                                 .range(0, PARTITIONS)
188                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
189                                                 .collect(Collectors.toList());
190         }
191
192
193         void send100Messages(Function<Long, Bytes> messageGenerator)
194         {
195                 long i = 0;
196
197                 for (int partition = 0; partition < 10; partition++)
198                 {
199                         for (int key = 0; key < 10; key++)
200                         {
201                                 Bytes value = messageGenerator.apply(++i);
202
203                                 ProducerRecord<String, Bytes> record =
204                                                 new ProducerRecord<>(
205                                                                 TOPIC,
206                                                                 partition,
207                                                                 Integer.toString(key%2),
208                                                                 value);
209
210                                 kafkaProducer.send(record, (metadata, e) ->
211                                 {
212                                         if (metadata != null)
213                                         {
214                                                 log.debug(
215                                                                 "{}|{} - {}={}",
216                                                                 metadata.partition(),
217                                                                 metadata.offset(),
218                                                                 record.key(),
219                                                                 record.value());
220                                         }
221                                         else
222                                         {
223                                                 log.warn(
224                                                                 "Exception for {}={}: {}",
225                                                                 record.key(),
226                                                                 record.value(),
227                                                                 e.toString());
228                                         }
229                                 });
230                         }
231                 }
232         }
233
234
235         @BeforeEach
236         public void init()
237         {
238                 testHandler = record -> {} ;
239
240                 oldOffsets = new HashMap<>();
241                 newOffsets = new HashMap<>();
242                 receivedRecords = new HashSet<>();
243
244                 doForCurrentOffsets((tp, offset) ->
245                 {
246                         oldOffsets.put(tp, offset - 1);
247                         newOffsets.put(tp, offset - 1);
248                 });
249
250                 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
251                                 record ->
252                                 {
253                                         newOffsets.put(
254                                                         new TopicPartition(record.topic(), record.partition()),
255                                                         record.offset());
256                                         receivedRecords.add(record);
257                                         testHandler.accept(record);
258                                 };
259
260                 endlessConsumer =
261                                 new EndlessConsumer<>(
262                                                 executor,
263                                                 properties.getClientId(),
264                                                 properties.getTopic(),
265                                                 kafkaConsumer,
266                                                 captureOffsetAndExecuteTestHandler);
267
268                 endlessConsumer.start();
269         }
270
271         @AfterEach
272         public void deinit()
273         {
274                 try
275                 {
276                         endlessConsumer.stop();
277                 }
278                 catch (Exception e)
279                 {
280                         log.info("Exception while stopping the consumer: {}", e.toString());
281                 }
282         }
283
284
285         @TestConfiguration
286         @Import(ApplicationConfiguration.class)
287         public static class Configuration
288         {
289                 @Bean
290                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
291                 {
292                         Properties props = new Properties();
293                         props.put("bootstrap.servers", properties.getBootstrapServer());
294                         props.put("linger.ms", 100);
295                         props.put("key.serializer", StringSerializer.class.getName());
296                         props.put("value.serializer", BytesSerializer.class.getName());
297
298                         return new KafkaProducer<>(props);
299                 }
300
301                 @Bean
302                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
303                 {
304                         Properties props = new Properties();
305                         props.put("bootstrap.servers", properties.getBootstrapServer());
306                         props.put("client.id", "OFFSET-CONSUMER");
307                         props.put("group.id", properties.getGroupId());
308                         props.put("key.deserializer", BytesDeserializer.class.getName());
309                         props.put("value.deserializer", BytesDeserializer.class.getName());
310
311                         return new KafkaConsumer<>(props);
312                 }
313         }
314 }