Tests: Umbau für einen Commit im Fehlerfall und Anpassung des Tests
[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                 await("100 records received")
86                                 .atMost(Duration.ofSeconds(30))
87                                 .until(() -> received.size() >= 100);
88
89                 await("Offsets committed")
90                                 .atMost(Duration.ofSeconds(10))
91                                 .untilAsserted(() ->
92                                 {
93                                         checkSeenOffsetsForProgress();
94                                         compareToCommitedOffsets(newOffsets);
95                                 });
96         }
97
98         @Test
99         @Order(2)
100         void commitsOffsetOfErrorForReprocessingOnError()
101         {
102                 send100Messages(counter ->
103                                 counter == 77
104                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
105                                                 : new Bytes(longSerializer.serialize(TOPIC, counter)));
106
107                 await("Consumer failed")
108                                 .atMost(Duration.ofSeconds(30))
109                                 .until(() -> !endlessConsumer.running());
110
111                 checkSeenOffsetsForProgress();
112                 compareToCommitedOffsets(newOffsets);
113         }
114
115
116         /** Helper methods for the verification of expectations */
117
118         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
119         {
120                 doForCurrentOffsets((tp, offset) ->
121                 {
122                         Long expected = offsetsToCheck.get(tp) + 1;
123                         log.debug("Checking, if the offset for {} is {}", tp, expected);
124                         assertThat(offset).isEqualTo(expected);
125                 });
126         }
127
128         void checkSeenOffsetsForProgress()
129         {
130                 // Be sure, that some messages were consumed...!
131                 Set<TopicPartition> withProgress = new HashSet<>();
132                 partitions().forEach(tp ->
133                 {
134                         Long oldOffset = oldOffsets.get(tp);
135                         Long newOffset = newOffsets.get(tp);
136                         if (!oldOffset.equals(newOffset))
137                         {
138                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
139                                 withProgress.add(tp);
140                         }
141                 });
142                 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
143         }
144
145
146         /** Helper methods for setting up and running the tests */
147
148         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
149         {
150                 offsetConsumer.assign(partitions());
151                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
152                 offsetConsumer.unsubscribe();
153         }
154
155         List<TopicPartition> partitions()
156         {
157                 return
158                                 IntStream
159                                                 .range(0, PARTITIONS)
160                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
161                                                 .collect(Collectors.toList());
162         }
163
164
165         void send100Messages(Function<Long, Bytes> messageGenerator)
166         {
167                 long i = 0;
168
169                 for (int partition = 0; partition < 10; partition++)
170                 {
171                         for (int key = 0; key < 10; key++)
172                         {
173                                 Bytes value = messageGenerator.apply(++i);
174
175                                 ProducerRecord<String, Bytes> record =
176                                                 new ProducerRecord<>(
177                                                                 TOPIC,
178                                                                 partition,
179                                                                 Integer.toString(key%2),
180                                                                 value);
181
182                                 kafkaProducer.send(record, (metadata, e) ->
183                                 {
184                                         if (metadata != null)
185                                         {
186                                                 log.debug(
187                                                                 "{}|{} - {}={}",
188                                                                 metadata.partition(),
189                                                                 metadata.offset(),
190                                                                 record.key(),
191                                                                 record.value());
192                                         }
193                                         else
194                                         {
195                                                 log.warn(
196                                                                 "Exception for {}={}: {}",
197                                                                 record.key(),
198                                                                 record.value(),
199                                                                 e.toString());
200                                         }
201                                 });
202                         }
203                 }
204         }
205
206
207         @BeforeEach
208         public void init()
209         {
210                 testHandler = record -> {} ;
211
212                 oldOffsets = new HashMap<>();
213                 newOffsets = new HashMap<>();
214
215                 doForCurrentOffsets((tp, offset) ->
216                 {
217                         oldOffsets.put(tp, offset - 1);
218                         newOffsets.put(tp, offset - 1);
219                 });
220
221                 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
222                                 record ->
223                                 {
224                                         newOffsets.put(
225                                                         new TopicPartition(record.topic(), record.partition()),
226                                                         record.offset());
227                                         testHandler.accept(record);
228                                 };
229
230                 endlessConsumer =
231                                 new EndlessConsumer<>(
232                                                 executor,
233                                                 properties.getClientId(),
234                                                 properties.getTopic(),
235                                                 kafkaConsumer,
236                                                 captureOffsetAndExecuteTestHandler);
237
238                 endlessConsumer.start();
239         }
240
241         @AfterEach
242         public void deinit()
243         {
244                 try
245                 {
246                         endlessConsumer.stop();
247                 }
248                 catch (Exception e)
249                 {
250                         log.info("Exception while stopping the consumer: {}", e.toString());
251                 }
252         }
253
254
255         @TestConfiguration
256         @Import(ApplicationConfiguration.class)
257         public static class Configuration
258         {
259                 @Bean
260                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
261                 {
262                         Properties props = new Properties();
263                         props.put("bootstrap.servers", properties.getBootstrapServer());
264                         props.put("linger.ms", 100);
265                         props.put("key.serializer", StringSerializer.class.getName());
266                         props.put("value.serializer", BytesSerializer.class.getName());
267
268                         return new KafkaProducer<>(props);
269                 }
270
271                 @Bean
272                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
273                 {
274                         Properties props = new Properties();
275                         props.put("bootstrap.servers", properties.getBootstrapServer());
276                         props.put("client.id", "OFFSET-CONSUMER");
277                         props.put("group.id", properties.getGroupId());
278                         props.put("key.deserializer", BytesDeserializer.class.getName());
279                         props.put("value.deserializer", BytesDeserializer.class.getName());
280
281                         return new KafkaConsumer<>(props);
282                 }
283         }
284 }