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