a9cca100a9674be1ca491177e692da8b77e4013e
[demos/kafka/wordcount] / src / test / java / de / juplo / kafka / wordcount / query / QueryApplicationIT.java
1 package de.juplo.kafka.wordcount.query;
2
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
6 import org.apache.kafka.streams.state.Stores;
7 import org.junit.jupiter.api.BeforeAll;
8 import org.junit.jupiter.api.DisplayName;
9 import org.junit.jupiter.api.Test;
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
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.http.MediaType;
17 import org.springframework.kafka.core.KafkaTemplate;
18 import org.springframework.kafka.support.SendResult;
19 import org.springframework.kafka.test.context.EmbeddedKafka;
20 import org.springframework.test.web.servlet.MockMvc;
21 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
22
23 import java.nio.charset.StandardCharsets;
24 import java.time.Duration;
25 import java.util.concurrent.CompletableFuture;
26
27 import static de.juplo.kafka.wordcount.query.QueryStreamProcessor.STORE_NAME;
28 import static org.awaitility.Awaitility.await;
29 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
30
31
32 @SpringBootTest(
33                 properties = {
34                                 "spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer",
35                                 "spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer",
36                                 "spring.kafka.producer.properties.spring.json.type.mapping=userdata:de.juplo.kafka.wordcount.users.TestUserData,ranking:de.juplo.kafka.wordcount.top10.TestRanking",
37                                 "logging.level.root=WARN",
38                                 "logging.level.de.juplo=DEBUG",
39                                 "logging.level.org.apache.kafka.clients=INFO",
40                                 "logging.level.org.apache.kafka.streams=INFO",
41                                 "juplo.wordcount.query.bootstrap-server=${spring.embedded.kafka.brokers}",
42                                 "juplo.wordcount.query.users-input-topic=" + QueryApplicationIT.TOPIC_USERS,
43                                 "juplo.wordcount.query.ranking-input-topic=" + QueryApplicationIT.TOPIC_TOP10 })
44 @AutoConfigureMockMvc
45 @EmbeddedKafka(topics = { QueryApplicationIT.TOPIC_TOP10, QueryApplicationIT.TOPIC_USERS})
46 @Slf4j
47 public class QueryApplicationIT
48 {
49         public static final String TOPIC_TOP10 = "top10";
50         public static final String TOPIC_USERS = "users";
51
52
53         @Autowired
54         MockMvc mockMvc;
55         @Autowired
56         ObjectMapper objectMapper;
57         @Autowired
58         QueryStreamProcessor streamProcessor;
59
60
61         @BeforeAll
62         public static void testSendMessage(
63                         @Autowired KafkaTemplate<String, Object> kafkaTemplate)
64         {
65                 TestData
66                                 .getUsersMessages()
67                                 .forEach(kv -> flush(kafkaTemplate.send(TOPIC_USERS, kv.key, kv.value)));
68                 TestData
69                                 .getTop10Messages()
70                                 .forEach(kv -> flush(kafkaTemplate.send(TOPIC_TOP10, kv.key, kv.value)));
71         }
72
73         private static void flush(CompletableFuture<SendResult<String, Object>> future)
74         {
75                 try
76                 {
77                         SendResult<String, Object> result = future.get();
78                         log.info(
79                                         "Sent: {}={}, partition={}, offset={}",
80                                         result.getProducerRecord().key(),
81                                         result.getProducerRecord().value(),
82                                         result.getRecordMetadata().partition(),
83                                         result.getRecordMetadata().offset());
84                 }
85                 catch (Exception e)
86                 {
87                         throw new RuntimeException(e);
88                 }
89         }
90
91         @DisplayName("Await, that the expected state is visible in the state-store")
92         @Test
93         public void testAwaitExpectedStateInStore()
94         {
95                 await("The expected state is visible in the state-store")
96                                 .atMost(Duration.ofSeconds(5))
97                                 .untilAsserted(() -> TestData.assertExpectedState(user -> streamProcessor.getStore().get(user)));
98         }
99
100         @DisplayName("Await, that the expected state is queryable")
101         @Test
102         public void testAwaitExpectedStateIsQueryable()
103         {
104                 await("The expected state is queryable")
105                                 .atMost(Duration.ofSeconds(5))
106                                 .untilAsserted(() -> TestData.assertExpectedState(user -> requestUserRankingFor(user)));
107         }
108
109         private UserRanking requestUserRankingFor(String user)
110         {
111                 try
112                 {
113                         return objectMapper.readValue(
114                                         mockMvc
115                                                         .perform(MockMvcRequestBuilders.get("/{user}", user)
116                                                                         .contentType(MediaType.APPLICATION_JSON))
117                                                         .andExpect(status().isOk())
118                                                         .andReturn()
119                                                         .getResponse()
120                                                         .getContentAsString(StandardCharsets.UTF_8),
121                                         UserRanking.class);
122                 }
123                 catch (Exception e)
124                 {
125                         throw new RuntimeException(e);
126                 }
127         }
128
129         @TestConfiguration
130         static class Configuration
131         {
132                 @Primary
133                 @Bean
134                 KeyValueBytesStoreSupplier inMemoryStoreSupplier()
135                 {
136                         return Stores.inMemoryKeyValueStore(STORE_NAME);
137                 }
138         }
139 }