Tests: Test-Reihenfolge definiert, da das Topic nicht geleert wird
[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.WakeupException;
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.MethodOrderer;
15 import org.junit.jupiter.api.Order;
16 import org.junit.jupiter.api.Test;
17 import org.junit.jupiter.api.TestMethodOrder;
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
20 import org.springframework.boot.test.context.TestConfiguration;
21 import org.springframework.context.annotation.Bean;
22 import org.springframework.context.annotation.Import;
23 import org.springframework.kafka.test.context.EmbeddedKafka;
24 import org.springframework.test.context.TestPropertySource;
25 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
26
27 import java.util.*;
28 import java.util.concurrent.ExecutorService;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import java.util.stream.IntStream;
34
35 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
36 import static de.juplo.kafka.ApplicationTests.TOPIC;
37 import static org.assertj.core.api.Assertions.assertThat;
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         ApplicationProperties properties;
63         @Autowired
64         ExecutorService executor;
65
66
67         @Test
68         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
69         void commitsCurrentOffsetsOnSuccess()
70         {
71                 send100Messages(i ->  new Bytes(longSerializer.serialize(TOPIC, i)));
72
73                 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
74                 Map<Integer, Long> offsets = runEndlessConsumer(record ->
75                 {
76                         received.add(record);
77                         if (received.size() == 100)
78                                 throw new WakeupException();
79                 });
80
81                 check(offsets);
82         }
83
84         @Test
85         @Order(2)
86         void commitsNoOffsetsOnError()
87         {
88                 send100Messages(counter ->
89                                 counter == 77
90                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
91                                                 : new Bytes(longSerializer.serialize(TOPIC, counter)));
92
93                 Map<Integer, Long> oldOffsets = new HashMap<>();
94                 doForCurrentOffsets((tp, offset) -> oldOffsets.put(tp.partition(), offset -1));
95                 Map<Integer, Long> newOffsets = runEndlessConsumer((record) -> {});
96
97                 check(oldOffsets);
98         }
99
100
101         void send100Messages(Function<Long, Bytes> messageGenerator)
102         {
103                 long i = 0;
104
105                 for (int partition = 0; partition < 10; partition++)
106                 {
107                         for (int key = 0; key < 10; key++)
108                         {
109                                 Bytes value = messageGenerator.apply(++i);
110
111                                 ProducerRecord<String, Bytes> record =
112                                                 new ProducerRecord<>(
113                                                                 TOPIC,
114                                                                 partition,
115                                                                 Integer.toString(key%2),
116                                                                 value);
117
118                                 kafkaProducer.send(record, (metadata, e) ->
119                                 {
120                                         if (metadata != null)
121                                         {
122                                                 log.debug(
123                                                                 "{}|{} - {}={}",
124                                                                 metadata.partition(),
125                                                                 metadata.offset(),
126                                                                 record.key(),
127                                                                 record.value());
128                                         }
129                                         else
130                                         {
131                                                 log.warn(
132                                                                 "Exception for {}={}: {}",
133                                                                 record.key(),
134                                                                 record.value(),
135                                                                 e.toString());
136                                         }
137                                 });
138                         }
139                 }
140         }
141
142         Map<Integer, Long> runEndlessConsumer(Consumer<ConsumerRecord<String, Long>> consumer)
143         {
144                 Map<Integer, Long> offsets = new HashMap<>();
145                 doForCurrentOffsets((tp, offset) -> offsets.put(tp.partition(), offset -1));
146                 Consumer<ConsumerRecord<String, Long>> captureOffset = record -> offsets.put(record.partition(), record.offset());
147                 EndlessConsumer<String, Long> endlessConsumer =
148                                 new EndlessConsumer<>(
149                                                 executor,
150                                                 properties.getClientId(),
151                                                 properties.getTopic(),
152                                                 kafkaConsumer,
153                                                 captureOffset.andThen(consumer));
154
155                 endlessConsumer.run();
156
157                 return offsets;
158         }
159
160         List<TopicPartition> partitions()
161         {
162                 return
163                                 IntStream
164                                                 .range(0, PARTITIONS)
165                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
166                                                 .collect(Collectors.toList());
167         }
168
169         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
170         {
171                 kafkaConsumer.assign(partitions());
172                 partitions().forEach(tp -> consumer.accept(tp, kafkaConsumer.position(tp)));
173                 kafkaConsumer.unsubscribe();
174         }
175
176         void check(Map<Integer, Long> offsets)
177         {
178                 doForCurrentOffsets((tp, offset) ->
179                 {
180                         Long expected = offsets.get(tp.partition()) + 1;
181                         log.debug("Checking, if the offset for {} is {}", tp, expected);
182                         assertThat(offset).isEqualTo(expected);
183                 });
184         }
185
186
187         @TestConfiguration
188         @Import(ApplicationConfiguration.class)
189         public static class Configuration
190         {
191                 @Bean
192                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
193                 {
194                         Properties props = new Properties();
195                         props.put("bootstrap.servers", properties.getBootstrapServer());
196                         props.put("linger.ms", 100);
197                         props.put("key.serializer", StringSerializer.class.getName());
198                         props.put("value.serializer", BytesSerializer.class.getName());
199
200                         return new KafkaProducer<>(props);
201                 }
202         }
203 }