bf1cdb8515a30053b64bfec64662809c8fa69d43
[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.WakeupException;
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.MethodOrderer;
15 import org.junit.jupiter.api.Order;
16 import org.junit.jupiter.api.Test;
17 import org.junit.jupiter.api.TestMethodOrder;
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
20 import org.springframework.boot.test.context.TestConfiguration;
21 import org.springframework.context.annotation.Bean;
22 import org.springframework.context.annotation.Import;
23 import org.springframework.kafka.test.context.EmbeddedKafka;
24 import org.springframework.test.context.TestPropertySource;
25 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
26
27 import java.util.*;
28 import java.util.concurrent.ExecutorService;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import java.util.stream.IntStream;
34
35 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
36 import static de.juplo.kafka.ApplicationTests.TOPIC;
37 import static org.assertj.core.api.Assertions.assertThat;
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         ApplicationProperties properties;
63         @Autowired
64         ExecutorService executor;
65
66
67         @Test
68         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
69         void commitsCurrentOffsetsOnSuccess()
70         {
71                 send100Messages(i ->  new Bytes(longSerializer.serialize(TOPIC, i)));
72
73                 Map<TopicPartition, Long> oldOffsets = new HashMap<>();
74                 doForCurrentOffsets((tp, offset) -> oldOffsets.put(tp, offset -1));
75                 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
76                 Map<TopicPartition, Long> newOffsets = runEndlessConsumer(record ->
77                 {
78                         received.add(record);
79                         if (received.size() == 100)
80                                 throw new WakeupException();
81                 });
82
83                 Set<TopicPartition> withProgress = new HashSet<>();
84                 partitions().forEach(tp ->
85                 {
86                         Long oldOffset = oldOffsets.get(tp);
87                         Long newOffset = newOffsets.get(tp);
88                         if (!oldOffset.equals(newOffset))
89                         {
90                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
91                                 withProgress.add(tp);
92                         }
93                 });
94                 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
95
96                 check(newOffsets);
97         }
98
99         @Test
100         @Order(2)
101         void commitsNoOffsetsOnError()
102         {
103                 send100Messages(counter ->
104                                 counter == 77
105                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
106                                                 : new Bytes(longSerializer.serialize(TOPIC, counter)));
107
108                 Map<TopicPartition, Long> oldOffsets = new HashMap<>();
109                 doForCurrentOffsets((tp, offset) -> oldOffsets.put(tp, offset -1));
110                 Map<TopicPartition, Long> newOffsets = runEndlessConsumer((record) -> {});
111
112                 Set<TopicPartition> withProgress = new HashSet<>();
113                 partitions().forEach(tp ->
114                 {
115                         Long oldOffset = oldOffsets.get(tp);
116                         Long newOffset = newOffsets.get(tp);
117                         if (!oldOffset.equals(newOffset))
118                         {
119                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
120                                 withProgress.add(tp);
121                         }
122                 });
123                 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
124
125                 check(oldOffsets);
126         }
127
128
129         void send100Messages(Function<Long, Bytes> messageGenerator)
130         {
131                 long i = 0;
132
133                 for (int partition = 0; partition < 10; partition++)
134                 {
135                         for (int key = 0; key < 10; key++)
136                         {
137                                 Bytes value = messageGenerator.apply(++i);
138
139                                 ProducerRecord<String, Bytes> record =
140                                                 new ProducerRecord<>(
141                                                                 TOPIC,
142                                                                 partition,
143                                                                 Integer.toString(key%2),
144                                                                 value);
145
146                                 kafkaProducer.send(record, (metadata, e) ->
147                                 {
148                                         if (metadata != null)
149                                         {
150                                                 log.debug(
151                                                                 "{}|{} - {}={}",
152                                                                 metadata.partition(),
153                                                                 metadata.offset(),
154                                                                 record.key(),
155                                                                 record.value());
156                                         }
157                                         else
158                                         {
159                                                 log.warn(
160                                                                 "Exception for {}={}: {}",
161                                                                 record.key(),
162                                                                 record.value(),
163                                                                 e.toString());
164                                         }
165                                 });
166                         }
167                 }
168         }
169
170         Map<TopicPartition, Long> runEndlessConsumer(Consumer<ConsumerRecord<String, Long>> consumer)
171         {
172                 Map<TopicPartition, Long> offsets = new HashMap<>();
173                 doForCurrentOffsets((tp, offset) -> offsets.put(tp, offset -1));
174                 Consumer<ConsumerRecord<String, Long>> captureOffset =
175                                 record ->
176                                                 offsets.put(
177                                                                 new TopicPartition(record.topic(), record.partition()),
178                                                                 record.offset());
179                 EndlessConsumer<String, Long> endlessConsumer =
180                                 new EndlessConsumer<>(
181                                                 executor,
182                                                 properties.getClientId(),
183                                                 properties.getTopic(),
184                                                 kafkaConsumer,
185                                                 captureOffset.andThen(consumer));
186
187                 endlessConsumer.run();
188
189                 return offsets;
190         }
191
192         List<TopicPartition> partitions()
193         {
194                 return
195                                 IntStream
196                                                 .range(0, PARTITIONS)
197                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
198                                                 .collect(Collectors.toList());
199         }
200
201         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
202         {
203                 kafkaConsumer.assign(partitions());
204                 partitions().forEach(tp -> consumer.accept(tp, kafkaConsumer.position(tp)));
205                 kafkaConsumer.unsubscribe();
206         }
207
208         void check(Map<TopicPartition, Long> offsets)
209         {
210                 doForCurrentOffsets((tp, offset) ->
211                 {
212                         Long expected = offsets.get(tp) + 1;
213                         log.debug("Checking, if the offset for {} is {}", tp, expected);
214                         assertThat(offset).isEqualTo(expected);
215                 });
216         }
217
218
219         @TestConfiguration
220         @Import(ApplicationConfiguration.class)
221         public static class Configuration
222         {
223                 @Bean
224                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
225                 {
226                         Properties props = new Properties();
227                         props.put("bootstrap.servers", properties.getBootstrapServer());
228                         props.put("linger.ms", 100);
229                         props.put("key.serializer", StringSerializer.class.getName());
230                         props.put("value.serializer", BytesSerializer.class.getName());
231
232                         return new KafkaProducer<>(props);
233                 }
234         }
235 }