Implementierung des Adders für SumUp
[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.*;
10 import org.apache.kafka.common.utils.Bytes;
11 import org.junit.jupiter.api.*;
12 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
14 import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
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.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.stream.Collectors;
29 import java.util.stream.IntStream;
30
31 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
32 import static de.juplo.kafka.ApplicationTests.TOPIC;
33 import static org.assertj.core.api.Assertions.*;
34 import static org.awaitility.Awaitility.*;
35
36
37 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
38 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
39 @TestPropertySource(
40                 properties = {
41                                 "sumup.adder.bootstrap-server=${spring.embedded.kafka.brokers}",
42                                 "sumup.adder.topic=" + TOPIC,
43                                 "sumup.adder.commit-interval=1s",
44                                 "spring.mongodb.embedded.version=4.4.13" })
45 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
46 @EnableAutoConfiguration
47 @AutoConfigureDataMongo
48 @Slf4j
49 class ApplicationTests
50 {
51         public static final String TOPIC = "FOO";
52         public static final int PARTITIONS = 10;
53
54
55         StringSerializer stringSerializer = new StringSerializer();
56
57         @Autowired
58         Serializer valueSerializer;
59         @Autowired
60         KafkaProducer<String, Bytes> kafkaProducer;
61         @Autowired
62         KafkaConsumer<String, String> kafkaConsumer;
63         @Autowired
64         KafkaConsumer<Bytes, Bytes> offsetConsumer;
65         @Autowired
66         PartitionStatisticsRepository partitionStatisticsRepository;
67         @Autowired
68         ApplicationProperties properties;
69         @Autowired
70         ExecutorService executor;
71         @Autowired
72         PartitionStatisticsRepository repository;
73         @Autowired
74         AdderRebalanceListener adderRebalanceListener;
75         @Autowired
76         AdderRecordHandler adderRecordHandler;
77
78         EndlessConsumer<String, String> endlessConsumer;
79         Map<TopicPartition, Long> oldOffsets;
80         Map<TopicPartition, Long> newOffsets;
81         Set<ConsumerRecord<String, String>> receivedRecords;
82
83
84         /** Tests methods */
85
86         @Test
87         @Disabled("Vorübergehend deaktivert, bis der Testfall angepasst ist")
88         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
89         {
90                 send100Messages((partition, key, counter) ->
91                 {
92                         Bytes value = new Bytes(valueSerializer.serialize(TOPIC, counter));
93                         return new ProducerRecord<>(TOPIC, partition, key, value);
94                 });
95
96                 await("100 records received")
97                                 .atMost(Duration.ofSeconds(30))
98                                 .pollInterval(Duration.ofSeconds(1))
99                                 .until(() -> receivedRecords.size() >= 100);
100
101                 await("Offsets committed")
102                                 .atMost(Duration.ofSeconds(10))
103                                 .pollInterval(Duration.ofSeconds(1))
104                                 .untilAsserted(() ->
105                                 {
106                                         checkSeenOffsetsForProgress();
107                                         compareToCommitedOffsets(newOffsets);
108                                 });
109
110                 assertThatExceptionOfType(IllegalStateException.class)
111                                 .isThrownBy(() -> endlessConsumer.exitStatus())
112                                 .describedAs("Consumer should still be running");
113         }
114
115
116         /** Helper methods for the verification of expectations */
117
118         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
119         {
120                 doForCurrentOffsets((tp, offset) ->
121                 {
122                         Long expected = offsetsToCheck.get(tp) + 1;
123                         log.debug("Checking, if the offset for {} is {}", tp, expected);
124                         assertThat(offset)
125                                         .describedAs("Committed offset corresponds to the offset of the consumer")
126                                         .isEqualTo(expected);
127                 });
128         }
129
130         void checkSeenOffsetsForProgress()
131         {
132                 // Be sure, that some messages were consumed...!
133                 Set<TopicPartition> withProgress = new HashSet<>();
134                 partitions().forEach(tp ->
135                 {
136                         Long oldOffset = oldOffsets.get(tp) + 1;
137                         Long newOffset = newOffsets.get(tp) + 1;
138                         if (!oldOffset.equals(newOffset))
139                         {
140                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
141                                 withProgress.add(tp);
142                         }
143                 });
144                 assertThat(withProgress)
145                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
146                                 .isNotEmpty();
147         }
148
149
150         /** Helper methods for setting up and running the tests */
151
152         void seekToEnd()
153         {
154                 offsetConsumer.assign(partitions());
155                 partitions().forEach(tp ->
156                 {
157                         Long offset = offsetConsumer.position(tp);
158                         log.info("New position for {}: {}", tp, offset);
159                         Integer partition = tp.partition();
160                         StateDocument document =
161                                         partitionStatisticsRepository
162                                                         .findById(partition.toString())
163                                                         .orElse(new StateDocument(partition));
164                         document.offset = offset;
165                         partitionStatisticsRepository.save(document);
166                 });
167                 offsetConsumer.unsubscribe();
168         }
169
170         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
171         {
172                 partitions().forEach(tp ->
173                 {
174                         String partition = Integer.toString(tp.partition());
175                         Optional<Long> offset = partitionStatisticsRepository.findById(partition).map(document -> document.offset);
176                         consumer.accept(tp, offset.orElse(0l));
177                 });
178         }
179
180         List<TopicPartition> partitions()
181         {
182                 return
183                                 IntStream
184                                                 .range(0, PARTITIONS)
185                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
186                                                 .collect(Collectors.toList());
187         }
188
189
190         public interface RecordGenerator<K, V>
191         {
192                 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
193         }
194
195         void send100Messages(RecordGenerator recordGenerator)
196         {
197                 long i = 0;
198
199                 for (int partition = 0; partition < 10; partition++)
200                 {
201                         for (int key = 0; key < 10; key++)
202                         {
203                                 ProducerRecord<String, Bytes> record =
204                                                 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
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
231         @BeforeEach
232         public void init()
233         {
234                 seekToEnd();
235
236                 oldOffsets = new HashMap<>();
237                 newOffsets = new HashMap<>();
238                 receivedRecords = new HashSet<>();
239
240                 doForCurrentOffsets((tp, offset) ->
241                 {
242                         oldOffsets.put(tp, offset - 1);
243                         newOffsets.put(tp, offset - 1);
244                 });
245
246                 TestRecordHandler<String, String> captureOffsetAndExecuteTestHandler =
247                                 new TestRecordHandler<String, String>(adderRecordHandler) {
248                                         @Override
249                                         public void onNewRecord(ConsumerRecord<String, String> record)
250                                         {
251                                                 newOffsets.put(
252                                                                 new TopicPartition(record.topic(), record.partition()),
253                                                                 record.offset());
254                                                 receivedRecords.add(record);
255                                         }
256                                 };
257
258                 endlessConsumer =
259                                 new EndlessConsumer<>(
260                                                 executor,
261                                                 properties.getClientId(),
262                                                 properties.getTopic(),
263                                                 kafkaConsumer,
264                                                 adderRebalanceListener,
265                                                 captureOffsetAndExecuteTestHandler);
266
267                 endlessConsumer.start();
268         }
269
270         @AfterEach
271         public void deinit()
272         {
273                 try
274                 {
275                         endlessConsumer.stop();
276                 }
277                 catch (Exception e)
278                 {
279                         log.info("Exception while stopping the consumer: {}", e.toString());
280                 }
281         }
282
283
284         @TestConfiguration
285         @Import(ApplicationConfiguration.class)
286         public static class Configuration
287         {
288                 @Bean
289                 Serializer<Long> serializer()
290                 {
291                         return new LongSerializer();
292                 }
293
294                 @Bean
295                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
296                 {
297                         Properties props = new Properties();
298                         props.put("bootstrap.servers", properties.getBootstrapServer());
299                         props.put("linger.ms", 100);
300                         props.put("key.serializer", StringSerializer.class.getName());
301                         props.put("value.serializer", BytesSerializer.class.getName());
302
303                         return new KafkaProducer<>(props);
304                 }
305
306                 @Bean
307                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
308                 {
309                         Properties props = new Properties();
310                         props.put("bootstrap.servers", properties.getBootstrapServer());
311                         props.put("client.id", "OFFSET-CONSUMER");
312                         props.put("enable.auto.commit", false);
313                         props.put("auto.offset.reset", "latest");
314                         props.put("key.deserializer", BytesDeserializer.class.getName());
315                         props.put("value.deserializer", BytesDeserializer.class.getName());
316
317                         return new KafkaConsumer<>(props);
318                 }
319         }
320 }