Springify: Merge des verschärften Tests aus der Vanilla-Version
[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.assertj.core.api.OptionalAssert;
13 import org.junit.jupiter.api.*;
14 import org.springframework.beans.factory.annotation.Autowired;
15 import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
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.test.context.EmbeddedKafka;
22 import org.springframework.test.context.TestPropertySource;
23 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
24
25 import java.time.Duration;
26 import java.util.*;
27 import java.util.concurrent.ExecutionException;
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.*;
37 import static org.awaitility.Awaitility.*;
38
39
40 @SpringJUnitConfig(
41                 initializers = ConfigDataApplicationContextInitializer.class,
42     classes = {
43                                 EndlessConsumer.class,
44                                 KafkaAutoConfiguration.class,
45                                 ApplicationTests.Configuration.class })
46 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
47 @TestPropertySource(
48                 properties = {
49                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
50                                 "consumer.topic=" + TOPIC })
51 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
52 @Slf4j
53 class ApplicationTests
54 {
55         public static final String TOPIC = "FOO";
56         public static final int PARTITIONS = 10;
57
58
59         StringSerializer stringSerializer = new StringSerializer();
60
61         @Autowired
62         Serializer valueSerializer;
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         Set<ConsumerRecord<String, Long>> receivedRecords;
77
78
79         /** Tests methods */
80
81         @Test
82         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
83         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
84         {
85                 send100Messages(i ->  new Bytes(valueSerializer.serialize(TOPIC, i)));
86
87                 await("100 records received")
88                                 .atMost(Duration.ofSeconds(30))
89                                 .until(() -> receivedRecords.size() >= 100);
90
91                 await("Offsets committed")
92                                 .atMost(Duration.ofSeconds(10))
93                                 .untilAsserted(() ->
94                                 {
95                                         checkSeenOffsetsForProgress();
96                                         compareToCommitedOffsets(newOffsets);
97                                 });
98
99                 assertThatExceptionOfType(IllegalStateException.class)
100                                 .isThrownBy(() -> endlessConsumer.exitStatus())
101                                 .describedAs("Consumer should still be running");
102         }
103
104         @Test
105         @Order(2)
106         void commitsOffsetOfErrorForReprocessingOnError()
107         {
108                 send100Messages(counter ->
109                                 counter == 77
110                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
111                                                 : new Bytes(valueSerializer.serialize(TOPIC, counter)));
112
113                 await("Consumer failed")
114                                 .atMost(Duration.ofSeconds(30))
115                                 .untilAsserted(() -> checkSeenOffsetsForProgress());
116
117                 compareToCommitedOffsets(newOffsets);
118                 assertThat(receivedRecords.size())
119                                 .describedAs("Received not all sent events")
120                                 .isLessThan(100);
121
122                 assertThatNoException()
123                                 .describedAs("Consumer should not be running")
124                                 .isThrownBy(() -> endlessConsumer.exitStatus());
125                 ((OptionalAssert<Exception>)assertThat(endlessConsumer.exitStatus()))
126                                 .describedAs("Consumer should have exited abnormally")
127                                 .containsInstanceOf(RecordDeserializationException.class);
128         }
129
130
131         /** Helper methods for the verification of expectations */
132
133         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
134         {
135                 doForCurrentOffsets((tp, offset) ->
136                 {
137                         Long expected = offsetsToCheck.get(tp) + 1;
138                         log.debug("Checking, if the offset for {} is {}", tp, expected);
139                         assertThat(offset)
140                                         .describedAs("Committed offset corresponds to the offset of the consumer")
141                                         .isEqualTo(expected);
142                 });
143         }
144
145         void checkSeenOffsetsForProgress()
146         {
147                 // Be sure, that some messages were consumed...!
148                 Set<TopicPartition> withProgress = new HashSet<>();
149                 partitions().forEach(tp ->
150                 {
151                         Long oldOffset = oldOffsets.get(tp);
152                         Long newOffset = newOffsets.get(tp);
153                         if (!oldOffset.equals(newOffset))
154                         {
155                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
156                                 withProgress.add(tp);
157                         }
158                 });
159                 assertThat(withProgress)
160                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
161                                 .isNotEmpty();
162         }
163
164
165         /** Helper methods for setting up and running the tests */
166
167         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
168         {
169                 offsetConsumer.assign(partitions());
170                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
171                 offsetConsumer.unsubscribe();
172         }
173
174         List<TopicPartition> partitions()
175         {
176                 return
177                                 IntStream
178                                                 .range(0, PARTITIONS)
179                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
180                                                 .collect(Collectors.toList());
181         }
182
183
184         void send100Messages(Function<Long, Bytes> messageGenerator)
185         {
186                 long i = 0;
187
188                 for (int partition = 0; partition < 10; partition++)
189                 {
190                         for (int key = 0; key < 10; key++)
191                         {
192                                 Bytes value = messageGenerator.apply(++i);
193
194                                 ProducerRecord<String, Bytes> record =
195                                                 new ProducerRecord<>(
196                                                                 TOPIC,
197                                                                 partition,
198                                                                 Integer.toString(key%2),
199                                                                 value);
200
201                                 kafkaProducer.send(record, (metadata, e) ->
202                                 {
203                                         if (metadata != null)
204                                         {
205                                                 log.debug(
206                                                                 "{}|{} - {}={}",
207                                                                 metadata.partition(),
208                                                                 metadata.offset(),
209                                                                 record.key(),
210                                                                 record.value());
211                                         }
212                                         else
213                                         {
214                                                 log.warn(
215                                                                 "Exception for {}={}: {}",
216                                                                 record.key(),
217                                                                 record.value(),
218                                                                 e.toString());
219                                         }
220                                 });
221                         }
222                 }
223         }
224
225
226         @BeforeEach
227         public void init()
228         {
229                 recordHandler.testHandler = (record) -> {};
230
231                 oldOffsets = new HashMap<>();
232                 newOffsets = new HashMap<>();
233                 receivedRecords = new HashSet<>();
234
235                 doForCurrentOffsets((tp, offset) ->
236                 {
237                         oldOffsets.put(tp, offset - 1);
238                         newOffsets.put(tp, offset - 1);
239                 });
240
241                 recordHandler.captureOffsets =
242                                 record ->
243                                 {
244                                         receivedRecords.add(record);
245                                         newOffsets.put(
246                                                         new TopicPartition(record.topic(), record.partition()),
247                                                         record.offset());
248                                 };
249
250                 endlessConsumer.start();
251         }
252
253         @AfterEach
254         public void deinit()
255         {
256                 try
257                 {
258                         endlessConsumer.stop();
259                 }
260                 catch (Exception e)
261                 {
262                         log.info("Exception while stopping the consumer: {}", e.toString());
263                 }
264         }
265
266         public static class RecordHandler implements Consumer<ConsumerRecord<String, Long>>
267         {
268                 Consumer<ConsumerRecord<String, Long>> captureOffsets;
269                 Consumer<ConsumerRecord<String, Long>> testHandler;
270
271
272                 @Override
273                 public void accept(ConsumerRecord<String, Long> record)
274                 {
275                         captureOffsets
276                                         .andThen(testHandler)
277                                         .accept(record);
278                 }
279         }
280
281         @TestConfiguration
282         @Import(ApplicationConfiguration.class)
283         public static class Configuration
284         {
285                 @Primary
286                 @Bean
287                 public Consumer<ConsumerRecord<String, Long>> testHandler()
288                 {
289                         return new RecordHandler();
290                 }
291
292                 @Bean
293                 Serializer<Long> serializer()
294                 {
295                         return new LongSerializer();
296                 }
297
298                 @Bean
299                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
300                 {
301                         Properties props = new Properties();
302                         props.put("bootstrap.servers", properties.getBootstrapServer());
303                         props.put("linger.ms", 100);
304                         props.put("key.serializer", StringSerializer.class.getName());
305                         props.put("value.serializer", BytesSerializer.class.getName());
306
307                         return new KafkaProducer<>(props);
308                 }
309
310                 @Bean
311                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
312                 {
313                         Properties props = new Properties();
314                         props.put("bootstrap.servers", properties.getBootstrapServer());
315                         props.put("client.id", "OFFSET-CONSUMER");
316                         props.put("group.id", properties.getGroupId());
317                         props.put("key.deserializer", BytesDeserializer.class.getName());
318                         props.put("value.deserializer", BytesDeserializer.class.getName());
319
320                         return new KafkaConsumer<>(props);
321                 }
322         }
323 }