Wordcount-Implementierung mit Kafka-Boardmitteln und MongoDB als Storage
[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.*;
10 import org.apache.kafka.common.utils.Bytes;
11 import org.junit.jupiter.api.*;
12 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
14 import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
15 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
16 import org.springframework.boot.test.context.TestConfiguration;
17 import org.springframework.context.annotation.Bean;
18 import org.springframework.context.annotation.Import;
19 import org.springframework.kafka.test.context.EmbeddedKafka;
20 import org.springframework.test.context.TestPropertySource;
21 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
22
23 import java.time.Clock;
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.*;
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                                 "consumer.commit-interval=1s",
47                                 "spring.mongodb.embedded.version=4.4.13" })
48 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
49 @EnableAutoConfiguration
50 @AutoConfigureDataMongo
51 @Slf4j
52 class ApplicationTests
53 {
54         public static final String TOPIC = "FOO";
55         public static final int PARTITIONS = 10;
56
57
58         StringSerializer stringSerializer = new StringSerializer();
59
60         @Autowired
61         Serializer valueSerializer;
62         @Autowired
63         KafkaProducer<String, Bytes> kafkaProducer;
64         @Autowired
65         KafkaConsumer<String, String> kafkaConsumer;
66         @Autowired
67         PartitionStatisticsRepository partitionStatisticsRepository;
68         @Autowired
69         ApplicationProperties properties;
70         @Autowired
71         ExecutorService executor;
72         @Autowired
73         PartitionStatisticsRepository repository;
74
75         Consumer<ConsumerRecord<String, String>> testHandler;
76         EndlessConsumer endlessConsumer;
77         Map<TopicPartition, Long> oldOffsets;
78         Map<TopicPartition, Long> newOffsets;
79         Set<ConsumerRecord<String, String>> receivedRecords;
80
81
82         /** Tests methods */
83
84         @Test
85         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
86         {
87                 send100Messages(i ->  new Bytes(valueSerializer.serialize(TOPIC, i)));
88
89                 await("100 records received")
90                                 .atMost(Duration.ofSeconds(30))
91                                 .until(() -> receivedRecords.size() >= 100);
92
93                 await("Offsets committed")
94                                 .atMost(Duration.ofSeconds(10))
95                                 .untilAsserted(() ->
96                                 {
97                                         checkSeenOffsetsForProgress();
98                                         compareToCommitedOffsets(newOffsets);
99                                 });
100
101                 assertThatExceptionOfType(IllegalStateException.class)
102                                 .isThrownBy(() -> endlessConsumer.exitStatus())
103                                 .describedAs("Consumer should still be running");
104         }
105
106
107         /** Helper methods for the verification of expectations */
108
109         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
110         {
111                 doForCurrentOffsets((tp, offset) ->
112                 {
113                         Long expected = offsetsToCheck.get(tp) + 1;
114                         log.debug("Checking, if the offset for {} is {}", tp, expected);
115                         assertThat(offset)
116                                         .describedAs("Committed offset corresponds to the offset of the consumer")
117                                         .isEqualTo(expected);
118                 });
119         }
120
121         void checkSeenOffsetsForProgress()
122         {
123                 // Be sure, that some messages were consumed...!
124                 Set<TopicPartition> withProgress = new HashSet<>();
125                 partitions().forEach(tp ->
126                 {
127                         Long oldOffset = oldOffsets.get(tp);
128                         Long newOffset = newOffsets.get(tp);
129                         if (!oldOffset.equals(newOffset))
130                         {
131                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
132                                 withProgress.add(tp);
133                         }
134                 });
135                 assertThat(withProgress)
136                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
137                                 .isNotEmpty();
138         }
139
140
141         /** Helper methods for setting up and running the tests */
142
143         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
144         {
145                 partitions().forEach(tp ->
146                 {
147                         String partition = Integer.toString(tp.partition());
148                         Optional<Long> offset = partitionStatisticsRepository.findById(partition).map(document -> document.offset);
149                         consumer.accept(tp, offset.orElse(0l));
150                 });
151         }
152
153         List<TopicPartition> partitions()
154         {
155                 return
156                                 IntStream
157                                                 .range(0, PARTITIONS)
158                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
159                                                 .collect(Collectors.toList());
160         }
161
162
163         void send100Messages(Function<Long, Bytes> messageGenerator)
164         {
165                 long i = 0;
166
167                 for (int partition = 0; partition < 10; partition++)
168                 {
169                         for (int key = 0; key < 10; key++)
170                         {
171                                 Bytes value = messageGenerator.apply(++i);
172
173                                 ProducerRecord<String, Bytes> record =
174                                                 new ProducerRecord<>(
175                                                                 TOPIC,
176                                                                 partition,
177                                                                 Integer.toString(key%2),
178                                                                 value);
179
180                                 kafkaProducer.send(record, (metadata, e) ->
181                                 {
182                                         if (metadata != null)
183                                         {
184                                                 log.debug(
185                                                                 "{}|{} - {}={}",
186                                                                 metadata.partition(),
187                                                                 metadata.offset(),
188                                                                 record.key(),
189                                                                 record.value());
190                                         }
191                                         else
192                                         {
193                                                 log.warn(
194                                                                 "Exception for {}={}: {}",
195                                                                 record.key(),
196                                                                 record.value(),
197                                                                 e.toString());
198                                         }
199                                 });
200                         }
201                 }
202         }
203
204
205         @BeforeEach
206         public void init()
207         {
208                 testHandler = record -> {} ;
209
210                 oldOffsets = new HashMap<>();
211                 newOffsets = new HashMap<>();
212                 receivedRecords = new HashSet<>();
213
214                 doForCurrentOffsets((tp, offset) ->
215                 {
216                         oldOffsets.put(tp, offset - 1);
217                         newOffsets.put(tp, offset - 1);
218                 });
219
220                 Consumer<ConsumerRecord<String, String>> captureOffsetAndExecuteTestHandler =
221                                 record ->
222                                 {
223                                         newOffsets.put(
224                                                         new TopicPartition(record.topic(), record.partition()),
225                                                         record.offset());
226                                         receivedRecords.add(record);
227                                         testHandler.accept(record);
228                                 };
229
230                 endlessConsumer =
231                                 new EndlessConsumer(
232                                                 executor,
233                                                 repository,
234                                                 properties.getClientId(),
235                                                 properties.getTopic(),
236                                                 Clock.systemDefaultZone(),
237                                                 properties.getCommitInterval(),
238                                                 kafkaConsumer);
239
240                 endlessConsumer.start();
241         }
242
243         @AfterEach
244         public void deinit()
245         {
246                 try
247                 {
248                         endlessConsumer.stop();
249                 }
250                 catch (Exception e)
251                 {
252                         log.info("Exception while stopping the consumer: {}", e.toString());
253                 }
254         }
255
256
257         @TestConfiguration
258         @Import(ApplicationConfiguration.class)
259         public static class Configuration
260         {
261                 @Bean
262                 Serializer<Long> serializer()
263                 {
264                         return new LongSerializer();
265                 }
266
267                 @Bean
268                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
269                 {
270                         Properties props = new Properties();
271                         props.put("bootstrap.servers", properties.getBootstrapServer());
272                         props.put("linger.ms", 100);
273                         props.put("key.serializer", StringSerializer.class.getName());
274                         props.put("value.serializer", BytesSerializer.class.getName());
275
276                         return new KafkaProducer<>(props);
277                 }
278         }
279 }