recorder: 1.1.2 - The `JsonSerializer` is used for serialization
[demos/kafka/wordcount] / src / test / java / de / juplo / kafka / wordcount / recorder / ApplicationTests.java
1 package de.juplo.kafka.wordcount.recorder;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.junit.jupiter.api.DisplayName;
5 import org.junit.jupiter.api.Test;
6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
8 import org.springframework.boot.test.context.SpringBootTest;
9 import org.springframework.boot.test.context.TestConfiguration;
10 import org.springframework.context.annotation.Bean;
11 import org.springframework.http.MediaType;
12 import org.springframework.kafka.annotation.KafkaListener;
13 import org.springframework.kafka.support.KafkaHeaders;
14 import org.springframework.kafka.test.context.EmbeddedKafka;
15 import org.springframework.messaging.handler.annotation.Header;
16 import org.springframework.messaging.handler.annotation.Payload;
17 import org.springframework.test.web.servlet.MockMvc;
18 import org.springframework.test.web.servlet.MvcResult;
19 import org.springframework.util.LinkedMultiValueMap;
20 import org.springframework.util.MultiValueMap;
21
22 import java.time.Duration;
23 import java.util.List;
24 import java.util.stream.Stream;
25
26 import static de.juplo.kafka.wordcount.recorder.ApplicationTests.TOPIC_OUT;
27 import static org.assertj.core.api.Assertions.assertThat;
28 import static org.awaitility.Awaitility.await;
29 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
30 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
31 import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
32 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
33 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
34
35
36 @SpringBootTest(
37                 properties = {
38                                 "spring.kafka.consumer.auto-offset-reset=earliest",
39                                 "spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer",
40                                 "spring.kafka.consumer.properties.spring.json.value.default.type=de.juplo.kafka.wordcount.recorder.RecordingData",
41                                 "spring.kafka.consumer.properties.spring.json.trusted.packages=de.juplo.kafka.wordcount.recorder",
42                                 "logging.level.root=WARN",
43                                 "logging.level.de.juplo=DEBUG",
44                                 "juplo.wordcount.recorder.bootstrap-server=${spring.embedded.kafka.brokers}",
45                                 "juplo.wordcount.recorder.topic=" + TOPIC_OUT })
46 @AutoConfigureMockMvc
47 @EmbeddedKafka(topics = { TOPIC_OUT })
48 @Slf4j
49 class ApplicationTests
50 {
51         static final String TOPIC_OUT = "out";
52
53         @Autowired
54         MockMvc mockMvc;
55         @Autowired
56         Consumer consumer;
57
58
59         @Test
60         @DisplayName("Posted messages are accepted and sent to Kafka")
61         void userMessagesAreAcceptedAndSentToKafka()
62         {
63                 MultiValueMap<String, RecordingData> recordings = new LinkedMultiValueMap<>();
64
65                 Stream
66                                 .of(
67                                                 new RecordingData("päter", "Hall° Wält?¢*&%€!"),
68                                                 new RecordingData("päter", "Hallo Welt!"),
69                                                 new RecordingData("klühs", "Müsch gäb's auch!"),
70                                                 new RecordingData("päter", "Boäh, echt! ß mal nä Nümmäh!"))
71                                 .forEach(recording ->
72                                 {
73                                         sendRedording(recording.getUser(), recording.getSentence());
74                                         recordings.add(recording.getUser(), recording);
75                                 });
76
77
78                 await("Received expected messages")
79                                 .atMost(Duration.ofSeconds(5))
80                                 .untilAsserted(() -> recordings.forEach((user, userRecordings) ->
81                                                 assertThat(consumer.receivedFor(user)).containsExactlyElementsOf(userRecordings)));
82         }
83
84         void sendRedording(String user, String sentence)
85         {
86                 try
87                 {
88                         MvcResult result = mockMvc
89                                         .perform(post("/{user}", user)
90                                                         .contentType(MediaType.TEXT_PLAIN)
91                                                         .content(sentence))
92                                         .andReturn();
93
94                         mockMvc.perform(asyncDispatch(result))
95                                         .andDo(print())
96                                         .andExpect(status().isOk())
97                                         .andExpect(jsonPath("$.username").value(user))
98                                         .andExpect(jsonPath("$.sentence").value(sentence));
99                 }
100                 catch (Exception e)
101                 {
102                         throw new RuntimeException(e);
103                 }
104         }
105
106
107         static class Consumer
108         {
109                 private final MultiValueMap<String, RecordingData> received = new LinkedMultiValueMap<>();
110
111                 @KafkaListener(groupId = "TEST", topics = TOPIC_OUT)
112                 public synchronized void receive(
113                                 @Header(KafkaHeaders.RECEIVED_KEY) String user,
114                                 @Payload RecordingData recording)
115                 {
116                         log.debug("Received message: {}={}", user, recording);
117                         received.add(user, recording);
118                 }
119
120                 synchronized List<RecordingData> receivedFor(String user)
121                 {
122                         return received.get(user);
123                 }
124         }
125
126         @TestConfiguration
127         static class Configuration
128         {
129                 @Bean
130                 Consumer consumer()
131                 {
132                         return new Consumer();
133                 }
134         }
135 }