Tests: Der EndlessConsumer wird jetzt doch asynchron ausgeführt
[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.serialization.BytesDeserializer;
10 import org.apache.kafka.common.serialization.BytesSerializer;
11 import org.apache.kafka.common.serialization.LongSerializer;
12 import org.apache.kafka.common.serialization.StringSerializer;
13 import org.apache.kafka.common.utils.Bytes;
14 import org.junit.jupiter.api.*;
15 import org.springframework.beans.factory.annotation.Autowired;
16 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
17 import org.springframework.boot.test.context.TestConfiguration;
18 import org.springframework.context.annotation.Bean;
19 import org.springframework.context.annotation.Import;
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.concurrent.ExecutorService;
28 import java.util.function.BiConsumer;
29 import java.util.function.Consumer;
30 import java.util.function.Function;
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.assertThat;
37 import static org.awaitility.Awaitility.*;
38
39
40 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
41 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
42 @TestPropertySource(
43                 properties = {
44                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
45                                 "consumer.topic=" + TOPIC })
46 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
47 @Slf4j
48 class ApplicationTests
49 {
50         public static final String TOPIC = "FOO";
51         public static final int PARTITIONS = 10;
52
53
54         StringSerializer stringSerializer = new StringSerializer();
55         LongSerializer longSerializer = new LongSerializer();
56
57         @Autowired
58         KafkaProducer<String, Bytes> kafkaProducer;
59         @Autowired
60         KafkaConsumer<String, Long> kafkaConsumer;
61         @Autowired
62         KafkaConsumer<Bytes, Bytes> offsetConsumer;
63         @Autowired
64         ApplicationProperties properties;
65         @Autowired
66         ExecutorService executor;
67
68         Consumer<ConsumerRecord<String, Long>> testHandler;
69         EndlessConsumer<String, Long> endlessConsumer;
70         Map<TopicPartition, Long> oldOffsets;
71         Map<TopicPartition, Long> newOffsets;
72
73
74         @Test
75         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
76         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
77         {
78                 send100Messages(i ->  new Bytes(longSerializer.serialize(TOPIC, i)));
79
80                 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
81                 testHandler = record -> received.add(record);
82
83                 await("100 records received")
84                                 .atMost(Duration.ofSeconds(30))
85                                 .until(() -> received.size() >= 100);
86
87                 endlessConsumer.stop();
88
89                 checkSeenOffsetsForProgress();
90                 compareToCommitedOffsets(newOffsets);
91         }
92
93         @Test
94         @Order(2)
95         void commitsNoOffsetsOnError()
96         {
97                 send100Messages(counter ->
98                                 counter == 77
99                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
100                                                 : new Bytes(longSerializer.serialize(TOPIC, counter)));
101
102                 await("Consumer failed")
103                                 .atMost(Duration.ofSeconds(30))
104                                 .until(() -> !endlessConsumer.running());
105
106                 checkSeenOffsetsForProgress();
107                 compareToCommitedOffsets(oldOffsets);
108         }
109
110
111         void send100Messages(Function<Long, Bytes> messageGenerator)
112         {
113                 long i = 0;
114
115                 for (int partition = 0; partition < 10; partition++)
116                 {
117                         for (int key = 0; key < 10; key++)
118                         {
119                                 Bytes value = messageGenerator.apply(++i);
120
121                                 ProducerRecord<String, Bytes> record =
122                                                 new ProducerRecord<>(
123                                                                 TOPIC,
124                                                                 partition,
125                                                                 Integer.toString(key%2),
126                                                                 value);
127
128                                 kafkaProducer.send(record, (metadata, e) ->
129                                 {
130                                         if (metadata != null)
131                                         {
132                                                 log.debug(
133                                                                 "{}|{} - {}={}",
134                                                                 metadata.partition(),
135                                                                 metadata.offset(),
136                                                                 record.key(),
137                                                                 record.value());
138                                         }
139                                         else
140                                         {
141                                                 log.warn(
142                                                                 "Exception for {}={}: {}",
143                                                                 record.key(),
144                                                                 record.value(),
145                                                                 e.toString());
146                                         }
147                                 });
148                         }
149                 }
150         }
151
152         @BeforeEach
153         public void init()
154         {
155                 testHandler = record -> {} ;
156
157                 oldOffsets = new HashMap<>();
158                 newOffsets = new HashMap<>();
159
160                 doForCurrentOffsets((tp, offset) ->
161                 {
162                         oldOffsets.put(tp, offset - 1);
163                         newOffsets.put(tp, offset - 1);
164                 });
165
166                 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
167                                 record ->
168                                 {
169                                         newOffsets.put(
170                                                         new TopicPartition(record.topic(), record.partition()),
171                                                         record.offset());
172                                         testHandler.accept(record);
173                                 };
174
175                 endlessConsumer =
176                                 new EndlessConsumer<>(
177                                                 executor,
178                                                 properties.getClientId(),
179                                                 properties.getTopic(),
180                                                 kafkaConsumer,
181                                                 captureOffsetAndExecuteTestHandler);
182
183                 endlessConsumer.start();
184         }
185
186         List<TopicPartition> partitions()
187         {
188                 return
189                                 IntStream
190                                                 .range(0, PARTITIONS)
191                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
192                                                 .collect(Collectors.toList());
193         }
194
195         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
196         {
197                 offsetConsumer.assign(partitions());
198                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
199                 offsetConsumer.unsubscribe();
200         }
201
202         void checkSeenOffsetsForProgress()
203         {
204                 // Be sure, that some messages were consumed...!
205                 Set<TopicPartition> withProgress = new HashSet<>();
206                 partitions().forEach(tp ->
207                 {
208                         Long oldOffset = oldOffsets.get(tp);
209                         Long newOffset = newOffsets.get(tp);
210                         if (!oldOffset.equals(newOffset))
211                         {
212                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
213                                 withProgress.add(tp);
214                         }
215                 });
216                 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
217         }
218
219         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
220         {
221                 doForCurrentOffsets((tp, offset) ->
222                 {
223                         Long expected = offsetsToCheck.get(tp) + 1;
224                         log.debug("Checking, if the offset for {} is {}", tp, expected);
225                         assertThat(offset).isEqualTo(expected);
226                 });
227         }
228
229
230         @AfterEach
231         public void deinit()
232         {
233                 try
234                 {
235                         endlessConsumer.stop();
236                 }
237                 catch (Exception e)
238                 {
239                         log.info("Exception while stopping the consumer: {}", e.toString());
240                 }
241         }
242
243         @TestConfiguration
244         @Import(ApplicationConfiguration.class)
245         public static class Configuration
246         {
247                 @Bean
248                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
249                 {
250                         Properties props = new Properties();
251                         props.put("bootstrap.servers", properties.getBootstrapServer());
252                         props.put("linger.ms", 100);
253                         props.put("key.serializer", StringSerializer.class.getName());
254                         props.put("value.serializer", BytesSerializer.class.getName());
255
256                         return new KafkaProducer<>(props);
257                 }
258
259                 @Bean
260                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
261                 {
262                         Properties props = new Properties();
263                         props.put("bootstrap.servers", properties.getBootstrapServer());
264                         props.put("client.id", "OFFSET-CONSUMER");
265                         props.put("group.id", properties.getGroupId());
266                         props.put("key.deserializer", BytesDeserializer.class.getName());
267                         props.put("value.deserializer", BytesDeserializer.class.getName());
268
269                         return new KafkaConsumer<>(props);
270                 }
271         }
272 }