popular: 1.0.0 - Word are counted for hopping time-windows
[demos/kafka/wordcount] / src / test / java / de / juplo / kafka / wordcount / popular / PopularApplicationIT.java
1 package de.juplo.kafka.wordcount.popular;
2
3 import de.juplo.kafka.wordcount.splitter.InputUser;
4 import de.juplo.kafka.wordcount.splitter.InputWord;
5 import de.juplo.kafka.wordcount.stats.OutputWindowedWord;
6 import de.juplo.kafka.wordcount.stats.OutputWordCounter;
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.apache.kafka.streams.state.WindowBytesStoreSupplier;
11 import org.junit.jupiter.api.BeforeAll;
12 import org.junit.jupiter.api.DisplayName;
13 import org.junit.jupiter.api.Test;
14 import org.springframework.beans.factory.annotation.Autowired;
15 import org.springframework.boot.test.context.SpringBootTest;
16 import org.springframework.boot.test.context.TestConfiguration;
17 import org.springframework.context.annotation.Bean;
18 import org.springframework.kafka.annotation.KafkaListener;
19 import org.springframework.kafka.core.KafkaTemplate;
20 import org.springframework.kafka.support.KafkaHeaders;
21 import org.springframework.kafka.support.SendResult;
22 import org.springframework.kafka.test.context.EmbeddedKafka;
23 import org.springframework.messaging.handler.annotation.Header;
24 import org.springframework.messaging.handler.annotation.Payload;
25 import org.springframework.util.LinkedMultiValueMap;
26 import org.springframework.util.MultiValueMap;
27
28 import java.time.Duration;
29
30 import static de.juplo.kafka.wordcount.popular.PopularApplicationIT.TOPIC_IN;
31 import static de.juplo.kafka.wordcount.popular.PopularApplicationIT.TOPIC_OUT;
32 import static de.juplo.kafka.wordcount.popular.PopularStreamProcessor.KEY_VALUE_STORE_NAME;
33 import static de.juplo.kafka.wordcount.popular.PopularStreamProcessor.WINDOW_STORE_NAME;
34 import static org.awaitility.Awaitility.await;
35
36
37 @SpringBootTest(
38                 properties = {
39                                 "spring.main.allow-bean-definition-overriding=true",
40                                 "spring.kafka.producer.key-serializer=org.springframework.kafka.support.serializer.JsonSerializer",
41                                 "spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer",
42                                 "spring.kafka.producer.properties.spring.json.add.type.headers=false",
43                                 "spring.kafka.consumer.auto-offset-reset=earliest",
44                                 "spring.kafka.consumer.key-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer",
45                                 "spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer",
46                                 "spring.kafka.consumer.properties.spring.json.type.mapping=word:de.juplo.kafka.wordcount.stats.OutputWindowedWord,counter:de.juplo.kafka.wordcount.stats.OutputWordCounter",
47                                 "logging.level.root=WARN",
48                                 "logging.level.de.juplo=DEBUG",
49                                 "juplo.wordcount.popular.bootstrap-server=${spring.embedded.kafka.brokers}",
50                                 "juplo.wordcount.popular.commit-interval=100",
51                                 "juplo.wordcount.popular.cache-max-bytes=0",
52                                 "juplo.wordcount.popular.input-topic=" + TOPIC_IN,
53                                 "juplo.wordcount.popular.output-topic=" + TOPIC_OUT })
54 @EmbeddedKafka(topics = { TOPIC_IN, TOPIC_OUT })
55 @Slf4j
56 public class PopularApplicationIT
57 {
58         public static final String TOPIC_IN = "in";
59         public static final String TOPIC_OUT = "out";
60
61         @Autowired
62         Consumer consumer;
63         @Autowired
64         PopularStreamProcessor streamProcessor;
65
66
67         @BeforeAll
68         public static void testSendMessage(
69                         @Autowired KafkaTemplate<InputUser, InputWord> kafkaTemplate)
70         {
71                 TestData
72                                 .sendInputMessages((instant, kv) ->
73                                 {
74                                         try
75                                         {
76                                                 SendResult<InputUser, InputWord> result = kafkaTemplate.send(TOPIC_IN, null, instant.toEpochMilli(), 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 number of messages")
92         @Test
93         public void testAwaitExpectedNumberOfMessagesForUsers()
94         {
95                 await("Expected number of messages")
96                                 .atMost(Duration.ofSeconds(5))
97                                 .untilAsserted(() -> consumer.enforceAssertion(
98                                                 receivedMessages -> TestData.assertExpectedNumberOfMessagesForWord(receivedMessages)));
99         }
100
101         @DisplayName("Await the expected output messages")
102         @Test
103         void testSendMessage()
104         {
105                 await("Expected messages")
106                                 .atMost(Duration.ofSeconds(10))
107                                 .untilAsserted(() -> consumer.enforceAssertion(
108                                                 receivedMessages -> TestData.assertExpectedMessages(receivedMessages)));
109         }
110
111         @DisplayName("Await the expected final output messages")
112         @Test
113         public void testAwaitExpectedLastMessagesForWord()
114         {
115                 await("Expected final output messages")
116                                 .atMost(Duration.ofSeconds(5))
117                                 .untilAsserted(() -> consumer.enforceAssertion(
118                                                 receivedMessages -> TestData.assertExpectedLastMessagesForWord(receivedMessages)));
119         }
120
121         @DisplayName("Await the expected state in the state-store")
122         @Test
123         public void testAwaitExpectedState()
124         {
125                 await("Expected state")
126                                 .atMost(Duration.ofSeconds(5))
127                                 .untilAsserted(() -> TestData.assertExpectedState(streamProcessor.getStore()));
128         }
129
130
131         static class Consumer
132         {
133                 private final MultiValueMap<OutputWindowedWord, OutputWordCounter> received = new LinkedMultiValueMap<>();
134
135                 @KafkaListener(groupId = "TEST", topics = TOPIC_OUT)
136                 public synchronized void receive(
137                                 @Header(KafkaHeaders.RECEIVED_KEY) OutputWindowedWord word,
138                                 @Payload OutputWordCounter counter)
139                 {
140                         log.debug("Received message: {} -> {}", word, counter);
141                         received.add(word, counter);
142                 }
143
144                 synchronized void enforceAssertion(
145                                 java.util.function.Consumer<MultiValueMap<OutputWindowedWord, OutputWordCounter>> assertion)
146                 {
147                         assertion.accept(received);
148                 }
149         }
150
151         @TestConfiguration
152         static class Configuration
153         {
154                 @Bean
155                 Consumer consumer()
156                 {
157                         return new Consumer();
158                 }
159
160                 @Bean
161                 WindowBytesStoreSupplier windowBytesStoreSupplier()
162                 {
163                         return Stores.inMemoryWindowStore(
164                                         WINDOW_STORE_NAME,
165                                         Duration.ofSeconds(60),
166                                         Duration.ofSeconds(30),
167                                         false);
168                 }
169
170                 @Bean
171                 KeyValueBytesStoreSupplier keyValueBytesStoreSupplier()
172                 {
173                         return Stores.inMemoryKeyValueStore(KEY_VALUE_STORE_NAME);
174                 }
175         }
176 }