8461824159886ec396a53117f7d887e98affa9a9
[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<TopicPartition, 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<TopicPartition, Long> oldOffsets = new HashMap<>();
94                 doForCurrentOffsets((tp, offset) -> oldOffsets.put(tp, offset -1));
95                 Map<TopicPartition, 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<TopicPartition, Long> runEndlessConsumer(Consumer<ConsumerRecord<String, Long>> consumer)
143         {
144                 Map<TopicPartition, Long> offsets = new HashMap<>();
145                 doForCurrentOffsets((tp, offset) -> offsets.put(tp, offset -1));
146                 Consumer<ConsumerRecord<String, Long>> captureOffset =
147                                 record ->
148                                                 offsets.put(
149                                                                 new TopicPartition(record.topic(), record.partition()),
150                                                                 record.offset());
151                 EndlessConsumer<String, Long> endlessConsumer =
152                                 new EndlessConsumer<>(
153                                                 executor,
154                                                 properties.getClientId(),
155                                                 properties.getTopic(),
156                                                 kafkaConsumer,
157                                                 captureOffset.andThen(consumer));
158
159                 endlessConsumer.run();
160
161                 return offsets;
162         }
163
164         List<TopicPartition> partitions()
165         {
166                 return
167                                 IntStream
168                                                 .range(0, PARTITIONS)
169                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
170                                                 .collect(Collectors.toList());
171         }
172
173         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
174         {
175                 kafkaConsumer.assign(partitions());
176                 partitions().forEach(tp -> consumer.accept(tp, kafkaConsumer.position(tp)));
177                 kafkaConsumer.unsubscribe();
178         }
179
180         void check(Map<TopicPartition, Long> offsets)
181         {
182                 doForCurrentOffsets((tp, offset) ->
183                 {
184                         Long expected = offsets.get(tp) + 1;
185                         log.debug("Checking, if the offset for {} is {}", tp, expected);
186                         assertThat(offset).isEqualTo(expected);
187                 });
188         }
189
190
191         @TestConfiguration
192         @Import(ApplicationConfiguration.class)
193         public static class Configuration
194         {
195                 @Bean
196                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
197                 {
198                         Properties props = new Properties();
199                         props.put("bootstrap.servers", properties.getBootstrapServer());
200                         props.put("linger.ms", 100);
201                         props.put("key.serializer", StringSerializer.class.getName());
202                         props.put("value.serializer", BytesSerializer.class.getName());
203
204                         return new KafkaProducer<>(props);
205                 }
206         }
207 }