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