top10: 1.2.1 - `TestData` uses faked foreign classes for input-/output data
[demos/kafka/wordcount] / src / test / java / de / juplo / kafka / wordcount / top10 / Top10ApplicationIT.java
1 package de.juplo.kafka.wordcount.top10;
2
3 import de.juplo.kafka.wordcount.counter.TestWord;
4 import de.juplo.kafka.wordcount.counter.TestCounter;
5 import de.juplo.kafka.wordcount.query.TestRanking;
6 import de.juplo.kafka.wordcount.query.TestUser;
7 import lombok.extern.slf4j.Slf4j;
8 import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
9 import org.apache.kafka.streams.state.Stores;
10 import org.junit.jupiter.api.*;
11 import org.springframework.beans.factory.annotation.Autowired;
12 import org.springframework.boot.test.context.SpringBootTest;
13 import org.springframework.boot.test.context.TestConfiguration;
14 import org.springframework.context.annotation.Bean;
15 import org.springframework.context.annotation.Primary;
16 import org.springframework.kafka.annotation.KafkaListener;
17 import org.springframework.kafka.core.KafkaTemplate;
18 import org.springframework.kafka.support.KafkaHeaders;
19 import org.springframework.kafka.support.SendResult;
20 import org.springframework.kafka.test.context.EmbeddedKafka;
21 import org.springframework.messaging.handler.annotation.Header;
22 import org.springframework.messaging.handler.annotation.Payload;
23 import org.springframework.util.LinkedMultiValueMap;
24 import org.springframework.util.MultiValueMap;
25
26 import java.time.Duration;
27 import java.util.stream.Stream;
28
29 import static de.juplo.kafka.wordcount.top10.Top10StreamProcessor.STORE_NAME;
30 import static org.awaitility.Awaitility.await;
31
32
33 @SpringBootTest(
34                 properties = {
35                                 "spring.kafka.producer.key-serializer=org.springframework.kafka.support.serializer.JsonSerializer",
36                                 "spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer",
37                                 "spring.kafka.producer.properties.spring.json.type.mapping=word:de.juplo.kafka.wordcount.counter.TestWord,counter:de.juplo.kafka.wordcount.counter.TestCounter",
38                                 "spring.kafka.consumer.auto-offset-reset=earliest",
39                                 "spring.kafka.consumer.key-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer",
40                                 "spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer",
41                                 "spring.kafka.consumer.properties.spring.json.use.type.headers=false",
42                                 "spring.kafka.consumer.properties.spring.json.key.default.type=de.juplo.kafka.wordcount.query.TestUser",
43                                 "spring.kafka.consumer.properties.spring.json.value.default.type=de.juplo.kafka.wordcount.query.TestRanking",
44                                 "logging.level.root=WARN",
45                                 "logging.level.de.juplo=DEBUG",
46                                 "logging.level.org.apache.kafka.clients=INFO",
47                                 "logging.level.org.apache.kafka.streams=INFO",
48                                 "juplo.wordcount.top10.bootstrap-server=${spring.embedded.kafka.brokers}",
49                                 "juplo.wordcount.top10.commit-interval=100",
50                                 "juplo.wordcount.top10.cacheMaxBytes=0",
51                                 "juplo.wordcount.top10.input-topic=" + Top10ApplicationIT.TOPIC_IN,
52                                 "juplo.wordcount.top10.output-topic=" + Top10ApplicationIT.TOPIC_OUT })
53 @EmbeddedKafka(topics = { Top10ApplicationIT.TOPIC_IN, Top10ApplicationIT.TOPIC_OUT })
54 @Slf4j
55 public class Top10ApplicationIT
56 {
57         public static final String TOPIC_IN = "in";
58         public static final String TOPIC_OUT = "out";
59
60         @Autowired
61         Consumer consumer;
62         @Autowired
63         Top10StreamProcessor streamProcessor;
64
65
66         @BeforeAll
67         public static void testSendMessage(
68                         @Autowired KafkaTemplate<TestWord, TestCounter> kafkaTemplate)
69         {
70                 Stream
71                                 .of(TestData.INPUT_MESSAGES)
72                                 .forEach(kv ->
73                                 {
74                                         try
75                                         {
76                                                 SendResult<TestWord, TestCounter> result = kafkaTemplate.send(TOPIC_IN, kv.key, kv.value).get();
77                                                 log.info(
78                                                                 "Sent: {}={}, partition={}, offset={}",
79                                                                 result.getProducerRecord().key(),
80                                                                 result.getProducerRecord().value(),
81                                                                 result.getRecordMetadata().partition(),
82                                                                 result.getRecordMetadata().offset());
83                                         }
84                                         catch (Exception e)
85                                         {
86                                                 throw new RuntimeException(e);
87                                         }
88                                 });
89         }
90
91         @DisplayName("Await the expected state in the state-store")
92         @Test
93         public void testAwaitExpectedState()
94         {
95                 await("Expected state")
96                                 .atMost(Duration.ofSeconds(5))
97                                 .untilAsserted(() -> TestData.assertExpectedState(streamProcessor.getStore()));
98         }
99
100         @DisplayName("Await the expected output messages")
101         @Test
102         @Disabled
103         public void testAwaitExpectedMessages()
104         {
105                 await("Expected messages")
106                                 .atMost(Duration.ofSeconds(5))
107                                 .untilAsserted(() -> TestData.assertExpectedMessages(consumer.getReceivedMessages()));
108         }
109
110         @DisplayName("Await the expected number of messages")
111         @Test
112         public void testAwaitExpectedNumberOfMessagesForUsers()
113         {
114                 await("Expected number of messages")
115                                 .atMost(Duration.ofSeconds(5))
116                                 .untilAsserted(() -> TestData.assertExpectedNumberOfMessagesForUsers(consumer.getReceivedMessages()));
117         }
118
119         @DisplayName("Await the expected final output messages")
120         @Test
121         public void testAwaitExpectedLastMessagesForUsers()
122         {
123                 await("Expected final output messages")
124                                 .atMost(Duration.ofSeconds(5))
125                                 .untilAsserted(() -> TestData.assertExpectedLastMessagesForUsers(consumer.getReceivedMessages()));
126         }
127
128
129         static class Consumer
130         {
131                 private final MultiValueMap<TestUser, TestRanking> received = new LinkedMultiValueMap<>();
132
133                 @KafkaListener(groupId = "TEST", topics = TOPIC_OUT)
134                 public synchronized void receive(
135                                 @Header(KafkaHeaders.RECEIVED_KEY) TestUser user,
136                                 @Payload TestRanking ranking)
137                 {
138                         log.debug("Received message: {} -> {}", user, ranking);
139                         received.add(user, ranking);
140                 }
141
142                 synchronized MultiValueMap<TestUser, TestRanking> getReceivedMessages()
143                 {
144                         return received;
145                 }
146         }
147
148         @TestConfiguration
149         static class Configuration
150         {
151                 @Bean
152                 Consumer consumer()
153                 {
154                         return new Consumer();
155                 }
156
157                 @Primary
158                 @Bean
159                 KeyValueBytesStoreSupplier inMemoryStoreSupplier()
160                 {
161                         return Stores.inMemoryKeyValueStore(STORE_NAME);
162                 }
163         }
164 }