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