refactor: Moved exceptions into package `exceptions` - Aligned Code
[demos/kafka/chat] / src / test / java / de / juplo / kafka / chat / backend / api / ChatBackendControllerTest.java
1 package de.juplo.kafka.chat.backend.api;
2
3 import de.juplo.kafka.chat.backend.ChatBackendProperties;
4 import de.juplo.kafka.chat.backend.domain.*;
5 import de.juplo.kafka.chat.backend.domain.exceptions.ShardNotOwnedException;
6 import de.juplo.kafka.chat.backend.domain.exceptions.UnknownChatroomException;
7 import lombok.extern.slf4j.Slf4j;
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.reactive.AutoConfigureWebTestClient;
12 import org.springframework.boot.test.context.SpringBootTest;
13 import org.springframework.boot.test.mock.mockito.MockBean;
14 import org.springframework.http.MediaType;
15 import org.springframework.test.web.reactive.server.WebTestClient;
16 import reactor.core.publisher.Mono;
17
18 import java.time.Clock;
19 import java.time.LocalDateTime;
20 import java.util.UUID;
21
22 import static org.mockito.ArgumentMatchers.any;
23 import static org.mockito.Mockito.*;
24
25
26 @SpringBootTest(properties = {
27     "spring.main.allow-bean-definition-overriding=true",
28     })
29 @AutoConfigureWebTestClient
30 @Slf4j
31 public class ChatBackendControllerTest
32 {
33   @Autowired
34   ChatBackendProperties properties;
35
36   @MockBean
37   ChatHome chatHome;
38   @MockBean
39   ChatRoomService chatRoomService;
40
41   @Test
42   @DisplayName("Assert expected problem-details for unknown chatroom on GET /list/{chatroomId}")
43   void testUnknownChatroomExceptionForListChatroom(@Autowired WebTestClient client)
44   {
45     // Given
46     UUID chatroomId = UUID.randomUUID();
47     when(chatHome.getChatRoomData(eq(chatroomId))).thenThrow(new UnknownChatroomException(chatroomId));
48
49     // When
50     WebTestClient.ResponseSpec responseSpec = client
51         .get()
52         .uri("/{chatroomId}/list", chatroomId)
53         .accept(MediaType.APPLICATION_JSON)
54         .exchange();
55
56     // Then
57     assertProblemDetailsForUnknownChatroomException(responseSpec, chatroomId);
58   }
59
60
61   @Test
62   @DisplayName("Assert expected problem-details for unknown chatroom on GET /get/{chatroomId}")
63   void testUnknownChatroomExceptionForGetChatroom(@Autowired WebTestClient client)
64   {
65     // Given
66     UUID chatroomId = UUID.randomUUID();
67     when(chatHome.getChatRoomInfo(eq(chatroomId))).thenThrow(new UnknownChatroomException(chatroomId));
68
69     // When
70     WebTestClient.ResponseSpec responseSpec = client
71         .get()
72         .uri("/{chatroomId}", chatroomId)
73         .accept(MediaType.APPLICATION_JSON)
74         .exchange();
75
76     // Then
77     assertProblemDetailsForUnknownChatroomException(responseSpec, chatroomId);
78   }
79
80   @Test
81   @DisplayName("Assert expected problem-details for unknown chatroom on PUT /put/{chatroomId}/{username}/{messageId}")
82   void testUnknownChatroomExceptionForPutMessage(@Autowired WebTestClient client)
83   {
84     // Given
85     UUID chatroomId = UUID.randomUUID();
86     String username = "foo";
87     Long messageId = 66l;
88     when(chatHome.getChatRoomData(eq(chatroomId))).thenThrow(new UnknownChatroomException(chatroomId));
89
90     // When
91     WebTestClient.ResponseSpec responseSpec = client
92         .put()
93         .uri(
94             "/{chatroomId}/{username}/{messageId}",
95             chatroomId,
96             username,
97             messageId)
98         .bodyValue("bar")
99         .accept(MediaType.APPLICATION_JSON)
100         .exchange();
101
102     // Then
103     assertProblemDetailsForUnknownChatroomException(responseSpec, chatroomId);
104   }
105
106   @Test
107   @DisplayName("Assert expected problem-details for unknown chatroom on GET /get/{chatroomId}/{username}/{messageId}")
108   void testUnknownChatroomExceptionForGetMessage(@Autowired WebTestClient client)
109   {
110     // Given
111     UUID chatroomId = UUID.randomUUID();
112     String username = "foo";
113     Long messageId = 66l;
114     when(chatHome.getChatRoomData(eq(chatroomId))).thenThrow(new UnknownChatroomException(chatroomId));
115
116     // When
117     WebTestClient.ResponseSpec responseSpec = client
118         .get()
119         .uri(
120             "/{chatroomId}/{username}/{messageId}",
121             chatroomId,
122             username,
123             messageId)
124         .accept(MediaType.APPLICATION_JSON)
125         .exchange();
126
127     // Then
128     assertProblemDetailsForUnknownChatroomException(responseSpec, chatroomId);
129   }
130
131   @Test
132   @DisplayName("Assert expected problem-details for unknown chatroom on GET /listen/{chatroomId}")
133   void testUnknownChatroomExceptionForListenChatroom(@Autowired WebTestClient client)
134   {
135     // Given
136     UUID chatroomId = UUID.randomUUID();
137     when(chatHome.getChatRoomData(eq(chatroomId))).thenThrow(new UnknownChatroomException(chatroomId));
138
139     // When
140     WebTestClient.ResponseSpec responseSpec = client
141         .get()
142         .uri("/{chatroomId}/listen", chatroomId)
143         // .accept(MediaType.TEXT_EVENT_STREAM, MediaType.APPLICATION_JSON) << TODO: Does not work!
144         .exchange();
145
146     // Then
147     assertProblemDetailsForUnknownChatroomException(responseSpec, chatroomId);
148   }
149
150   private void assertProblemDetailsForUnknownChatroomException(
151       WebTestClient.ResponseSpec responseSpec,
152       UUID chatroomId)
153   {
154     responseSpec
155         .expectStatus().isNotFound()
156         .expectBody()
157         .jsonPath("$.type").isEqualTo("/problem/unknown-chatroom")
158         .jsonPath("$.chatroomId").isEqualTo(chatroomId.toString());
159   }
160
161   @Test
162   @DisplayName("Assert expected problem-details for message mutation on PUT /put/{chatroomId}/{username}/{messageId}")
163   void testMessageMutationException(@Autowired WebTestClient client)
164   {
165     // Given
166     UUID chatroomId = UUID.randomUUID();
167     String user = "foo";
168     Long messageId = 66l;
169     Message.MessageKey key = Message.MessageKey.of(user, messageId);
170     Long serialNumberExistingMessage = 0l;
171     String timeExistingMessageAsString = "2023-01-09T20:44:57.389665447";
172     LocalDateTime timeExistingMessage = LocalDateTime.parse(timeExistingMessageAsString);
173     String textExistingMessage = "Existing";
174     String textMutatedMessage = "Mutated!";
175     ChatRoomData chatRoomData = new ChatRoomData(
176         Clock.systemDefaultZone(),
177         chatRoomService,
178         8);
179     when(chatHome.getChatRoomData(eq(chatroomId))).thenReturn(Mono.just(chatRoomData));
180     Message existingMessage = new Message(
181         key,
182         serialNumberExistingMessage,
183         timeExistingMessage,
184         textExistingMessage);
185     when(chatRoomService.getMessage(any(Message.MessageKey.class)))
186         .thenReturn(Mono.just(existingMessage));
187     // Needed for readable error-reports, in case of a bug that leads to according unwanted call
188     when(chatRoomService.persistMessage(any(Message.MessageKey.class), any(LocalDateTime.class), any(String.class)))
189         .thenReturn(Mono.just(mock(Message.class)));
190
191     // When
192     client
193         .put()
194         .uri(
195             "/{chatroomId}/{username}/{messageId}",
196             chatroomId,
197             user,
198             messageId)
199         .bodyValue(textMutatedMessage)
200         .accept(MediaType.APPLICATION_JSON)
201         .exchange()
202         // Then
203         .expectStatus().is4xxClientError()
204         .expectBody()
205         .jsonPath("$.type").isEqualTo("/problem/message-mutation")
206         .jsonPath("$.existingMessage.id").isEqualTo(messageId)
207         .jsonPath("$.existingMessage.serial").isEqualTo(serialNumberExistingMessage)
208         .jsonPath("$.existingMessage.time").isEqualTo(timeExistingMessageAsString)
209         .jsonPath("$.existingMessage.user").isEqualTo(user)
210         .jsonPath("$.existingMessage.text").isEqualTo(textExistingMessage)
211         .jsonPath("$.mutatedText").isEqualTo(textMutatedMessage);
212     verify(chatRoomService, never()).persistMessage(eq(key), any(LocalDateTime.class), any(String.class));
213   }
214
215   @Test
216   @DisplayName("Assert expected problem-details for invalid username on PUT /put/{chatroomId}/{username}/{messageId}")
217   void testInvalidUsernameException(@Autowired WebTestClient client)
218   {
219     // Given
220     UUID chatroomId = UUID.randomUUID();
221     String user = "Foo";
222     Long messageId = 66l;
223     Message.MessageKey key = Message.MessageKey.of(user, messageId);
224     String textMessage = "Hallo Welt";
225     ChatRoomData chatRoomData = new ChatRoomData(
226         Clock.systemDefaultZone(),
227         chatRoomService,
228         8);
229     when(chatHome.getChatRoomData(any(UUID.class)))
230         .thenReturn(Mono.just(chatRoomData));
231     when(chatRoomService.getMessage(any(Message.MessageKey.class)))
232         .thenReturn(Mono.empty());
233     // Needed for readable error-reports, in case of a bug that leads to according unwanted call
234     when(chatRoomService.persistMessage(any(Message.MessageKey.class), any(LocalDateTime.class), any(String.class)))
235         .thenReturn(Mono.just(mock(Message.class)));
236
237     // When
238     client
239         .put()
240         .uri(
241             "/{chatroomId}/{username}/{messageId}",
242             chatroomId,
243             user,
244             messageId)
245         .bodyValue(textMessage)
246         .accept(MediaType.APPLICATION_JSON)
247         .exchange()
248         // Then
249         .expectStatus().is4xxClientError()
250         .expectBody()
251         .jsonPath("$.type").isEqualTo("/problem/invalid-username")
252         .jsonPath("$.username").isEqualTo(user);
253     verify(chatRoomService, never()).persistMessage(eq(key), any(LocalDateTime.class), any(String.class));
254   }
255
256   @Test
257   @DisplayName("Assert expected problem-details for not owned shard on GET /{chatroomId}")
258   void testShardNotOwnedExceptionForGetChatroom(@Autowired WebTestClient client)
259   {
260     // Given
261     UUID chatroomId = UUID.randomUUID();
262     int shard = 666;
263     when(chatHome.getChatRoomInfo(eq(chatroomId))).thenThrow(new ShardNotOwnedException(shard));
264
265     // When
266     WebTestClient.ResponseSpec responseSpec = client
267         .get()
268         .uri("/{chatroomId}", chatroomId)
269         .accept(MediaType.APPLICATION_JSON)
270         .exchange();
271
272     // Then
273     assertProblemDetailsForShardNotOwnedException(responseSpec, shard);
274   }
275
276   @Test
277   @DisplayName("Assert expected problem-details for not owned shard on GET /list/{chatroomId}")
278   void testShardNotOwnedExceptionForListChatroom(@Autowired WebTestClient client)
279   {
280     // Given
281     UUID chatroomId = UUID.randomUUID();
282     int shard = 666;
283     when(chatHome.getChatRoomData(eq(chatroomId))).thenThrow(new ShardNotOwnedException(shard));
284
285     // When
286     WebTestClient.ResponseSpec responseSpec = client
287         .get()
288         .uri("/{chatroomId}/list", chatroomId)
289         .accept(MediaType.APPLICATION_JSON)
290         .exchange();
291
292     // Then
293     assertProblemDetailsForShardNotOwnedException(responseSpec, shard);
294   }
295
296   @Test
297   @DisplayName("Assert expected problem-details for not owned shard on PUT /put/{chatroomId}/{username}/{messageId}")
298   void testShardNotOwnedExceptionForPutMessage(@Autowired WebTestClient client)
299   {
300     // Given
301     UUID chatroomId = UUID.randomUUID();
302     String username = "foo";
303     Long messageId = 66l;
304     int shard = 666;
305     when(chatHome.getChatRoomData(eq(chatroomId))).thenThrow(new ShardNotOwnedException(shard));
306
307     // When
308     WebTestClient.ResponseSpec responseSpec = client
309         .put()
310         .uri(
311             "/{chatroomId}/{username}/{messageId}",
312             chatroomId,
313             username,
314             messageId)
315         .bodyValue("bar")
316         .accept(MediaType.APPLICATION_JSON)
317         .exchange();
318
319     // Then
320     assertProblemDetailsForShardNotOwnedException(responseSpec, shard);
321   }
322
323   @Test
324   @DisplayName("Assert expected problem-details for not owned shard on GET /get/{chatroomId}/{username}/{messageId}")
325   void testShardNotOwnedExceptionForGetMessage(@Autowired WebTestClient client)
326   {
327     // Given
328     UUID chatroomId = UUID.randomUUID();
329     String username = "foo";
330     Long messageId = 66l;
331     int shard = 666;
332     when(chatHome.getChatRoomData(eq(chatroomId))).thenThrow(new ShardNotOwnedException(shard));
333
334     // When
335     WebTestClient.ResponseSpec responseSpec = client
336         .get()
337         .uri(
338             "/{chatroomId}/{username}/{messageId}",
339             chatroomId,
340             username,
341             messageId)
342         .accept(MediaType.APPLICATION_JSON)
343         .exchange();
344
345     // Then
346     assertProblemDetailsForShardNotOwnedException(responseSpec, shard);
347   }
348
349   @Test
350   @DisplayName("Assert expected problem-details for not owned shard on GET /listen/{chatroomId}")
351   void testShardNotOwnedExceptionForListenChatroom(@Autowired WebTestClient client)
352   {
353     // Given
354     UUID chatroomId = UUID.randomUUID();
355     int shard = 666;
356     when(chatHome.getChatRoomData(eq(chatroomId))).thenThrow(new ShardNotOwnedException(shard));
357
358     // When
359     WebTestClient.ResponseSpec responseSpec = client
360         .get()
361         .uri("/{chatroomId}/listen", chatroomId)
362         // .accept(MediaType.TEXT_EVENT_STREAM, MediaType.APPLICATION_JSON) << TODO: Does not work!
363         .exchange();
364
365     // Then
366     assertProblemDetailsForShardNotOwnedException(responseSpec, shard);
367   }
368
369   private void assertProblemDetailsForShardNotOwnedException(
370       WebTestClient.ResponseSpec responseSpec,
371       int shard)
372   {
373     responseSpec
374         .expectStatus().isNotFound()
375         .expectBody()
376         .jsonPath("$.type").isEqualTo("/problem/shard-not-owned")
377         .jsonPath("$.shard").isEqualTo(shard);
378   }
379 }