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