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