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