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