Erzeugung von ProducerRecord in Test refaktorisiert
[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.function.Function;
29 import java.util.stream.Collectors;
30 import java.util.stream.IntStream;
31
32 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
33 import static de.juplo.kafka.ApplicationTests.TOPIC;
34 import static org.assertj.core.api.Assertions.*;
35 import static org.awaitility.Awaitility.*;
36
37
38 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
39 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
40 @TestPropertySource(
41                 properties = {
42                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
43                                 "consumer.topic=" + TOPIC })
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         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
78         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
79         {
80                 send100Messages((partition, key, counter) ->
81                 {
82                         Bytes value = new Bytes(valueSerializer.serialize(TOPIC, counter));
83                         return new ProducerRecord<>(TOPIC, partition, key, value);
84                 });
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                 assertThatExceptionOfType(IllegalStateException.class)
99                                 .isThrownBy(() -> endlessConsumer.exitStatus())
100                                 .describedAs("Consumer should still be running");
101         }
102
103         @Test
104         @Order(2)
105         void commitsOffsetOfErrorForReprocessingOnError()
106         {
107                 send100Messages((partition, key, counter) ->
108                 {
109                         Bytes value = counter == 77
110                                         ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
111                                         : new Bytes(valueSerializer.serialize(TOPIC, counter));
112                         return new ProducerRecord<>(TOPIC, partition, key, value);
113                 });
114
115                 await("Consumer failed")
116                                 .atMost(Duration.ofSeconds(30))
117                                 .until(() -> !endlessConsumer.running());
118
119                 checkSeenOffsetsForProgress();
120                 compareToCommitedOffsets(newOffsets);
121
122                 endlessConsumer.start();
123                 await("Consumer failed")
124                                 .atMost(Duration.ofSeconds(30))
125                                 .until(() -> !endlessConsumer.running());
126
127                 checkSeenOffsetsForProgress();
128                 compareToCommitedOffsets(newOffsets);
129                 assertThat(receivedRecords.size())
130                                 .describedAs("Received not all sent events")
131                                 .isLessThan(100);
132
133                 assertThatNoException()
134                                 .describedAs("Consumer should not be running")
135                                 .isThrownBy(() -> endlessConsumer.exitStatus());
136                 assertThat(endlessConsumer.exitStatus())
137                                 .describedAs("Consumer should have exited abnormally")
138                                 .containsInstanceOf(RecordDeserializationException.class);
139         }
140
141
142         /** Helper methods for the verification of expectations */
143
144         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
145         {
146                 doForCurrentOffsets((tp, offset) ->
147                 {
148                         Long expected = offsetsToCheck.get(tp) + 1;
149                         log.debug("Checking, if the offset for {} is {}", tp, expected);
150                         assertThat(offset)
151                                         .describedAs("Committed offset corresponds to the offset of the consumer")
152                                         .isEqualTo(expected);
153                 });
154         }
155
156         void checkSeenOffsetsForProgress()
157         {
158                 // Be sure, that some messages were consumed...!
159                 Set<TopicPartition> withProgress = new HashSet<>();
160                 partitions().forEach(tp ->
161                 {
162                         Long oldOffset = oldOffsets.get(tp);
163                         Long newOffset = newOffsets.get(tp);
164                         if (!oldOffset.equals(newOffset))
165                         {
166                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
167                                 withProgress.add(tp);
168                         }
169                 });
170                 assertThat(withProgress)
171                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
172                                 .isNotEmpty();
173         }
174
175
176         /** Helper methods for setting up and running the tests */
177
178         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
179         {
180                 offsetConsumer.assign(partitions());
181                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
182                 offsetConsumer.unsubscribe();
183         }
184
185         List<TopicPartition> partitions()
186         {
187                 return
188                                 IntStream
189                                                 .range(0, PARTITIONS)
190                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
191                                                 .collect(Collectors.toList());
192         }
193
194
195         public interface RecordGenerator<K, V>
196         {
197                 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
198         }
199
200         void send100Messages(RecordGenerator recordGenerator)
201         {
202                 long i = 0;
203
204                 for (int partition = 0; partition < 10; partition++)
205                 {
206                         for (int key = 0; key < 10; key++)
207                         {
208                                 ProducerRecord<String, Bytes> record =
209                                                 recordGenerator.generate(partition, Integer.toString(key%2), ++i);
210
211                                 kafkaProducer.send(record, (metadata, e) ->
212                                 {
213                                         if (metadata != null)
214                                         {
215                                                 log.debug(
216                                                                 "{}|{} - {}={}",
217                                                                 metadata.partition(),
218                                                                 metadata.offset(),
219                                                                 record.key(),
220                                                                 record.value());
221                                         }
222                                         else
223                                         {
224                                                 log.warn(
225                                                                 "Exception for {}={}: {}",
226                                                                 record.key(),
227                                                                 record.value(),
228                                                                 e.toString());
229                                         }
230                                 });
231                         }
232                 }
233         }
234
235
236         @BeforeEach
237         public void init()
238         {
239                 testHandler = record -> {} ;
240
241                 oldOffsets = new HashMap<>();
242                 newOffsets = new HashMap<>();
243                 receivedRecords = new HashSet<>();
244
245                 doForCurrentOffsets((tp, offset) ->
246                 {
247                         oldOffsets.put(tp, offset - 1);
248                         newOffsets.put(tp, offset - 1);
249                 });
250
251                 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
252                                 record ->
253                                 {
254                                         newOffsets.put(
255                                                         new TopicPartition(record.topic(), record.partition()),
256                                                         record.offset());
257                                         receivedRecords.add(record);
258                                         testHandler.accept(record);
259                                 };
260
261                 endlessConsumer =
262                                 new EndlessConsumer<>(
263                                                 executor,
264                                                 properties.getClientId(),
265                                                 properties.getTopic(),
266                                                 kafkaConsumer,
267                                                 captureOffsetAndExecuteTestHandler);
268
269                 endlessConsumer.start();
270         }
271
272         @AfterEach
273         public void deinit()
274         {
275                 try
276                 {
277                         endlessConsumer.stop();
278                 }
279                 catch (Exception e)
280                 {
281                         log.info("Exception while stopping the consumer: {}", e.toString());
282                 }
283         }
284
285
286         @TestConfiguration
287         @Import(ApplicationConfiguration.class)
288         public static class Configuration
289         {
290                 @Bean
291                 Serializer<Long> serializer()
292                 {
293                         return new LongSerializer();
294                 }
295
296                 @Bean
297                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
298                 {
299                         Properties props = new Properties();
300                         props.put("bootstrap.servers", properties.getBootstrapServer());
301                         props.put("linger.ms", 100);
302                         props.put("key.serializer", StringSerializer.class.getName());
303                         props.put("value.serializer", BytesSerializer.class.getName());
304
305                         return new KafkaProducer<>(props);
306                 }
307
308                 @Bean
309                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
310                 {
311                         Properties props = new Properties();
312                         props.put("bootstrap.servers", properties.getBootstrapServer());
313                         props.put("client.id", "OFFSET-CONSUMER");
314                         props.put("group.id", properties.getGroupId());
315                         props.put("key.deserializer", BytesDeserializer.class.getName());
316                         props.put("value.deserializer", BytesDeserializer.class.getName());
317
318                         return new KafkaConsumer<>(props);
319                 }
320         }
321 }