Refaktorisierungen des Testfalls gemerged (Branch 'deserialization')
[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.test.context.ConfigDataApplicationContextInitializer;
15 import org.springframework.boot.test.context.TestConfiguration;
16 import org.springframework.context.annotation.Bean;
17 import org.springframework.context.annotation.Import;
18 import org.springframework.kafka.support.serializer.JsonSerializer;
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.BiFunction;
29 import java.util.function.Consumer;
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                                 "consumer.bootstrap-server=${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, ClientMessage> kafkaConsumer;
61         @Autowired
62         KafkaConsumer<Bytes, Bytes> offsetConsumer;
63         @Autowired
64         ApplicationProperties properties;
65         @Autowired
66         ExecutorService executor;
67
68         Consumer<ConsumerRecord<String, ClientMessage>> testHandler;
69         EndlessConsumer<String, ClientMessage> endlessConsumer;
70         Map<TopicPartition, Long> oldOffsets;
71         Map<TopicPartition, Long> newOffsets;
72         Set<ConsumerRecord<String, ClientMessage>> receivedRecords;
73
74
75         /** Tests methods */
76
77         @Test
78         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
79         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
80         {
81                 send100Messages((partition, key, counter) ->
82                 {
83                         Bytes value = serialize(key, counter);
84                         return new ProducerRecord<>(TOPIC, partition, key, value);
85                 });
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((partition, key, counter) ->
109                 {
110                         Bytes value = counter == 77
111                                         ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
112                                         : serialize(key, counter);
113                         return new ProducerRecord<>(TOPIC, partition, key, value);
114                 });
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         public interface RecordGenerator<K, V>
197         {
198                 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
199         }
200
201         void send100Messages(RecordGenerator recordGenerator)
202         {
203                 long i = 0;
204
205                 for (int partition = 0; partition < 10; partition++)
206                 {
207                         for (int key = 0; key < 10; key++)
208                         {
209                                 ProducerRecord<String, Bytes> record =
210                                                 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
211
212                                 record.headers().add("__TypeId__", "message".getBytes());
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         Bytes serialize(String key, Long value)
238         {
239                 ClientMessage message = new ClientMessage();
240                 message.setClient(key);
241                 message.setMessage(value.toString());
242                 return new Bytes(valueSerializer.serialize(TOPIC, message));
243         }
244
245
246         @BeforeEach
247         public void init()
248         {
249                 testHandler = record -> {} ;
250
251                 oldOffsets = new HashMap<>();
252                 newOffsets = new HashMap<>();
253                 receivedRecords = new HashSet<>();
254
255                 doForCurrentOffsets((tp, offset) ->
256                 {
257                         oldOffsets.put(tp, offset - 1);
258                         newOffsets.put(tp, offset - 1);
259                 });
260
261                 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsetAndExecuteTestHandler =
262                                 record ->
263                                 {
264                                         newOffsets.put(
265                                                         new TopicPartition(record.topic(), record.partition()),
266                                                         record.offset());
267                                         receivedRecords.add(record);
268                                         testHandler.accept(record);
269                                 };
270
271                 endlessConsumer =
272                                 new EndlessConsumer<>(
273                                                 executor,
274                                                 properties.getClientId(),
275                                                 properties.getTopic(),
276                                                 kafkaConsumer,
277                                                 captureOffsetAndExecuteTestHandler);
278
279                 endlessConsumer.start();
280         }
281
282         @AfterEach
283         public void deinit()
284         {
285                 try
286                 {
287                         endlessConsumer.stop();
288                 }
289                 catch (Exception e)
290                 {
291                         log.info("Exception while stopping the consumer: {}", e.toString());
292                 }
293         }
294
295
296         @TestConfiguration
297         @Import(ApplicationConfiguration.class)
298         public static class Configuration
299         {
300                 @Bean
301                 Serializer<ClientMessage> serializer()
302                 {
303                         return new JsonSerializer<>();
304                 }
305
306                 @Bean
307                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
308                 {
309                         Properties props = new Properties();
310                         props.put("bootstrap.servers", properties.getBootstrapServer());
311                         props.put("linger.ms", 100);
312                         props.put("key.serializer", StringSerializer.class.getName());
313                         props.put("value.serializer", BytesSerializer.class.getName());
314
315                         return new KafkaProducer<>(props);
316                 }
317
318                 @Bean
319                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
320                 {
321                         Properties props = new Properties();
322                         props.put("bootstrap.servers", properties.getBootstrapServer());
323                         props.put("client.id", "OFFSET-CONSUMER");
324                         props.put("group.id", properties.getGroupId());
325                         props.put("key.deserializer", BytesDeserializer.class.getName());
326                         props.put("value.deserializer", BytesDeserializer.class.getName());
327
328                         return new KafkaConsumer<>(props);
329                 }
330         }
331 }