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