counter: 1.2.15 - Added assertion for the expected final output messages
[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.TestInputWord;
4 import de.juplo.kafka.wordcount.top10.TestOutputWord;
5 import de.juplo.kafka.wordcount.top10.TestOutputWordCounter;
6 import lombok.extern.slf4j.Slf4j;
7 import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
8 import org.apache.kafka.streams.state.Stores;
9 import org.junit.jupiter.api.BeforeAll;
10 import org.junit.jupiter.api.DisplayName;
11 import org.junit.jupiter.api.Test;
12 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.boot.test.context.SpringBootTest;
14 import org.springframework.boot.test.context.TestConfiguration;
15 import org.springframework.context.annotation.Bean;
16 import org.springframework.context.annotation.Primary;
17 import org.springframework.kafka.annotation.KafkaListener;
18 import org.springframework.kafka.core.KafkaTemplate;
19 import org.springframework.kafka.support.KafkaHeaders;
20 import org.springframework.kafka.support.SendResult;
21 import org.springframework.kafka.test.context.EmbeddedKafka;
22 import org.springframework.messaging.handler.annotation.Header;
23 import org.springframework.messaging.handler.annotation.Payload;
24 import org.springframework.util.LinkedMultiValueMap;
25 import org.springframework.util.MultiValueMap;
26
27 import java.time.Duration;
28
29 import static de.juplo.kafka.wordcount.counter.CounterApplicationIT.TOPIC_IN;
30 import static de.juplo.kafka.wordcount.counter.CounterApplicationIT.TOPIC_OUT;
31 import static org.awaitility.Awaitility.await;
32
33
34 @SpringBootTest(
35                 properties = {
36                                 "spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer",
37                                 "spring.kafka.producer.properties.spring.json.add.type.headers=false",
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.type.mapping=word:de.juplo.kafka.wordcount.top10.TestOutputWord,counter:de.juplo.kafka.wordcount.top10.TestOutputWordCounter",
42                                 "logging.level.root=WARN",
43                                 "logging.level.de.juplo=DEBUG",
44                                 "juplo.wordcount.counter.bootstrap-server=${spring.embedded.kafka.brokers}",
45                                 "juplo.wordcount.counter.commit-interval=0",
46                                 "juplo.wordcount.counter.cacheMaxBytes=0",
47                                 "juplo.wordcount.counter.input-topic=" + TOPIC_IN,
48                                 "juplo.wordcount.counter.output-topic=" + TOPIC_OUT })
49 @EmbeddedKafka(topics = { TOPIC_IN, TOPIC_OUT })
50 @Slf4j
51 public class CounterApplicationIT
52 {
53         public static final String TOPIC_IN = "in";
54         public static final String TOPIC_OUT = "out";
55
56         @Autowired
57         Consumer consumer;
58
59
60         @BeforeAll
61         public static void testSendMessage(
62                         @Autowired KafkaTemplate<String, TestInputWord> kafkaTemplate)
63         {
64                 TestData
65                                 .getInputMessages()
66                                 .forEach(kv ->
67                                 {
68                                         try
69                                         {
70                                                 SendResult<String, TestInputWord> result = kafkaTemplate.send(TOPIC_IN, kv.key, kv.value).get();
71                                                 log.info(
72                                                                 "Sent: {}={}, partition={}, offset={}",
73                                                                 result.getProducerRecord().key(),
74                                                                 result.getProducerRecord().value(),
75                                                                 result.getRecordMetadata().partition(),
76                                                                 result.getRecordMetadata().offset());
77                                         }
78                                         catch (Exception e)
79                                         {
80                                                 throw new RuntimeException(e);
81                                         }
82                                 });
83         }
84
85         @DisplayName("Await the expected number of messages")
86         @Test
87         public void testAwaitExpectedNumberOfMessagesForUsers()
88         {
89                 await("Expected number of messages")
90                                 .atMost(Duration.ofSeconds(5))
91                                 .untilAsserted(() -> consumer.enforceAssertion(TestData.expectedNumberOfMessagesForWordAssertion()));
92         }
93
94         @DisplayName("Await the expected output messages")
95         @Test
96         void testSendMessage()
97         {
98                 await("Expected messages")
99                                 .atMost(Duration.ofSeconds(10))
100                                 .untilAsserted(() -> consumer.enforceAssertion(TestData.expectedMessagesAssertion()));
101         }
102
103         @DisplayName("Await the expected final output messages")
104         @Test
105         public void testAwaitExpectedLastMessagesForUsers()
106         {
107                 await("Expected final output messages")
108                                 .atMost(Duration.ofSeconds(5))
109                                 .untilAsserted(() -> consumer.enforceAssertion(TestData.expectedLastMessagesForWordAssertion()));
110         }
111
112
113         static class Consumer
114         {
115                 private final MultiValueMap<TestOutputWord, TestOutputWordCounter> received = new LinkedMultiValueMap<>();
116
117                 @KafkaListener(groupId = "TEST", topics = TOPIC_OUT)
118                 public synchronized void receive(
119                                 @Header(KafkaHeaders.RECEIVED_KEY) TestOutputWord word,
120                                 @Payload TestOutputWordCounter counter)
121                 {
122                         log.debug("Received message: {} -> {}", word, counter);
123                         received.add(word, counter);
124                 }
125
126                 synchronized void enforceAssertion(
127                                 java.util.function.Consumer<MultiValueMap<TestOutputWord, TestOutputWordCounter>> assertion)
128                 {
129                         assertion.accept(received);
130                 }
131         }
132
133         @TestConfiguration
134         static class Configuration
135         {
136                 @Bean
137                 Consumer consumer()
138                 {
139                         return new Consumer();
140                 }
141
142                 @Primary
143                 @Bean
144                 KeyValueBytesStoreSupplier inMemoryStoreSupplier()
145                 {
146                         return Stores.inMemoryKeyValueStore("TEST-STORE");
147                 }
148         }
149 }