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