Springify: Merge der Umstellung auf die Auto-Konfiguration von Spring-Boot
[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.RecordDeserializationException;
10 import org.apache.kafka.common.serialization.*;
11 import org.apache.kafka.common.utils.Bytes;
12 import org.junit.jupiter.api.*;
13 import org.springframework.beans.factory.annotation.Autowired;
14 import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
15 import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
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.context.annotation.Primary;
21 import org.springframework.kafka.support.serializer.JsonSerializer;
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.BiFunction;
31 import java.util.function.Consumer;
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.*;
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                                 "spring.kafka.consumer.bootstrap-servers=${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
62         @Autowired
63         Serializer valueSerializer;
64         @Autowired
65         KafkaProducer<String, Bytes> kafkaProducer;
66         @Autowired
67         org.apache.kafka.clients.consumer.Consumer<String, ClientMessage> kafkaConsumer;
68         @Autowired
69         KafkaConsumer<Bytes, Bytes> offsetConsumer;
70         @Autowired
71         ApplicationProperties applicationProperties;
72         @Autowired
73         KafkaProperties kafkaProperties;
74         @Autowired
75         EndlessConsumer endlessConsumer;
76         @Autowired
77         RecordHandler recordHandler;
78
79         Map<TopicPartition, Long> oldOffsets;
80         Map<TopicPartition, Long> newOffsets;
81         Set<ConsumerRecord<String, ClientMessage>> receivedRecords;
82
83
84         /** Tests methods */
85
86         @Test
87         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
88         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
89         {
90                 send100Messages((key, counter) -> serialize(key, counter));
91
92                 await("100 records received")
93                                 .atMost(Duration.ofSeconds(30))
94                                 .until(() -> receivedRecords.size() >= 100);
95
96                 await("Offsets committed")
97                                 .atMost(Duration.ofSeconds(10))
98                                 .untilAsserted(() ->
99                                 {
100                                         checkSeenOffsetsForProgress();
101                                         compareToCommitedOffsets(newOffsets);
102                                 });
103
104                 assertThatExceptionOfType(IllegalStateException.class)
105                                 .isThrownBy(() -> endlessConsumer.exitStatus())
106                                 .describedAs("Consumer should still be running");
107         }
108
109         @Test
110         @Order(2)
111         void commitsOffsetOfErrorForReprocessingOnError()
112         {
113                 send100Messages((key, counter) ->
114                                 counter == 77
115                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
116                                                 : serialize(key, counter));
117
118                 await("Consumer failed")
119                                 .atMost(Duration.ofSeconds(30))
120                                 .untilAsserted(() -> checkSeenOffsetsForProgress());
121
122                 compareToCommitedOffsets(newOffsets);
123                 assertThat(receivedRecords.size())
124                                 .describedAs("Received not all sent events")
125                                 .isLessThan(100);
126
127                 assertThatNoException()
128                                 .describedAs("Consumer should not be running")
129                                 .isThrownBy(() -> endlessConsumer.exitStatus());
130                 assertThat(endlessConsumer.exitStatus())
131                                 .containsInstanceOf(RecordDeserializationException.class)
132                                 .describedAs("Consumer should have exited abnormally");
133         }
134
135
136         /** Helper methods for the verification of expectations */
137
138         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
139         {
140                 doForCurrentOffsets((tp, offset) ->
141                 {
142                         Long expected = offsetsToCheck.get(tp) + 1;
143                         log.debug("Checking, if the offset for {} is {}", tp, expected);
144                         assertThat(offset)
145                                         .describedAs("Committed offset corresponds to the offset of the consumer")
146                                         .isEqualTo(expected);
147                 });
148         }
149
150         void checkSeenOffsetsForProgress()
151         {
152                 // Be sure, that some messages were consumed...!
153                 Set<TopicPartition> withProgress = new HashSet<>();
154                 partitions().forEach(tp ->
155                 {
156                         Long oldOffset = oldOffsets.get(tp);
157                         Long newOffset = newOffsets.get(tp);
158                         if (!oldOffset.equals(newOffset))
159                         {
160                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
161                                 withProgress.add(tp);
162                         }
163                 });
164                 assertThat(withProgress)
165                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
166                                 .isNotEmpty();
167         }
168
169
170         /** Helper methods for setting up and running the tests */
171
172         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
173         {
174                 offsetConsumer.assign(partitions());
175                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
176                 offsetConsumer.unsubscribe();
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         void send100Messages(BiFunction<Integer, Long, Bytes> messageGenerator)
190         {
191                 long i = 0;
192
193                 for (int partition = 0; partition < 10; partition++)
194                 {
195                         for (int key = 0; key < 10; key++)
196                         {
197                                 Bytes value = messageGenerator.apply(key, ++i);
198
199                                 ProducerRecord<String, Bytes> record =
200                                                 new ProducerRecord<>(
201                                                                 TOPIC,
202                                                                 partition,
203                                                                 Integer.toString(key%2),
204                                                                 value);
205
206                                 record.headers().add("__TypeId__", "message".getBytes());
207                                 kafkaProducer.send(record, (metadata, e) ->
208                                 {
209                                         if (metadata != null)
210                                         {
211                                                 log.debug(
212                                                                 "{}|{} - {}={}",
213                                                                 metadata.partition(),
214                                                                 metadata.offset(),
215                                                                 record.key(),
216                                                                 record.value());
217                                         }
218                                         else
219                                         {
220                                                 log.warn(
221                                                                 "Exception for {}={}: {}",
222                                                                 record.key(),
223                                                                 record.value(),
224                                                                 e.toString());
225                                         }
226                                 });
227                         }
228                 }
229         }
230
231         Bytes serialize(Integer key, Long value)
232         {
233                 ClientMessage message = new ClientMessage();
234                 message.setClient(key.toString());
235                 message.setMessage(value.toString());
236                 return new Bytes(valueSerializer.serialize(TOPIC, message));
237         }
238
239
240         @BeforeEach
241         public void init()
242         {
243                 recordHandler.testHandler = (record) -> {};
244
245                 oldOffsets = new HashMap<>();
246                 newOffsets = new HashMap<>();
247                 receivedRecords = new HashSet<>();
248
249                 doForCurrentOffsets((tp, offset) ->
250                 {
251                         oldOffsets.put(tp, offset - 1);
252                         newOffsets.put(tp, offset - 1);
253                 });
254
255                 recordHandler.captureOffsets =
256                                 record ->
257                                 {
258                                         receivedRecords.add(record);
259                                         newOffsets.put(
260                                                         new TopicPartition(record.topic(), record.partition()),
261                                                         record.offset());
262                                 };
263
264                 endlessConsumer.start();
265         }
266
267         @AfterEach
268         public void deinit()
269         {
270                 try
271                 {
272                         endlessConsumer.stop();
273                 }
274                 catch (Exception e)
275                 {
276                         log.info("Exception while stopping the consumer: {}", e.toString());
277                 }
278         }
279
280         public static class RecordHandler implements Consumer<ConsumerRecord<String, ClientMessage>>
281         {
282                 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsets;
283                 Consumer<ConsumerRecord<String, ClientMessage>> testHandler;
284
285
286                 @Override
287                 public void accept(ConsumerRecord<String, ClientMessage> record)
288                 {
289                         captureOffsets
290                                         .andThen(testHandler)
291                                         .accept(record);
292                 }
293         }
294
295         @TestConfiguration
296         @Import(ApplicationConfiguration.class)
297         public static class Configuration
298         {
299                 @Primary
300                 @Bean
301                 public Consumer<ConsumerRecord<String, ClientMessage>> testHandler()
302                 {
303                         return new RecordHandler();
304                 }
305
306                 @Bean
307                 Serializer<ClientMessage> serializer()
308                 {
309                         return new JsonSerializer<>();
310                 }
311
312                 @Bean
313                 KafkaProducer<String, Bytes> kafkaProducer(KafkaProperties properties)
314                 {
315                         Properties props = new Properties();
316                         props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
317                         props.put("linger.ms", 100);
318                         props.put("key.serializer", StringSerializer.class.getName());
319                         props.put("value.serializer", BytesSerializer.class.getName());
320
321                         return new KafkaProducer<>(props);
322                 }
323
324                 @Bean
325                 KafkaConsumer<Bytes, Bytes> offsetConsumer(KafkaProperties properties)
326                 {
327                         Properties props = new Properties();
328                         props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
329                         props.put("client.id", "OFFSET-CONSUMER");
330                         props.put("group.id", properties.getConsumer().getGroupId());
331                         props.put("key.deserializer", BytesDeserializer.class.getName());
332                         props.put("value.deserializer", BytesDeserializer.class.getName());
333
334                         return new KafkaConsumer<>(props);
335                 }
336         }
337 }