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