TMP
[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.Duration;
24 import java.util.*;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.ExecutorService;
27 import java.util.function.BiConsumer;
28 import java.util.stream.Collectors;
29 import java.util.stream.IntStream;
30
31 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
32 import static de.juplo.kafka.ApplicationTests.TOPIC;
33 import static org.assertj.core.api.Assertions.*;
34 import static org.awaitility.Awaitility.*;
35
36
37 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
38 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
39 @TestPropertySource(
40                 properties = {
41                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
42                                 "consumer.topic=" + TOPIC,
43                                 "consumer.commit-interval=1s",
44                                 "spring.mongodb.embedded.version=4.4.13" })
45 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
46 @EnableAutoConfiguration
47 @AutoConfigureDataMongo
48 @Slf4j
49 class ApplicationTests
50 {
51         public static final String TOPIC = "FOO";
52         public static final int PARTITIONS = 10;
53
54
55         StringSerializer stringSerializer = new StringSerializer();
56
57         @Autowired
58         Serializer valueSerializer;
59         @Autowired
60         KafkaProducer<String, Bytes> kafkaProducer;
61         @Autowired
62         KafkaConsumer<String, String> kafkaConsumer;
63         @Autowired
64         KafkaConsumer<Bytes, Bytes> offsetConsumer;
65         @Autowired
66         PartitionStatisticsRepository partitionStatisticsRepository;
67         @Autowired
68         ApplicationProperties properties;
69         @Autowired
70         ExecutorService executor;
71         @Autowired
72         PartitionStatisticsRepository repository;
73         @Autowired
74         SumRebalanceListener sumRebalanceListener;
75         @Autowired
76         SumRecordHandler sumRecordHandler;
77
78         EndlessConsumer<String, String> endlessConsumer;
79         Map<TopicPartition, Long> oldOffsets;
80         Map<TopicPartition, Long> newOffsets;
81         Set<ConsumerRecord<String, String>> receivedRecords;
82
83
84         /** Tests methods */
85
86         @Test
87         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
88         {
89                 send100Messages((partition, key, counter) ->
90                 {
91                         Bytes value = new Bytes(valueSerializer.serialize(TOPIC, counter));
92                         return new ProducerRecord<>(TOPIC, partition, key, value);
93                 });
94
95                 await("100 records received")
96                                 .atMost(Duration.ofSeconds(30))
97                                 .pollInterval(Duration.ofSeconds(1))
98                                 .until(() -> receivedRecords.size() >= 100);
99
100                 await("Offsets committed")
101                                 .atMost(Duration.ofSeconds(10))
102                                 .pollInterval(Duration.ofSeconds(1))
103                                 .untilAsserted(() ->
104                                 {
105                                         checkSeenOffsetsForProgress();
106                                         compareToCommitedOffsets(newOffsets);
107                                 });
108
109                 assertThatExceptionOfType(IllegalStateException.class)
110                                 .isThrownBy(() -> endlessConsumer.exitStatus())
111                                 .describedAs("Consumer should still be running");
112         }
113
114
115         /** Helper methods for the verification of expectations */
116
117         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
118         {
119                 doForCurrentOffsets((tp, offset) ->
120                 {
121                         Long expected = offsetsToCheck.get(tp) + 1;
122                         log.debug("Checking, if the offset for {} is {}", tp, expected);
123                         assertThat(offset)
124                                         .describedAs("Committed offset corresponds to the offset of the consumer")
125                                         .isEqualTo(expected);
126                 });
127         }
128
129         void checkSeenOffsetsForProgress()
130         {
131                 // Be sure, that some messages were consumed...!
132                 Set<TopicPartition> withProgress = new HashSet<>();
133                 partitions().forEach(tp ->
134                 {
135                         Long oldOffset = oldOffsets.get(tp) + 1;
136                         Long newOffset = newOffsets.get(tp) + 1;
137                         if (!oldOffset.equals(newOffset))
138                         {
139                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
140                                 withProgress.add(tp);
141                         }
142                 });
143                 assertThat(withProgress)
144                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
145                                 .isNotEmpty();
146         }
147
148
149         /** Helper methods for setting up and running the tests */
150
151         void seekToEnd()
152         {
153                 offsetConsumer.assign(partitions());
154                 partitions().forEach(tp ->
155                 {
156                         Long offset = offsetConsumer.position(tp);
157                         log.info("New position for {}: {}", tp, offset);
158                         Integer partition = tp.partition();
159                         StatisticsDocument document =
160                                         partitionStatisticsRepository
161                                                         .findById(partition.toString())
162                                                         .orElse(new StatisticsDocument(partition));
163                         document.offset = offset;
164                         partitionStatisticsRepository.save(document);
165                 });
166                 offsetConsumer.unsubscribe();
167         }
168
169         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
170         {
171                 partitions().forEach(tp ->
172                 {
173                         String partition = Integer.toString(tp.partition());
174                         Optional<Long> offset = partitionStatisticsRepository.findById(partition).map(document -> document.offset);
175                         consumer.accept(tp, offset.orElse(0l));
176                 });
177         }
178
179         List<TopicPartition> partitions()
180         {
181                 return
182                                 IntStream
183                                                 .range(0, PARTITIONS)
184                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
185                                                 .collect(Collectors.toList());
186         }
187
188
189         public interface RecordGenerator<K, V>
190         {
191                 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
192         }
193
194         void send100Messages(RecordGenerator recordGenerator)
195         {
196                 long i = 0;
197
198                 for (int partition = 0; partition < 10; partition++)
199                 {
200                         for (int key = 0; key < 10; key++)
201                         {
202                                 ProducerRecord<String, Bytes> record =
203                                                 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
204
205                                 kafkaProducer.send(record, (metadata, e) ->
206                                 {
207                                         if (metadata != null)
208                                         {
209                                                 log.debug(
210                                                                 "{}|{} - {}={}",
211                                                                 metadata.partition(),
212                                                                 metadata.offset(),
213                                                                 record.key(),
214                                                                 record.value());
215                                         }
216                                         else
217                                         {
218                                                 log.warn(
219                                                                 "Exception for {}={}: {}",
220                                                                 record.key(),
221                                                                 record.value(),
222                                                                 e.toString());
223                                         }
224                                 });
225                         }
226                 }
227         }
228
229
230         @BeforeEach
231         public void init()
232         {
233                 seekToEnd();
234
235                 oldOffsets = new HashMap<>();
236                 newOffsets = new HashMap<>();
237                 receivedRecords = new HashSet<>();
238
239                 doForCurrentOffsets((tp, offset) ->
240                 {
241                         oldOffsets.put(tp, offset - 1);
242                         newOffsets.put(tp, offset - 1);
243                 });
244
245                 TestRecordHandler<String, String> captureOffsetAndExecuteTestHandler =
246                                 new TestRecordHandler<String, String>(sumRecordHandler) {
247                                         @Override
248                                         public void onNewRecord(ConsumerRecord<String, String> record)
249                                         {
250                                                 newOffsets.put(
251                                                                 new TopicPartition(record.topic(), record.partition()),
252                                                                 record.offset());
253                                                 receivedRecords.add(record);
254                                         }
255                                 };
256
257                 endlessConsumer =
258                                 new EndlessConsumer<>(
259                                                 executor,
260                                                 properties.getClientId(),
261                                                 properties.getTopic(),
262                                                 kafkaConsumer,
263                                                 sumRebalanceListener,
264                                                 captureOffsetAndExecuteTestHandler);
265
266                 endlessConsumer.start();
267         }
268
269         @AfterEach
270         public void deinit()
271         {
272                 try
273                 {
274                         endlessConsumer.stop();
275                 }
276                 catch (Exception e)
277                 {
278                         log.info("Exception while stopping the consumer: {}", e.toString());
279                 }
280         }
281
282
283         @TestConfiguration
284         @Import(ApplicationConfiguration.class)
285         public static class Configuration
286         {
287                 @Bean
288                 Serializer<Long> serializer()
289                 {
290                         return new LongSerializer();
291                 }
292
293                 @Bean
294                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
295                 {
296                         Properties props = new Properties();
297                         props.put("bootstrap.servers", properties.getBootstrapServer());
298                         props.put("linger.ms", 100);
299                         props.put("key.serializer", StringSerializer.class.getName());
300                         props.put("value.serializer", BytesSerializer.class.getName());
301
302                         return new KafkaProducer<>(props);
303                 }
304
305                 @Bean
306                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
307                 {
308                         Properties props = new Properties();
309                         props.put("bootstrap.servers", properties.getBootstrapServer());
310                         props.put("client.id", "OFFSET-CONSUMER");
311                         props.put("enable.auto.commit", false);
312                         props.put("auto.offset.reset", "latest");
313                         props.put("key.deserializer", BytesDeserializer.class.getName());
314                         props.put("value.deserializer", BytesDeserializer.class.getName());
315
316                         return new KafkaConsumer<>(props);
317                 }
318         }
319 }