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