Tests: Der Test wartet, bis die Offsets regulär committed wurden
[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         @Test
75         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
76         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
77         {
78                 send100Messages(i ->  new Bytes(longSerializer.serialize(TOPIC, i)));
79
80                 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
81                 testHandler = record -> received.add(record);
82
83                 await("100 records received")
84                                 .atMost(Duration.ofSeconds(30))
85                                 .until(() -> received.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 commitsNoOffsetsOnError()
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(oldOffsets);
111         }
112
113
114         void send100Messages(Function<Long, Bytes> messageGenerator)
115         {
116                 long i = 0;
117
118                 for (int partition = 0; partition < 10; partition++)
119                 {
120                         for (int key = 0; key < 10; key++)
121                         {
122                                 Bytes value = messageGenerator.apply(++i);
123
124                                 ProducerRecord<String, Bytes> record =
125                                                 new ProducerRecord<>(
126                                                                 TOPIC,
127                                                                 partition,
128                                                                 Integer.toString(key%2),
129                                                                 value);
130
131                                 kafkaProducer.send(record, (metadata, e) ->
132                                 {
133                                         if (metadata != null)
134                                         {
135                                                 log.debug(
136                                                                 "{}|{} - {}={}",
137                                                                 metadata.partition(),
138                                                                 metadata.offset(),
139                                                                 record.key(),
140                                                                 record.value());
141                                         }
142                                         else
143                                         {
144                                                 log.warn(
145                                                                 "Exception for {}={}: {}",
146                                                                 record.key(),
147                                                                 record.value(),
148                                                                 e.toString());
149                                         }
150                                 });
151                         }
152                 }
153         }
154
155         @BeforeEach
156         public void init()
157         {
158                 testHandler = record -> {} ;
159
160                 oldOffsets = new HashMap<>();
161                 newOffsets = new HashMap<>();
162
163                 doForCurrentOffsets((tp, offset) ->
164                 {
165                         oldOffsets.put(tp, offset - 1);
166                         newOffsets.put(tp, offset - 1);
167                 });
168
169                 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
170                                 record ->
171                                 {
172                                         newOffsets.put(
173                                                         new TopicPartition(record.topic(), record.partition()),
174                                                         record.offset());
175                                         testHandler.accept(record);
176                                 };
177
178                 endlessConsumer =
179                                 new EndlessConsumer<>(
180                                                 executor,
181                                                 properties.getClientId(),
182                                                 properties.getTopic(),
183                                                 kafkaConsumer,
184                                                 captureOffsetAndExecuteTestHandler);
185
186                 endlessConsumer.start();
187         }
188
189         List<TopicPartition> partitions()
190         {
191                 return
192                                 IntStream
193                                                 .range(0, PARTITIONS)
194                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
195                                                 .collect(Collectors.toList());
196         }
197
198         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
199         {
200                 offsetConsumer.assign(partitions());
201                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
202                 offsetConsumer.unsubscribe();
203         }
204
205         void checkSeenOffsetsForProgress()
206         {
207                 // Be sure, that some messages were consumed...!
208                 Set<TopicPartition> withProgress = new HashSet<>();
209                 partitions().forEach(tp ->
210                 {
211                         Long oldOffset = oldOffsets.get(tp);
212                         Long newOffset = newOffsets.get(tp);
213                         if (!oldOffset.equals(newOffset))
214                         {
215                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
216                                 withProgress.add(tp);
217                         }
218                 });
219                 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
220         }
221
222         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
223         {
224                 doForCurrentOffsets((tp, offset) ->
225                 {
226                         Long expected = offsetsToCheck.get(tp) + 1;
227                         log.debug("Checking, if the offset for {} is {}", tp, expected);
228                         assertThat(offset).isEqualTo(expected);
229                 });
230         }
231
232
233         @AfterEach
234         public void deinit()
235         {
236                 try
237                 {
238                         endlessConsumer.stop();
239                 }
240                 catch (Exception e)
241                 {
242                         log.info("Exception while stopping the consumer: {}", e.toString());
243                 }
244         }
245
246         @TestConfiguration
247         @Import(ApplicationConfiguration.class)
248         public static class Configuration
249         {
250                 @Bean
251                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
252                 {
253                         Properties props = new Properties();
254                         props.put("bootstrap.servers", properties.getBootstrapServer());
255                         props.put("linger.ms", 100);
256                         props.put("key.serializer", StringSerializer.class.getName());
257                         props.put("value.serializer", BytesSerializer.class.getName());
258
259                         return new KafkaProducer<>(props);
260                 }
261
262                 @Bean
263                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
264                 {
265                         Properties props = new Properties();
266                         props.put("bootstrap.servers", properties.getBootstrapServer());
267                         props.put("client.id", "OFFSET-CONSUMER");
268                         props.put("group.id", properties.getGroupId());
269                         props.put("key.deserializer", BytesDeserializer.class.getName());
270                         props.put("value.deserializer", BytesDeserializer.class.getName());
271
272                         return new KafkaConsumer<>(props);
273                 }
274         }
275 }