52ecc0f4d31056d693ab5a335f5113b3bece3351
[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.listener.MessageListenerContainer;
22 import org.springframework.kafka.support.serializer.JsonSerializer;
23 import org.springframework.kafka.test.context.EmbeddedKafka;
24 import org.springframework.test.context.TestPropertySource;
25 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
26
27 import java.time.Duration;
28 import java.util.*;
29 import java.util.concurrent.ExecutionException;
30 import java.util.function.BiConsumer;
31 import java.util.function.BiFunction;
32 import java.util.function.Consumer;
33 import java.util.stream.Collectors;
34 import java.util.stream.IntStream;
35
36 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
37 import static de.juplo.kafka.ApplicationTests.TOPIC;
38 import static org.assertj.core.api.Assertions.*;
39 import static org.awaitility.Awaitility.*;
40
41
42 @SpringJUnitConfig(
43                 initializers = ConfigDataApplicationContextInitializer.class,
44                 classes = {
45                                 EndlessConsumer.class,
46                                 KafkaAutoConfiguration.class,
47                                 ApplicationTests.Configuration.class })
48 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
49 @TestPropertySource(
50                 properties = {
51                                 "spring.kafka.consumer.bootstrap-servers=${spring.embedded.kafka.brokers}",
52                                 "spring.kafka.producer.bootstrap-servers=${spring.embedded.kafka.brokers}",
53                                 "consumer.topic=" + TOPIC })
54 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
55 @Slf4j
56 class ApplicationTests
57 {
58         public static final String TOPIC = "FOO";
59         public static final int PARTITIONS = 10;
60
61
62         StringSerializer stringSerializer = new StringSerializer();
63
64         @Autowired
65         Serializer valueSerializer;
66         @Autowired
67         KafkaProducer<String, Bytes> kafkaProducer;
68         @Autowired
69         org.apache.kafka.clients.consumer.Consumer<String, ClientMessage> kafkaConsumer;
70         @Autowired
71         KafkaConsumer<Bytes, Bytes> offsetConsumer;
72         @Autowired
73         ApplicationProperties applicationProperties;
74         @Autowired
75         KafkaProperties kafkaProperties;
76         @Autowired
77         EndlessConsumer endlessConsumer;
78         @Autowired
79         RecordHandler recordHandler;
80
81         Map<TopicPartition, Long> oldOffsets;
82         Map<TopicPartition, Long> newOffsets;
83         Set<ConsumerRecord<String, ClientMessage>> receivedRecords;
84
85
86         /** Tests methods */
87
88         @Test
89         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
90         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
91         {
92                 send100Messages((key, counter) -> serialize(key, counter));
93
94                 await("100 records received")
95                                 .atMost(Duration.ofSeconds(30))
96                                 .until(() -> receivedRecords.size() == 100);
97
98                 await("Offsets committed")
99                                 .atMost(Duration.ofSeconds(10))
100                                 .untilAsserted(() ->
101                                 {
102                                         checkSeenOffsetsForProgress();
103                                         compareToCommitedOffsets(newOffsets);
104                                 });
105
106                 assertThat(endlessConsumer.isRunning())
107                                 .describedAs("Consumer should still be running")
108                                 .isTrue();
109         }
110
111         @Test
112         @Order(2)
113         void commitsCurrentOffsetsOnError()
114         {
115                 send100Messages((key, counter) ->
116                                 counter == 77
117                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
118                                                 : serialize(key, counter));
119
120                 await("99 records received")
121                                 .atMost(Duration.ofSeconds(30))
122                                 .until(() -> receivedRecords.size() == 99);
123
124                 await("Offsets committed")
125                                 .atMost(Duration.ofSeconds(10))
126                                 .untilAsserted(() ->
127                                 {
128                                         // UNSCHÖN:
129                                         // Funktioniert nur, weil nach der Nachrichten, die den
130                                         // Deserialisierungs-Fehler auslöst noch valide Nachrichten
131                                         // gelesen werden.
132                                         // GRUND:
133                                         // Der MessageHandler sieht den Offset der Fehlerhaften
134                                         // Nachricht nicht!
135                                         checkSeenOffsetsForProgress();
136                                         compareToCommitedOffsets(newOffsets);
137                                 });
138
139                 assertThat(endlessConsumer.isRunning())
140                                 .describedAs("Consumer should still be running")
141                                 .isTrue();
142         }
143
144
145         /** Helper methods for the verification of expectations */
146
147         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
148         {
149                 doForCurrentOffsets((tp, offset) ->
150                 {
151                         Long expected = offsetsToCheck.get(tp) + 1;
152                         log.debug("Checking, if the offset for {} is {}", tp, expected);
153                         assertThat(offset)
154                                         .describedAs("Committed offset corresponds to the offset of the consumer")
155                                         .isEqualTo(expected);
156                 });
157         }
158
159         void checkSeenOffsetsForProgress()
160         {
161                 // Be sure, that some messages were consumed...!
162                 Set<TopicPartition> withProgress = new HashSet<>();
163                 partitions().forEach(tp ->
164                 {
165                         Long oldOffset = oldOffsets.get(tp);
166                         Long newOffset = newOffsets.get(tp);
167                         if (!oldOffset.equals(newOffset))
168                         {
169                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
170                                 withProgress.add(tp);
171                         }
172                 });
173                 assertThat(withProgress)
174                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
175                                 .isNotEmpty();
176         }
177
178
179         /** Helper methods for setting up and running the tests */
180
181         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
182         {
183                 offsetConsumer.assign(partitions());
184                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
185                 offsetConsumer.unsubscribe();
186         }
187
188         List<TopicPartition> partitions()
189         {
190                 return
191                                 IntStream
192                                                 .range(0, PARTITIONS)
193                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
194                                                 .collect(Collectors.toList());
195         }
196
197
198         void send100Messages(BiFunction<Integer, Long, Bytes> messageGenerator)
199         {
200                 long i = 0;
201
202                 for (int partition = 0; partition < 10; partition++)
203                 {
204                         for (int key = 0; key < 10; key++)
205                         {
206                                 Bytes value = messageGenerator.apply(key, ++i);
207
208                                 ProducerRecord<String, Bytes> record =
209                                                 new ProducerRecord<>(
210                                                                 TOPIC,
211                                                                 partition,
212                                                                 Integer.toString(key%2),
213                                                                 value);
214
215                                 record.headers().add("__TypeId__", "message".getBytes());
216                                 kafkaProducer.send(record, (metadata, e) ->
217                                 {
218                                         if (metadata != null)
219                                         {
220                                                 log.debug(
221                                                                 "{}|{} - {}={}",
222                                                                 metadata.partition(),
223                                                                 metadata.offset(),
224                                                                 record.key(),
225                                                                 record.value());
226                                         }
227                                         else
228                                         {
229                                                 log.warn(
230                                                                 "Exception for {}={}: {}",
231                                                                 record.key(),
232                                                                 record.value(),
233                                                                 e.toString());
234                                         }
235                                 });
236                         }
237                 }
238         }
239
240         Bytes serialize(Integer key, Long value)
241         {
242                 ClientMessage message = new ClientMessage();
243                 message.setClient(key.toString());
244                 message.setMessage(value.toString());
245                 return new Bytes(valueSerializer.serialize(TOPIC, message));
246         }
247
248
249         @BeforeEach
250         public void init()
251         {
252                 recordHandler.testHandler = (record) -> {};
253
254                 oldOffsets = new HashMap<>();
255                 newOffsets = new HashMap<>();
256                 receivedRecords = new HashSet<>();
257
258                 doForCurrentOffsets((tp, offset) ->
259                 {
260                         oldOffsets.put(tp, offset - 1);
261                         newOffsets.put(tp, offset - 1);
262                 });
263
264                 recordHandler.captureOffsets =
265                                 record ->
266                                 {
267                                         receivedRecords.add(record);
268                                         newOffsets.put(
269                                                         new TopicPartition(record.topic(), record.partition()),
270                                                         record.offset());
271                                 };
272
273                 endlessConsumer.start();
274         }
275
276         @AfterEach
277         public void deinit()
278         {
279                 try
280                 {
281                         endlessConsumer.stop();
282                 }
283                 catch (Exception e)
284                 {
285                         log.info("Exception while stopping the consumer: {}", e.toString());
286                 }
287         }
288
289         public static class RecordHandler implements Consumer<ConsumerRecord<String, ClientMessage>>
290         {
291                 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsets;
292                 Consumer<ConsumerRecord<String, ClientMessage>> testHandler;
293
294
295                 @Override
296                 public void accept(ConsumerRecord<String, ClientMessage> record)
297                 {
298                         captureOffsets
299                                         .andThen(testHandler)
300                                         .accept(record);
301                 }
302         }
303
304         @TestConfiguration
305         @Import(ApplicationConfiguration.class)
306         public static class Configuration
307         {
308                 @Primary
309                 @Bean
310                 public Consumer<ConsumerRecord<String, ClientMessage>> testHandler()
311                 {
312                         return new RecordHandler();
313                 }
314
315                 @Bean
316                 Serializer<ClientMessage> serializer()
317                 {
318                         return new JsonSerializer<>();
319                 }
320
321                 @Bean
322                 KafkaProducer<String, Bytes> kafkaProducer(KafkaProperties properties)
323                 {
324                         Properties props = new Properties();
325                         props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
326                         props.put("linger.ms", 100);
327                         props.put("key.serializer", StringSerializer.class.getName());
328                         props.put("value.serializer", BytesSerializer.class.getName());
329
330                         return new KafkaProducer<>(props);
331                 }
332
333                 @Bean
334                 KafkaConsumer<Bytes, Bytes> offsetConsumer(KafkaProperties properties)
335                 {
336                         Properties props = new Properties();
337                         props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
338                         props.put("client.id", "OFFSET-CONSUMER");
339                         props.put("group.id", properties.getConsumer().getGroupId());
340                         props.put("key.deserializer", BytesDeserializer.class.getName());
341                         props.put("value.deserializer", BytesDeserializer.class.getName());
342
343                         return new KafkaConsumer<>(props);
344                 }
345         }
346 }