Springify: GRÜN - `start()`/`stop()` werden im Test explizit aufgerufen
[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.autoconfigure.kafka.KafkaAutoConfiguration;
17 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
18 import org.springframework.boot.test.context.TestConfiguration;
19 import org.springframework.context.annotation.Bean;
20 import org.springframework.context.annotation.Import;
21 import org.springframework.context.annotation.Primary;
22 import org.springframework.kafka.test.context.EmbeddedKafka;
23 import org.springframework.test.context.TestPropertySource;
24 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
25
26 import java.time.Duration;
27 import java.util.*;
28 import java.util.concurrent.ExecutionException;
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 import static org.awaitility.Awaitility.*;
39
40
41 @SpringJUnitConfig(
42                 initializers = ConfigDataApplicationContextInitializer.class,
43     classes = {
44                                 EndlessConsumer.class,
45                                 KafkaAutoConfiguration.class,
46                                 ApplicationTests.Configuration.class })
47 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
48 @TestPropertySource(
49                 properties = {
50                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
51                                 "consumer.topic=" + TOPIC })
52 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
53 @Slf4j
54 class ApplicationTests
55 {
56         public static final String TOPIC = "FOO";
57         public static final int PARTITIONS = 10;
58
59
60         StringSerializer stringSerializer = new StringSerializer();
61         LongSerializer longSerializer = new LongSerializer();
62
63         @Autowired
64         KafkaProducer<String, Bytes> kafkaProducer;
65         @Autowired
66         KafkaConsumer<Bytes, Bytes> offsetConsumer;
67         @Autowired
68         ApplicationProperties properties;
69         @Autowired
70         EndlessConsumer endlessConsumer;
71         @Autowired
72         RecordHandler recordHandler;
73
74         Map<TopicPartition, Long> oldOffsets;
75         Map<TopicPartition, Long> newOffsets;
76
77
78         /** Tests methods */
79
80         @Test
81         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
82         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
83         {
84                 send100Messages(i ->  new Bytes(longSerializer.serialize(TOPIC, i)));
85
86                 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
87                 recordHandler.testHandler = record -> received.add(record);
88
89                 await("100 records received")
90                                 .atMost(Duration.ofSeconds(30))
91                                 .until(() -> received.size() >= 100);
92
93                 await("Offsets committed")
94                                 .atMost(Duration.ofSeconds(10))
95                                 .untilAsserted(() ->
96                                 {
97                                         checkSeenOffsetsForProgress();
98                                         compareToCommitedOffsets(newOffsets);
99                                 });
100         }
101
102         @Test
103         @Order(2)
104         void commitsOffsetOfErrorForReprocessingOnError()
105         {
106                 send100Messages(counter ->
107                                 counter == 77
108                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
109                                                 : new Bytes(longSerializer.serialize(TOPIC, counter)));
110
111                 await("Consumer failed")
112                                 .atMost(Duration.ofSeconds(30))
113                                 .untilAsserted(() -> checkSeenOffsetsForProgress());
114
115                 compareToCommitedOffsets(newOffsets);
116         }
117
118
119         /** Helper methods for the verification of expectations */
120
121         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
122         {
123                 doForCurrentOffsets((tp, offset) ->
124                 {
125                         Long expected = offsetsToCheck.get(tp) + 1;
126                         log.debug("Checking, if the offset for {} is {}", tp, expected);
127                         assertThat(offset).isEqualTo(expected);
128                 });
129         }
130
131         void checkSeenOffsetsForProgress()
132         {
133                 // Be sure, that some messages were consumed...!
134                 Set<TopicPartition> withProgress = new HashSet<>();
135                 partitions().forEach(tp ->
136                 {
137                         Long oldOffset = oldOffsets.get(tp);
138                         Long newOffset = newOffsets.get(tp);
139                         if (!oldOffset.equals(newOffset))
140                         {
141                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
142                                 withProgress.add(tp);
143                         }
144                 });
145                 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
146         }
147
148
149         /** Helper methods for setting up and running the tests */
150
151         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
152         {
153                 offsetConsumer.assign(partitions());
154                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
155                 offsetConsumer.unsubscribe();
156         }
157
158         List<TopicPartition> partitions()
159         {
160                 return
161                                 IntStream
162                                                 .range(0, PARTITIONS)
163                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
164                                                 .collect(Collectors.toList());
165         }
166
167
168         void send100Messages(Function<Long, Bytes> messageGenerator)
169         {
170                 long i = 0;
171
172                 for (int partition = 0; partition < 10; partition++)
173                 {
174                         for (int key = 0; key < 10; key++)
175                         {
176                                 Bytes value = messageGenerator.apply(++i);
177
178                                 ProducerRecord<String, Bytes> record =
179                                                 new ProducerRecord<>(
180                                                                 TOPIC,
181                                                                 partition,
182                                                                 Integer.toString(key%2),
183                                                                 value);
184
185                                 kafkaProducer.send(record, (metadata, e) ->
186                                 {
187                                         if (metadata != null)
188                                         {
189                                                 log.debug(
190                                                                 "{}|{} - {}={}",
191                                                                 metadata.partition(),
192                                                                 metadata.offset(),
193                                                                 record.key(),
194                                                                 record.value());
195                                         }
196                                         else
197                                         {
198                                                 log.warn(
199                                                                 "Exception for {}={}: {}",
200                                                                 record.key(),
201                                                                 record.value(),
202                                                                 e.toString());
203                                         }
204                                 });
205                         }
206                 }
207         }
208
209
210         @BeforeEach
211         public void init()
212         {
213                 recordHandler.testHandler = (record) -> {};
214
215                 oldOffsets = new HashMap<>();
216                 newOffsets = new HashMap<>();
217
218                 doForCurrentOffsets((tp, offset) ->
219                 {
220                         oldOffsets.put(tp, offset - 1);
221                         newOffsets.put(tp, offset - 1);
222                 });
223
224                 recordHandler.captureOffsets =
225                                 record ->
226                                         newOffsets.put(
227                                                         new TopicPartition(record.topic(), record.partition()),
228                                                         record.offset());
229
230                 endlessConsumer.start();
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         public static class RecordHandler implements Consumer<ConsumerRecord<String, Long>>
247         {
248                 Consumer<ConsumerRecord<String, Long>> captureOffsets;
249                 Consumer<ConsumerRecord<String, Long>> testHandler;
250
251
252                 @Override
253                 public void accept(ConsumerRecord<String, Long> record)
254                 {
255                         captureOffsets
256                                         .andThen(testHandler)
257                                         .accept(record);
258                 }
259         }
260
261         @TestConfiguration
262         @Import(ApplicationConfiguration.class)
263         public static class Configuration
264         {
265                 @Primary
266                 @Bean
267                 public Consumer<ConsumerRecord<String, Long>> testHandler()
268                 {
269                         return new RecordHandler();
270                 }
271
272                 @Bean
273                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
274                 {
275                         Properties props = new Properties();
276                         props.put("bootstrap.servers", properties.getBootstrapServer());
277                         props.put("linger.ms", 100);
278                         props.put("key.serializer", StringSerializer.class.getName());
279                         props.put("value.serializer", BytesSerializer.class.getName());
280
281                         return new KafkaProducer<>(props);
282                 }
283
284                 @Bean
285                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
286                 {
287                         Properties props = new Properties();
288                         props.put("bootstrap.servers", properties.getBootstrapServer());
289                         props.put("client.id", "OFFSET-CONSUMER");
290                         props.put("group.id", properties.getGroupId());
291                         props.put("key.deserializer", BytesDeserializer.class.getName());
292                         props.put("value.deserializer", BytesDeserializer.class.getName());
293
294                         return new KafkaConsumer<>(props);
295                 }
296         }
297 }