fbc668ff2aa8491bedb4cbf7475747ef99291c37
[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                                 kafkaProducer.send(record, (metadata, e) ->
207                                 {
208                                         if (metadata != null)
209                                         {
210                                                 log.debug(
211                                                                 "{}|{} - {}={}",
212                                                                 metadata.partition(),
213                                                                 metadata.offset(),
214                                                                 record.key(),
215                                                                 record.value());
216                                         }
217                                         else
218                                         {
219                                                 log.warn(
220                                                                 "Exception for {}={}: {}",
221                                                                 record.key(),
222                                                                 record.value(),
223                                                                 e.toString());
224                                         }
225                                 });
226                         }
227                 }
228         }
229
230         Bytes serialize(Integer key, Long value)
231         {
232                 ClientMessage message = new ClientMessage();
233                 message.setClient(key.toString());
234                 message.setMessage(value.toString());
235                 return new Bytes(valueSerializer.serialize(TOPIC, message));
236         }
237
238
239         @BeforeEach
240         public void init()
241         {
242                 testHandler = record -> {} ;
243
244                 oldOffsets = new HashMap<>();
245                 newOffsets = new HashMap<>();
246                 receivedRecords = new HashSet<>();
247
248                 doForCurrentOffsets((tp, offset) ->
249                 {
250                         oldOffsets.put(tp, offset - 1);
251                         newOffsets.put(tp, offset - 1);
252                 });
253
254                 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsetAndExecuteTestHandler =
255                                 record ->
256                                 {
257                                         newOffsets.put(
258                                                         new TopicPartition(record.topic(), record.partition()),
259                                                         record.offset());
260                                         receivedRecords.add(record);
261                                         testHandler.accept(record);
262                                 };
263
264                 endlessConsumer =
265                                 new EndlessConsumer<>(
266                                                 executor,
267                                                 properties.getClientId(),
268                                                 properties.getTopic(),
269                                                 kafkaConsumer,
270                                                 captureOffsetAndExecuteTestHandler);
271
272                 endlessConsumer.start();
273         }
274
275         @AfterEach
276         public void deinit()
277         {
278                 try
279                 {
280                         endlessConsumer.stop();
281                 }
282                 catch (Exception e)
283                 {
284                         log.info("Exception while stopping the consumer: {}", e.toString());
285                 }
286         }
287
288
289         @TestConfiguration
290         @Import(ApplicationConfiguration.class)
291         public static class Configuration
292         {
293                 @Bean
294                 Serializer<ClientMessage> serializer()
295                 {
296                         return new JsonSerializer<>();
297                 }
298
299                 @Bean
300                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
301                 {
302                         Properties props = new Properties();
303                         props.put("bootstrap.servers", properties.getBootstrapServer());
304                         props.put("linger.ms", 100);
305                         props.put("key.serializer", StringSerializer.class.getName());
306                         props.put("value.serializer", BytesSerializer.class.getName());
307
308                         return new KafkaProducer<>(props);
309                 }
310
311                 @Bean
312                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
313                 {
314                         Properties props = new Properties();
315                         props.put("bootstrap.servers", properties.getBootstrapServer());
316                         props.put("client.id", "OFFSET-CONSUMER");
317                         props.put("group.id", properties.getGroupId());
318                         props.put("key.deserializer", BytesDeserializer.class.getName());
319                         props.put("value.deserializer", BytesDeserializer.class.getName());
320
321                         return new KafkaConsumer<>(props);
322                 }
323         }
324 }