mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-23 06:30:48 +08:00
优化目录结构
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import com.openisle.config.CustomAccessDeniedHandler;
|
||||
import com.openisle.config.SecurityConfig;
|
||||
import com.openisle.service.JwtService;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import com.openisle.service.UserVisitService;
|
||||
import com.openisle.model.Role;
|
||||
import com.openisle.model.User;
|
||||
import java.util.Optional;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@WebMvcTest(AdminController.class)
|
||||
@AutoConfigureMockMvc
|
||||
@Import({SecurityConfig.class, CustomAccessDeniedHandler.class})
|
||||
class AdminControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private JwtService jwtService;
|
||||
@MockBean
|
||||
private UserRepository userRepository;
|
||||
@MockBean
|
||||
private UserVisitService userVisitService;
|
||||
|
||||
@Test
|
||||
void adminHelloReturnsMessage() throws Exception {
|
||||
Mockito.when(jwtService.validateAndGetSubject("adminToken")).thenReturn("admin");
|
||||
User admin = new User();
|
||||
admin.setUsername("admin");
|
||||
admin.setPassword("p");
|
||||
admin.setEmail("a@b.com");
|
||||
admin.setRole(Role.ADMIN);
|
||||
Mockito.when(userRepository.findByUsername("admin")).thenReturn(Optional.of(admin));
|
||||
|
||||
mockMvc.perform(get("/api/admin/hello").header("Authorization", "Bearer adminToken"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.message").value("Hello, Admin User"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminHelloMissingToken() throws Exception {
|
||||
mockMvc.perform(get("/api/admin/hello"))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.error").value("Missing token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminHelloInvalidToken() throws Exception {
|
||||
Mockito.when(jwtService.validateAndGetSubject("bad")).thenThrow(new RuntimeException());
|
||||
|
||||
mockMvc.perform(get("/api/admin/hello").header("Authorization", "Bearer bad"))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.error").value("Invalid or expired token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminHelloNotAdmin() throws Exception {
|
||||
Mockito.when(jwtService.validateAndGetSubject("userToken")).thenReturn("user");
|
||||
User user = new User();
|
||||
user.setUsername("user");
|
||||
user.setPassword("p");
|
||||
user.setEmail("u@example.com");
|
||||
user.setRole(Role.USER);
|
||||
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
|
||||
|
||||
mockMvc.perform(get("/api/admin/hello").header("Authorization", "Bearer userToken"))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.error").value("Unauthorized"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.model.User;
|
||||
import com.openisle.service.*;
|
||||
import com.openisle.model.RegisterMode;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@WebMvcTest(AuthController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class AuthControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private UserService userService;
|
||||
@MockBean
|
||||
private JwtService jwtService;
|
||||
@MockBean
|
||||
private EmailSender emailService;
|
||||
@MockBean
|
||||
private CaptchaService captchaService;
|
||||
@MockBean
|
||||
private GoogleAuthService googleAuthService;
|
||||
@MockBean
|
||||
private RegisterModeService registerModeService;
|
||||
|
||||
@Test
|
||||
void registerSendsEmail() throws Exception {
|
||||
User user = new User();
|
||||
user.setEmail("a@b.com");
|
||||
user.setUsername("u");
|
||||
user.setVerificationCode("123456");
|
||||
Mockito.when(registerModeService.getRegisterMode()).thenReturn(RegisterMode.DIRECT);
|
||||
Mockito.when(userService.register(eq("u"), eq("a@b.com"), eq("p"), any(), eq(RegisterMode.DIRECT))).thenReturn(user);
|
||||
|
||||
mockMvc.perform(post("/api/auth/register")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"u\",\"email\":\"a@b.com\",\"password\":\"p\",\"reason\":\"test reason more than twenty\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.message").exists());
|
||||
|
||||
Mockito.verify(emailService).sendEmail(eq("a@b.com"), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyCodeEndpoint() throws Exception {
|
||||
Mockito.when(userService.verifyCode("u", "123")).thenReturn(true);
|
||||
|
||||
mockMvc.perform(post("/api/auth/verify")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"u\",\"code\":\"123\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.message").value("Verified"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginReturnsToken() throws Exception {
|
||||
User user = new User();
|
||||
user.setUsername("u");
|
||||
Mockito.when(userService.findByUsername("u")).thenReturn(Optional.of(user));
|
||||
Mockito.when(userService.matchesPassword(user, "p")).thenReturn(true);
|
||||
Mockito.when(jwtService.generateToken("u")).thenReturn("token");
|
||||
|
||||
mockMvc.perform(post("/api/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"u\",\"password\":\"p\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.token").value("token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginFails() throws Exception {
|
||||
Mockito.when(userService.findByUsername("u")).thenReturn(Optional.empty());
|
||||
|
||||
mockMvc.perform(post("/api/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"u\",\"password\":\"bad\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.reason_code").value("INVALID_CREDENTIALS"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.model.Category;
|
||||
import com.openisle.service.CategoryService;
|
||||
import com.openisle.service.PostService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@WebMvcTest(CategoryController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class CategoryControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private CategoryService categoryService;
|
||||
|
||||
@MockBean
|
||||
private PostService postService;
|
||||
|
||||
@Test
|
||||
void createAndGetCategory() throws Exception {
|
||||
Category c = new Category();
|
||||
c.setId(1L);
|
||||
c.setName("tech");
|
||||
c.setDescription("d");
|
||||
c.setIcon("i");
|
||||
c.setSmallIcon("s1");
|
||||
Mockito.when(categoryService.createCategory(eq("tech"), eq("d"), eq("i"), eq("s1"))).thenReturn(c);
|
||||
Mockito.when(categoryService.getCategory(1L)).thenReturn(c);
|
||||
|
||||
mockMvc.perform(post("/api/categories")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"tech\",\"description\":\"d\",\"icon\":\"i\",\"smallIcon\":\"s1\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("tech"))
|
||||
.andExpect(jsonPath("$.description").value("d"))
|
||||
.andExpect(jsonPath("$.icon").value("i"))
|
||||
.andExpect(jsonPath("$.smallIcon").value("s1"));
|
||||
|
||||
mockMvc.perform(get("/api/categories/1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listCategories() throws Exception {
|
||||
Category c = new Category();
|
||||
c.setId(2L);
|
||||
c.setName("life");
|
||||
c.setDescription("d2");
|
||||
c.setIcon("i2");
|
||||
c.setSmallIcon("s2");
|
||||
Mockito.when(categoryService.listCategories()).thenReturn(List.of(c));
|
||||
|
||||
mockMvc.perform(get("/api/categories"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].name").value("life"))
|
||||
.andExpect(jsonPath("$[0].description").value("d2"))
|
||||
.andExpect(jsonPath("$[0].icon").value("i2"))
|
||||
.andExpect(jsonPath("$[0].smallIcon").value("s2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateCategory() throws Exception {
|
||||
Category c = new Category();
|
||||
c.setId(3L);
|
||||
c.setName("tech");
|
||||
c.setDescription("d3");
|
||||
c.setIcon("i3");
|
||||
c.setSmallIcon("s3");
|
||||
Mockito.when(categoryService.updateCategory(eq(3L), eq("tech"), eq("d3"), eq("i3"), eq("s3"))).thenReturn(c);
|
||||
|
||||
mockMvc.perform(put("/api/categories/3")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"tech\",\"description\":\"d3\",\"icon\":\"i3\",\"smallIcon\":\"s3\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(3))
|
||||
.andExpect(jsonPath("$.name").value("tech"))
|
||||
.andExpect(jsonPath("$.description").value("d3"))
|
||||
.andExpect(jsonPath("$.icon").value("i3"))
|
||||
.andExpect(jsonPath("$.smallIcon").value("s3"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.model.Comment;
|
||||
import com.openisle.model.Post;
|
||||
import com.openisle.model.User;
|
||||
import com.openisle.service.CommentService;
|
||||
import com.openisle.service.CaptchaService;
|
||||
import com.openisle.service.LevelService;
|
||||
import com.openisle.service.ReactionService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@WebMvcTest(CommentController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class CommentControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private CommentService commentService;
|
||||
@MockBean
|
||||
private CaptchaService captchaService;
|
||||
@MockBean
|
||||
private LevelService levelService;
|
||||
@MockBean
|
||||
private ReactionService reactionService;
|
||||
|
||||
private Comment createComment(Long id, String content, String authorName) {
|
||||
User user = new User();
|
||||
user.setUsername(authorName);
|
||||
Comment c = new Comment();
|
||||
c.setId(id);
|
||||
c.setContent(content);
|
||||
c.setCreatedAt(LocalDateTime.now());
|
||||
c.setAuthor(user);
|
||||
c.setPost(new Post());
|
||||
return c;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAndListComments() throws Exception {
|
||||
Comment comment = createComment(1L, "hi", "bob");
|
||||
Mockito.when(commentService.addComment(eq("bob"), eq(1L), eq("hi"))).thenReturn(comment);
|
||||
Mockito.when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of(comment));
|
||||
Mockito.when(commentService.getReplies(1L)).thenReturn(List.of());
|
||||
Mockito.when(reactionService.getReactionsForComment(1L)).thenReturn(List.of());
|
||||
|
||||
mockMvc.perform(post("/api/posts/1/comments")
|
||||
.contentType("application/json")
|
||||
.content("{\"content\":\"hi\"}")
|
||||
.principal(new UsernamePasswordAuthenticationToken("bob", "p")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.content").value("hi"));
|
||||
|
||||
mockMvc.perform(get("/api/posts/1/comments"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].id").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replyComment() throws Exception {
|
||||
Comment reply = createComment(2L, "re", "alice");
|
||||
Mockito.when(commentService.addReply(eq("alice"), eq(1L), eq("re"))).thenReturn(reply);
|
||||
|
||||
mockMvc.perform(post("/api/comments/1/replies")
|
||||
.contentType("application/json")
|
||||
.content("{\"content\":\"re\"}")
|
||||
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import com.openisle.config.CustomAccessDeniedHandler;
|
||||
import com.openisle.config.SecurityConfig;
|
||||
import com.openisle.service.JwtService;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import com.openisle.service.UserVisitService;
|
||||
import com.openisle.model.Role;
|
||||
import com.openisle.model.User;
|
||||
import java.util.Optional;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@WebMvcTest(HelloController.class)
|
||||
@AutoConfigureMockMvc
|
||||
@Import({SecurityConfig.class, CustomAccessDeniedHandler.class})
|
||||
class HelloControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private JwtService jwtService;
|
||||
@MockBean
|
||||
private UserRepository userRepository;
|
||||
@MockBean
|
||||
private UserVisitService userVisitService;
|
||||
|
||||
@Test
|
||||
void helloReturnsMessage() throws Exception {
|
||||
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
|
||||
User user = new User();
|
||||
user.setUsername("user");
|
||||
user.setPassword("p");
|
||||
user.setEmail("u@example.com");
|
||||
user.setRole(Role.USER);
|
||||
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
|
||||
|
||||
mockMvc.perform(get("/api/hello").header("Authorization", "Bearer token"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.message").value("Hello, Authenticated User"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void helloMissingToken() throws Exception {
|
||||
mockMvc.perform(get("/api/hello"))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.error").value("Missing token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void helloInvalidToken() throws Exception {
|
||||
Mockito.when(jwtService.validateAndGetSubject("bad")).thenThrow(new RuntimeException());
|
||||
|
||||
mockMvc.perform(get("/api/hello").header("Authorization", "Bearer bad"))
|
||||
.andExpect(status().isUnauthorized())
|
||||
.andExpect(jsonPath("$.error").value("Invalid or expired token"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.model.Notification;
|
||||
import com.openisle.model.NotificationType;
|
||||
import com.openisle.model.Post;
|
||||
import com.openisle.service.NotificationService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@WebMvcTest(NotificationController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class NotificationControllerTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private NotificationService notificationService;
|
||||
|
||||
@Test
|
||||
void listNotifications() throws Exception {
|
||||
Notification n = new Notification();
|
||||
n.setId(1L);
|
||||
n.setType(NotificationType.POST_VIEWED);
|
||||
Post p = new Post();
|
||||
p.setId(2L);
|
||||
n.setPost(p);
|
||||
n.setCreatedAt(LocalDateTime.now());
|
||||
Mockito.when(notificationService.listNotifications("alice", null))
|
||||
.thenReturn(List.of(n));
|
||||
|
||||
mockMvc.perform(get("/api/notifications")
|
||||
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].id").value(1))
|
||||
.andExpect(jsonPath("$[0].post.id").value(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void markReadEndpoint() throws Exception {
|
||||
mockMvc.perform(post("/api/notifications/read")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"ids\":[1,2]}" )
|
||||
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
verify(notificationService).markRead("alice", List.of(1L,2L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadCountEndpoint() throws Exception {
|
||||
Mockito.when(notificationService.countUnread("alice")).thenReturn(3L);
|
||||
|
||||
mockMvc.perform(get("/api/notifications/unread-count")
|
||||
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.count").value(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.model.Post;
|
||||
import com.openisle.model.User;
|
||||
import com.openisle.model.Category;
|
||||
import com.openisle.model.Tag;
|
||||
import com.openisle.service.PostService;
|
||||
import com.openisle.service.CommentService;
|
||||
import com.openisle.service.ReactionService;
|
||||
import com.openisle.service.CaptchaService;
|
||||
import com.openisle.service.DraftService;
|
||||
import com.openisle.service.LevelService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.never;
|
||||
|
||||
@WebMvcTest(PostController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class PostControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
@Autowired
|
||||
private PostController postController;
|
||||
|
||||
|
||||
@MockBean
|
||||
private PostService postService;
|
||||
@MockBean
|
||||
private CommentService commentService;
|
||||
@MockBean
|
||||
private ReactionService reactionService;
|
||||
@MockBean
|
||||
private CaptchaService captchaService;
|
||||
@MockBean
|
||||
private DraftService draftService;
|
||||
@MockBean
|
||||
private LevelService levelService;
|
||||
|
||||
@Test
|
||||
void createAndGetPost() throws Exception {
|
||||
User user = new User();
|
||||
user.setUsername("alice");
|
||||
Category cat = new Category();
|
||||
cat.setId(1L);
|
||||
cat.setName("tech");
|
||||
cat.setDescription("d");
|
||||
cat.setIcon("i");
|
||||
Tag tag = new Tag();
|
||||
tag.setId(1L);
|
||||
tag.setName("java");
|
||||
tag.setDescription("td");
|
||||
tag.setIcon("ti");
|
||||
Post post = new Post();
|
||||
post.setId(1L);
|
||||
post.setTitle("t");
|
||||
post.setContent("c");
|
||||
post.setCreatedAt(LocalDateTime.now());
|
||||
post.setAuthor(user);
|
||||
post.setCategory(cat);
|
||||
post.setTags(java.util.Set.of(tag));
|
||||
Mockito.when(commentService.getParticipants(Mockito.anyLong(), Mockito.anyInt())).thenReturn(java.util.List.of());
|
||||
Mockito.when(postService.createPost(eq("alice"), eq(1L), eq("t"), eq("c"), eq(java.util.List.of(1L)))).thenReturn(post);
|
||||
Mockito.when(postService.viewPost(eq(1L), Mockito.isNull())).thenReturn(post);
|
||||
|
||||
mockMvc.perform(post("/api/posts")
|
||||
.contentType("application/json")
|
||||
.content("{\"title\":\"t\",\"content\":\"c\",\"categoryId\":1,\"tagIds\":[1]}")
|
||||
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.title").value("t"));
|
||||
|
||||
mockMvc.perform(get("/api/posts/1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPosts() throws Exception {
|
||||
User user = new User();
|
||||
user.setUsername("bob");
|
||||
Category cat = new Category();
|
||||
cat.setId(1L);
|
||||
cat.setName("tech");
|
||||
cat.setDescription("d");
|
||||
cat.setIcon("i");
|
||||
Tag tag = new Tag();
|
||||
tag.setId(1L);
|
||||
tag.setName("java");
|
||||
tag.setDescription("td");
|
||||
tag.setIcon("ti");
|
||||
Post post = new Post();
|
||||
post.setId(2L);
|
||||
post.setTitle("hello");
|
||||
post.setContent("world");
|
||||
post.setCreatedAt(LocalDateTime.now());
|
||||
post.setAuthor(user);
|
||||
post.setCategory(cat);
|
||||
post.setTags(java.util.Set.of(tag));
|
||||
Mockito.when(commentService.getParticipants(Mockito.anyLong(), Mockito.anyInt())).thenReturn(java.util.List.of());
|
||||
Mockito.when(postService.listPostsByCategories(Mockito.isNull(), Mockito.isNull(), Mockito.isNull()))
|
||||
.thenReturn(List.of(post));
|
||||
|
||||
mockMvc.perform(get("/api/posts"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].title").value("hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPostRejectsInvalidCaptcha() throws Exception {
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(postController, "captchaEnabled", true);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(postController, "postCaptchaEnabled", true);
|
||||
Mockito.when(captchaService.verify("bad")).thenReturn(false);
|
||||
|
||||
mockMvc.perform(post("/api/posts")
|
||||
.contentType("application/json")
|
||||
.content("{\"title\":\"t\",\"content\":\"c\",\"categoryId\":1,\"tagIds\":[1],\"captcha\":\"bad\"}")
|
||||
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
verify(postService, never()).createPost(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPostWithNestedData() throws Exception {
|
||||
User user = new User();
|
||||
user.setUsername("alice");
|
||||
Category cat = new Category();
|
||||
cat.setId(1L);
|
||||
cat.setName("tech");
|
||||
Tag tag = new Tag();
|
||||
tag.setId(1L);
|
||||
tag.setName("java");
|
||||
Post post = new Post();
|
||||
post.setId(1L);
|
||||
post.setTitle("t");
|
||||
post.setContent("c");
|
||||
post.setCreatedAt(LocalDateTime.now());
|
||||
post.setAuthor(user);
|
||||
post.setCategory(cat);
|
||||
post.setTags(java.util.Set.of(tag));
|
||||
|
||||
com.openisle.model.Comment comment = new com.openisle.model.Comment();
|
||||
comment.setId(2L);
|
||||
comment.setContent("hi");
|
||||
comment.setCreatedAt(LocalDateTime.now());
|
||||
comment.setAuthor(user);
|
||||
comment.setPost(post);
|
||||
|
||||
com.openisle.model.Comment reply = new com.openisle.model.Comment();
|
||||
reply.setId(3L);
|
||||
reply.setContent("reply");
|
||||
reply.setCreatedAt(LocalDateTime.now());
|
||||
reply.setAuthor(user);
|
||||
reply.setPost(post);
|
||||
|
||||
com.openisle.model.Reaction pr = new com.openisle.model.Reaction();
|
||||
pr.setId(10L);
|
||||
pr.setUser(user);
|
||||
pr.setPost(post);
|
||||
pr.setType(com.openisle.model.ReactionType.LIKE);
|
||||
|
||||
com.openisle.model.Reaction cr = new com.openisle.model.Reaction();
|
||||
cr.setId(11L);
|
||||
cr.setUser(user);
|
||||
cr.setComment(comment);
|
||||
cr.setType(com.openisle.model.ReactionType.LIKE);
|
||||
|
||||
Mockito.when(postService.viewPost(eq(1L), Mockito.isNull())).thenReturn(post);
|
||||
Mockito.when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of(comment));
|
||||
Mockito.when(commentService.getReplies(2L)).thenReturn(List.of(reply));
|
||||
Mockito.when(commentService.getReplies(3L)).thenReturn(List.of());
|
||||
Mockito.when(commentService.getParticipants(Mockito.anyLong(), Mockito.anyInt())).thenReturn(java.util.List.of());
|
||||
Mockito.when(reactionService.getReactionsForPost(1L)).thenReturn(List.of(pr));
|
||||
Mockito.when(reactionService.getReactionsForComment(2L)).thenReturn(List.of(cr));
|
||||
Mockito.when(reactionService.getReactionsForComment(3L)).thenReturn(List.of());
|
||||
|
||||
mockMvc.perform(get("/api/posts/1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.reactions[0].id").value(10))
|
||||
.andExpect(jsonPath("$.comments[0].replies[0].id").value(3))
|
||||
.andExpect(jsonPath("$.comments[0].reactions[0].id").value(11));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPostsByCategoriesAndTags() throws Exception {
|
||||
User user = new User();
|
||||
user.setUsername("alice");
|
||||
Category cat = new Category();
|
||||
cat.setName("tech");
|
||||
Tag tag = new Tag();
|
||||
tag.setId(1L);
|
||||
tag.setName("java");
|
||||
Post post = new Post();
|
||||
post.setId(2L);
|
||||
post.setTitle("hello");
|
||||
post.setCreatedAt(LocalDateTime.now());
|
||||
post.setAuthor(user);
|
||||
post.setCategory(cat);
|
||||
post.setTags(java.util.Set.of(tag));
|
||||
Mockito.when(commentService.getParticipants(Mockito.anyLong(), Mockito.anyInt())).thenReturn(java.util.List.of());
|
||||
|
||||
Mockito.when(postService.listPostsByCategoriesAndTags(eq(java.util.List.of(1L)), eq(java.util.List.of(1L, 2L)), eq(0), eq(5)))
|
||||
.thenReturn(List.of(post));
|
||||
|
||||
mockMvc.perform(get("/api/posts")
|
||||
.param("tagIds", "1,2")
|
||||
.param("page", "0")
|
||||
.param("pageSize", "5")
|
||||
.param("categoryId", "1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].id").value(2));
|
||||
|
||||
verify(postService).listPostsByCategoriesAndTags(eq(java.util.List.of(1L)), eq(java.util.List.of(1L, 2L)), eq(0), eq(5));
|
||||
verify(postService, never()).listPostsByCategories(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rankingPostsFiltered() throws Exception {
|
||||
User user = new User();
|
||||
user.setUsername("alice");
|
||||
Category cat = new Category();
|
||||
cat.setName("tech");
|
||||
Tag tag = new Tag();
|
||||
tag.setId(1L);
|
||||
tag.setName("java");
|
||||
Post post = new Post();
|
||||
post.setId(3L);
|
||||
post.setTitle("rank");
|
||||
post.setCreatedAt(LocalDateTime.now());
|
||||
post.setAuthor(user);
|
||||
post.setCategory(cat);
|
||||
post.setTags(java.util.Set.of(tag));
|
||||
Mockito.when(commentService.getParticipants(Mockito.anyLong(), Mockito.anyInt())).thenReturn(java.util.List.of());
|
||||
|
||||
Mockito.when(postService.listPostsByViews(eq(java.util.List.of(1L)), eq(java.util.List.of(1L, 2L)), eq(0), eq(5)))
|
||||
.thenReturn(List.of(post));
|
||||
|
||||
mockMvc.perform(get("/api/posts/ranking")
|
||||
.param("tagIds", "1,2")
|
||||
.param("page", "0")
|
||||
.param("pageSize", "5")
|
||||
.param("categoryId", "1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].id").value(3));
|
||||
|
||||
verify(postService).listPostsByViews(eq(java.util.List.of(1L)), eq(java.util.List.of(1L, 2L)), eq(0), eq(5));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.service.PushSubscriptionService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@WebMvcTest(PushSubscriptionController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class PushSubscriptionControllerTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private PushSubscriptionService pushSubscriptionService;
|
||||
|
||||
@Test
|
||||
void subscribeEndpoint() throws Exception {
|
||||
mockMvc.perform(post("/api/push/subscribe")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"endpoint\":\"e\",\"p256dh\":\"p\",\"auth\":\"a\"}")
|
||||
.principal(new UsernamePasswordAuthenticationToken("u","p")))
|
||||
.andExpect(status().isOk());
|
||||
Mockito.verify(pushSubscriptionService).saveSubscription("u","e","p","a");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.model.Comment;
|
||||
import com.openisle.model.Post;
|
||||
import com.openisle.model.Reaction;
|
||||
import com.openisle.model.ReactionType;
|
||||
import com.openisle.model.User;
|
||||
import com.openisle.service.ReactionService;
|
||||
import com.openisle.service.LevelService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@WebMvcTest(ReactionController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class ReactionControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private ReactionService reactionService;
|
||||
@MockBean
|
||||
private LevelService levelService;
|
||||
|
||||
@Test
|
||||
void reactToPost() throws Exception {
|
||||
User user = new User();
|
||||
user.setUsername("u1");
|
||||
Post post = new Post();
|
||||
post.setId(1L);
|
||||
Reaction reaction = new Reaction();
|
||||
reaction.setId(1L);
|
||||
reaction.setUser(user);
|
||||
reaction.setPost(post);
|
||||
reaction.setType(ReactionType.LIKE);
|
||||
Mockito.when(reactionService.reactToPost(eq("u1"), eq(1L), eq(ReactionType.LIKE))).thenReturn(reaction);
|
||||
|
||||
mockMvc.perform(post("/api/posts/1/reactions")
|
||||
.contentType("application/json")
|
||||
.content("{\"type\":\"LIKE\"}")
|
||||
.principal(new UsernamePasswordAuthenticationToken("u1", "p")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.postId").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reactToComment() throws Exception {
|
||||
User user = new User();
|
||||
user.setUsername("u2");
|
||||
Comment comment = new Comment();
|
||||
comment.setId(2L);
|
||||
Reaction reaction = new Reaction();
|
||||
reaction.setId(2L);
|
||||
reaction.setUser(user);
|
||||
reaction.setComment(comment);
|
||||
reaction.setType(ReactionType.RECOMMEND);
|
||||
Mockito.when(reactionService.reactToComment(eq("u2"), eq(2L), eq(ReactionType.RECOMMEND))).thenReturn(reaction);
|
||||
|
||||
mockMvc.perform(post("/api/comments/2/reactions")
|
||||
.contentType("application/json")
|
||||
.content("{\"type\":\"RECOMMEND\"}")
|
||||
.principal(new UsernamePasswordAuthenticationToken("u2", "p")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.commentId").value(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReactionTypes() throws Exception {
|
||||
mockMvc.perform(get("/api/reaction-types"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0]").value("LIKE"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.model.Comment;
|
||||
import com.openisle.model.Post;
|
||||
import com.openisle.model.User;
|
||||
import com.openisle.model.PostStatus;
|
||||
import com.openisle.service.SearchService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@WebMvcTest(SearchController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class SearchControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private SearchService searchService;
|
||||
|
||||
@Test
|
||||
void userSearchEndpoint() throws Exception {
|
||||
User user = new User();
|
||||
user.setId(1L);
|
||||
user.setUsername("alice");
|
||||
Mockito.when(searchService.searchUsers("ali")).thenReturn(List.of(user));
|
||||
|
||||
mockMvc.perform(get("/api/search/users").param("keyword", "ali"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].username").value("alice"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void globalSearchAggregatesTypes() throws Exception {
|
||||
User u = new User();
|
||||
u.setId(1L);
|
||||
u.setUsername("bob");
|
||||
Post p = new Post();
|
||||
p.setId(2L);
|
||||
p.setTitle("hello");
|
||||
p.setStatus(PostStatus.PUBLISHED);
|
||||
Comment c = new Comment();
|
||||
c.setId(3L);
|
||||
c.setContent("nice");
|
||||
Mockito.when(searchService.globalSearch("n")).thenReturn(List.of(
|
||||
new SearchService.SearchResult("user", 1L, "bob", null, null, null),
|
||||
new SearchService.SearchResult("post", 2L, "hello", null, null, null),
|
||||
new SearchService.SearchResult("comment", 3L, "nice", null, null, null)
|
||||
));
|
||||
|
||||
mockMvc.perform(get("/api/search/global").param("keyword", "n"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].type").value("user"))
|
||||
.andExpect(jsonPath("$[1].type").value("post"))
|
||||
.andExpect(jsonPath("$[2].type").value("comment"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchPostsByTitle() throws Exception {
|
||||
Post p = new Post();
|
||||
p.setId(2L);
|
||||
p.setTitle("spring");
|
||||
Mockito.when(searchService.searchPostsByTitle("spr")).thenReturn(List.of(p));
|
||||
|
||||
mockMvc.perform(get("/api/search/posts/title").param("keyword", "spr"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].title").value("spring"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void searchPosts() throws Exception {
|
||||
Post p = new Post();
|
||||
p.setId(5L);
|
||||
p.setTitle("hello");
|
||||
Mockito.when(searchService.searchPosts("he")).thenReturn(List.of(p));
|
||||
|
||||
mockMvc.perform(get("/api/search/posts").param("keyword", "he"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].id").value(5));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.config.CustomAccessDeniedHandler;
|
||||
import com.openisle.config.SecurityConfig;
|
||||
import com.openisle.service.JwtService;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import com.openisle.service.UserVisitService;
|
||||
import com.openisle.model.Role;
|
||||
import com.openisle.model.User;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@WebMvcTest(StatController.class)
|
||||
@AutoConfigureMockMvc
|
||||
@Import({SecurityConfig.class, CustomAccessDeniedHandler.class})
|
||||
class StatControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private JwtService jwtService;
|
||||
@MockBean
|
||||
private UserRepository userRepository;
|
||||
@MockBean
|
||||
private UserVisitService userVisitService;
|
||||
|
||||
@Test
|
||||
void dauReturnsCount() throws Exception {
|
||||
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
|
||||
User user = new User();
|
||||
user.setUsername("user");
|
||||
user.setPassword("p");
|
||||
user.setEmail("u@example.com");
|
||||
user.setRole(Role.USER);
|
||||
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
|
||||
Mockito.when(userVisitService.countDau(Mockito.any())).thenReturn(3L);
|
||||
|
||||
mockMvc.perform(get("/api/stats/dau").header("Authorization", "Bearer token"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.dau").value(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dauRangeReturnsSeries() throws Exception {
|
||||
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
|
||||
User user = new User();
|
||||
user.setUsername("user");
|
||||
user.setPassword("p");
|
||||
user.setEmail("u@example.com");
|
||||
user.setRole(Role.USER);
|
||||
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
|
||||
java.util.Map<java.time.LocalDate, Long> map = new java.util.LinkedHashMap<>();
|
||||
map.put(java.time.LocalDate.now().minusDays(1), 1L);
|
||||
map.put(java.time.LocalDate.now(), 2L);
|
||||
Mockito.when(userVisitService.countDauRange(Mockito.any(), Mockito.any())).thenReturn(map);
|
||||
|
||||
mockMvc.perform(get("/api/stats/dau-range").param("days", "2").header("Authorization", "Bearer token"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].value").value(1))
|
||||
.andExpect(jsonPath("$[1].value").value(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.model.Tag;
|
||||
import com.openisle.service.TagService;
|
||||
import com.openisle.service.PostService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@WebMvcTest(TagController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class TagControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private TagService tagService;
|
||||
|
||||
@MockBean
|
||||
private PostService postService;
|
||||
|
||||
@Test
|
||||
void createAndGetTag() throws Exception {
|
||||
Tag t = new Tag();
|
||||
t.setId(1L);
|
||||
t.setName("java");
|
||||
t.setDescription("d");
|
||||
t.setIcon("i");
|
||||
t.setSmallIcon("s1");
|
||||
Mockito.when(tagService.createTag(eq("java"), eq("d"), eq("i"), eq("s1"), eq(true), isNull())).thenReturn(t);
|
||||
Mockito.when(tagService.getTag(1L)).thenReturn(t);
|
||||
|
||||
mockMvc.perform(post("/api/tags")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"java\",\"description\":\"d\",\"icon\":\"i\",\"smallIcon\":\"s1\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("java"))
|
||||
.andExpect(jsonPath("$.description").value("d"))
|
||||
.andExpect(jsonPath("$.icon").value("i"))
|
||||
.andExpect(jsonPath("$.smallIcon").value("s1"));
|
||||
|
||||
mockMvc.perform(get("/api/tags/1"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listTags() throws Exception {
|
||||
Tag t = new Tag();
|
||||
t.setId(2L);
|
||||
t.setName("spring");
|
||||
t.setDescription("d2");
|
||||
t.setIcon("i2");
|
||||
t.setSmallIcon("s2");
|
||||
Mockito.when(tagService.listTags()).thenReturn(List.of(t));
|
||||
|
||||
mockMvc.perform(get("/api/tags"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].name").value("spring"))
|
||||
.andExpect(jsonPath("$[0].description").value("d2"))
|
||||
.andExpect(jsonPath("$[0].icon").value("i2"))
|
||||
.andExpect(jsonPath("$[0].smallIcon").value("s2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTag() throws Exception {
|
||||
Tag t = new Tag();
|
||||
t.setId(3L);
|
||||
t.setName("java");
|
||||
t.setDescription("d3");
|
||||
t.setIcon("i3");
|
||||
t.setSmallIcon("s3");
|
||||
Mockito.when(tagService.updateTag(eq(3L), eq("java"), eq("d3"), eq("i3"), eq("s3"))).thenReturn(t);
|
||||
|
||||
mockMvc.perform(put("/api/tags/3")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"java\",\"description\":\"d3\",\"icon\":\"i3\",\"smallIcon\":\"s3\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(3))
|
||||
.andExpect(jsonPath("$.name").value("java"))
|
||||
.andExpect(jsonPath("$.description").value("d3"))
|
||||
.andExpect(jsonPath("$.icon").value("i3"))
|
||||
.andExpect(jsonPath("$.smallIcon").value("s3"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.model.User;
|
||||
import com.openisle.service.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@WebMvcTest(UserController.class)
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
class UserControllerTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private ReactionService reactionService;
|
||||
@MockBean
|
||||
private SubscriptionService subscriptionService;
|
||||
@MockBean
|
||||
private UserService userService;
|
||||
@MockBean
|
||||
private ImageUploader imageUploader;
|
||||
@MockBean
|
||||
private PostService postService;
|
||||
@MockBean
|
||||
private CommentService commentService;
|
||||
@MockBean
|
||||
private LevelService levelService;
|
||||
|
||||
@Test
|
||||
void getCurrentUser() throws Exception {
|
||||
User u = new User();
|
||||
u.setId(1L);
|
||||
u.setUsername("alice");
|
||||
u.setEmail("a@b.com");
|
||||
u.setAvatar("http://x/avatar.png");
|
||||
Mockito.when(userService.findByUsername("alice")).thenReturn(Optional.of(u));
|
||||
|
||||
mockMvc.perform(get("/api/users/me").principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.avatar").value("http://x/avatar.png"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadAvatar() throws Exception {
|
||||
MockMultipartFile file = new MockMultipartFile("file", "a.png", MediaType.IMAGE_PNG_VALUE, "img".getBytes());
|
||||
Mockito.when(imageUploader.upload(any(), eq("a.png"))).thenReturn(java.util.concurrent.CompletableFuture.completedFuture("http://img/a.png"));
|
||||
|
||||
mockMvc.perform(multipart("/api/users/me/avatar").file(file).principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.url").value("http://img/a.png"));
|
||||
|
||||
Mockito.verify(userService).updateAvatar("alice", "http://img/a.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadAvatarRejectsNonImage() throws Exception {
|
||||
MockMultipartFile file = new MockMultipartFile("file", "a.txt", MediaType.TEXT_PLAIN_VALUE, "text".getBytes());
|
||||
|
||||
mockMvc.perform(multipart("/api/users/me/avatar").file(file).principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.error").value("File is not an image"));
|
||||
|
||||
Mockito.verify(imageUploader, Mockito.never()).upload(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUserByName() throws Exception {
|
||||
User u = new User();
|
||||
u.setId(2L);
|
||||
u.setUsername("bob");
|
||||
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(u));
|
||||
|
||||
mockMvc.perform(get("/api/users/bob"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listUserPosts() throws Exception {
|
||||
User user = new User();
|
||||
user.setUsername("bob");
|
||||
com.openisle.model.Category cat = new com.openisle.model.Category();
|
||||
cat.setName("tech");
|
||||
com.openisle.model.Post post = new com.openisle.model.Post();
|
||||
post.setId(3L);
|
||||
post.setTitle("hello");
|
||||
post.setCreatedAt(java.time.LocalDateTime.now());
|
||||
post.setCategory(cat);
|
||||
post.setAuthor(user);
|
||||
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
|
||||
Mockito.when(postService.getRecentPostsByUser("bob", 10)).thenReturn(java.util.List.of(post));
|
||||
|
||||
mockMvc.perform(get("/api/users/bob/posts"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].title").value("hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listUserReplies() throws Exception {
|
||||
User user = new User();
|
||||
user.setUsername("bob");
|
||||
com.openisle.model.Post post = new com.openisle.model.Post();
|
||||
post.setId(5L);
|
||||
com.openisle.model.Category cat = new com.openisle.model.Category();
|
||||
cat.setName("tech");
|
||||
post.setCategory(cat);
|
||||
com.openisle.model.Comment comment = new com.openisle.model.Comment();
|
||||
comment.setId(4L);
|
||||
comment.setContent("hi");
|
||||
comment.setCreatedAt(java.time.LocalDateTime.now());
|
||||
comment.setAuthor(user);
|
||||
comment.setPost(post);
|
||||
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
|
||||
Mockito.when(commentService.getRecentCommentsByUser("bob", 50)).thenReturn(java.util.List.of(comment));
|
||||
|
||||
mockMvc.perform(get("/api/users/bob/replies"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].id").value(4));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aggregateUserData() throws Exception {
|
||||
User user = new User();
|
||||
user.setId(2L);
|
||||
user.setUsername("bob");
|
||||
user.setEmail("b@e.com");
|
||||
com.openisle.model.Category cat = new com.openisle.model.Category();
|
||||
cat.setName("tech");
|
||||
com.openisle.model.Post post = new com.openisle.model.Post();
|
||||
post.setId(3L);
|
||||
post.setTitle("hello");
|
||||
post.setCreatedAt(java.time.LocalDateTime.now());
|
||||
post.setCategory(cat);
|
||||
post.setAuthor(user);
|
||||
com.openisle.model.Comment comment = new com.openisle.model.Comment();
|
||||
comment.setId(4L);
|
||||
comment.setContent("hi");
|
||||
comment.setCreatedAt(java.time.LocalDateTime.now());
|
||||
comment.setAuthor(user);
|
||||
comment.setPost(post);
|
||||
|
||||
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
|
||||
Mockito.when(postService.getRecentPostsByUser("bob", 10)).thenReturn(java.util.List.of(post));
|
||||
Mockito.when(commentService.getRecentCommentsByUser("bob", 50)).thenReturn(java.util.List.of(comment));
|
||||
|
||||
mockMvc.perform(get("/api/users/bob/all"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.user.id").value(2))
|
||||
.andExpect(jsonPath("$.posts[0].id").value(3))
|
||||
.andExpect(jsonPath("$.replies[0].id").value(4));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.openisle.integration;
|
||||
|
||||
import com.openisle.model.User;
|
||||
import com.openisle.model.Role;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import com.openisle.service.EmailSender;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.http.*;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = "app.register.mode=DIRECT")
|
||||
class ComplexFlowIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate rest;
|
||||
|
||||
@Autowired
|
||||
private UserRepository users;
|
||||
|
||||
@MockBean
|
||||
private EmailSender emailService;
|
||||
|
||||
private String registerAndLogin(String username, String email) {
|
||||
HttpHeaders h = new HttpHeaders();
|
||||
h.setContentType(MediaType.APPLICATION_JSON);
|
||||
rest.postForEntity("/api/auth/register", new HttpEntity<>(
|
||||
Map.of("username", username, "email", email, "password", "pass123", "reason", "integration test reason more than twenty"), h), Map.class);
|
||||
User u = users.findByUsername(username).orElseThrow();
|
||||
if (u.getVerificationCode() != null) {
|
||||
rest.postForEntity("/api/auth/verify", new HttpEntity<>(
|
||||
Map.of("username", username, "code", u.getVerificationCode()), h), Map.class);
|
||||
}
|
||||
ResponseEntity<Map> resp = rest.postForEntity("/api/auth/login", new HttpEntity<>(
|
||||
Map.of("username", username, "password", "pass123"), h), Map.class);
|
||||
return (String) resp.getBody().get("token");
|
||||
}
|
||||
|
||||
private String registerAndLoginAsAdmin(String username, String email) {
|
||||
String token = registerAndLogin(username, email);
|
||||
User u = users.findByUsername(username).orElseThrow();
|
||||
u.setRole(Role.ADMIN);
|
||||
users.save(u);
|
||||
return token;
|
||||
}
|
||||
|
||||
private ResponseEntity<Map> postJson(String url, Map<?,?> body, String token) {
|
||||
HttpHeaders h = new HttpHeaders();
|
||||
h.setContentType(MediaType.APPLICATION_JSON);
|
||||
if (token != null) h.setBearerAuth(token);
|
||||
return rest.exchange(url, HttpMethod.POST, new HttpEntity<>(body, h), Map.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedCommentsVisibleInPost() {
|
||||
String t1 = registerAndLogin("alice1", "a@example.com");
|
||||
String t2 = registerAndLogin("bob123", "b@example.com");
|
||||
|
||||
String adminToken = registerAndLoginAsAdmin("admin1", "admin@example.com");
|
||||
ResponseEntity<Map> catResp = postJson("/api/categories",
|
||||
Map.of("name", "general", "description", "d", "icon", "i"), adminToken);
|
||||
Long catId = ((Number)catResp.getBody().get("id")).longValue();
|
||||
|
||||
ResponseEntity<Map> tagResp = postJson("/api/tags",
|
||||
Map.of("name", "java", "description", "d", "icon", "i"), adminToken);
|
||||
Long tagId = ((Number)tagResp.getBody().get("id")).longValue();
|
||||
|
||||
ResponseEntity<Map> postResp = postJson("/api/posts",
|
||||
Map.of("title", "Hello", "content", "World", "categoryId", catId,
|
||||
"tagIds", List.of(tagId)), t1);
|
||||
Long postId = ((Number)postResp.getBody().get("id")).longValue();
|
||||
|
||||
ResponseEntity<Map> c1Resp = postJson("/api/posts/" + postId + "/comments",
|
||||
Map.of("content", "first"), t2);
|
||||
Long c1 = ((Number)c1Resp.getBody().get("id")).longValue();
|
||||
|
||||
ResponseEntity<Map> r1Resp = postJson("/api/comments/" + c1 + "/replies",
|
||||
Map.of("content", "reply1"), t1);
|
||||
Long r1 = ((Number)r1Resp.getBody().get("id")).longValue();
|
||||
|
||||
postJson("/api/comments/" + r1 + "/replies",
|
||||
Map.of("content", "reply2"), t2);
|
||||
|
||||
Map post = rest.getForObject("/api/posts/" + postId, Map.class);
|
||||
assertEquals("Hello", post.get("title"));
|
||||
List<?> comments = (List<?>) post.get("comments");
|
||||
assertEquals(1, comments.size());
|
||||
Map<?,?> cMap = (Map<?,?>) comments.get(0);
|
||||
assertEquals("first", cMap.get("content"));
|
||||
List<?> replies1 = (List<?>) cMap.get("replies");
|
||||
assertEquals(1, replies1.size());
|
||||
Map<?,?> rMap = (Map<?,?>) replies1.get(0);
|
||||
assertEquals("reply1", rMap.get("content"));
|
||||
List<?> replies2 = (List<?>) rMap.get("replies");
|
||||
assertEquals(1, replies2.size());
|
||||
assertEquals("reply2", ((Map<?,?>)replies2.get(0)).get("content"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reactionsReturnedForPostAndComment() {
|
||||
String t1 = registerAndLogin("carol1", "c@example.com");
|
||||
String t2 = registerAndLogin("dave01", "d@example.com");
|
||||
|
||||
String adminToken = registerAndLoginAsAdmin("admin2", "admin2@example.com");
|
||||
List<Map<String, Object>> categories = (List<Map<String, Object>>) rest.getForObject("/api/categories", List.class);
|
||||
Long catId = null;
|
||||
if (categories != null) {
|
||||
for (Map<String, Object> cat : categories) {
|
||||
if ("general".equals(cat.get("name"))) {
|
||||
catId = ((Number)cat.get("id")).longValue();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (catId == null) {
|
||||
ResponseEntity<Map> catResp = postJson("/api/categories",
|
||||
Map.of("name", "general", "description", "d", "icon", "i"), adminToken);
|
||||
catId = ((Number)catResp.getBody().get("id")).longValue();
|
||||
}
|
||||
|
||||
ResponseEntity<Map> tagResp = postJson("/api/tags",
|
||||
Map.of("name", "spring", "description", "d", "icon", "i"), adminToken);
|
||||
Long tagId = ((Number)tagResp.getBody().get("id")).longValue();
|
||||
|
||||
ResponseEntity<Map> postResp = postJson("/api/posts",
|
||||
Map.of("title", "React", "content", "Test", "categoryId", catId,
|
||||
"tagIds", List.of(tagId)), t1);
|
||||
Long postId = ((Number)postResp.getBody().get("id")).longValue();
|
||||
|
||||
postJson("/api/posts/" + postId + "/reactions",
|
||||
Map.of("type", "LIKE"), t2);
|
||||
|
||||
ResponseEntity<Map> cResp = postJson("/api/posts/" + postId + "/comments",
|
||||
Map.of("content", "hi"), t1);
|
||||
Long commentId = ((Number)cResp.getBody().get("id")).longValue();
|
||||
|
||||
postJson("/api/comments/" + commentId + "/reactions",
|
||||
Map.of("type", "DISLIKE"), t2);
|
||||
|
||||
Map post = rest.getForObject("/api/posts/" + postId, Map.class);
|
||||
List<?> reactions = (List<?>) post.get("reactions");
|
||||
assertEquals(1, reactions.size());
|
||||
assertEquals("LIKE", ((Map<?,?>)reactions.get(0)).get("type"));
|
||||
|
||||
List<?> comments = (List<?>) post.get("comments");
|
||||
Map<?,?> comment = (Map<?,?>) comments.get(0);
|
||||
List<?> creactions = (List<?>) comment.get("reactions");
|
||||
assertEquals(1, creactions.size());
|
||||
assertEquals("DISLIKE", ((Map<?,?>)creactions.get(0)).get("type"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.openisle.integration;
|
||||
|
||||
import com.openisle.model.Role;
|
||||
import com.openisle.model.User;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import com.openisle.service.EmailSender;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.http.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Integration tests for review publish mode. */
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = {"app.post.publish-mode=REVIEW","app.register.mode=DIRECT"})
|
||||
class PublishModeIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate rest;
|
||||
|
||||
@Autowired
|
||||
private UserRepository users;
|
||||
|
||||
@MockBean
|
||||
private EmailSender emailService;
|
||||
|
||||
private String registerAndLogin(String username, String email) {
|
||||
HttpHeaders h = new HttpHeaders();
|
||||
h.setContentType(MediaType.APPLICATION_JSON);
|
||||
rest.postForEntity("/api/auth/register", new HttpEntity<>(
|
||||
Map.of("username", username, "email", email, "password", "pass123", "reason", "integration test reason more than twenty"), h), Map.class);
|
||||
User u = users.findByUsername(username).orElseThrow();
|
||||
if (u.getVerificationCode() != null) {
|
||||
rest.postForEntity("/api/auth/verify", new HttpEntity<>(
|
||||
Map.of("username", username, "code", u.getVerificationCode()), h), Map.class);
|
||||
}
|
||||
ResponseEntity<Map> resp = rest.postForEntity("/api/auth/login", new HttpEntity<>(
|
||||
Map.of("username", username, "password", "pass123"), h), Map.class);
|
||||
return (String) resp.getBody().get("token");
|
||||
}
|
||||
|
||||
private String registerAndLoginAsAdmin(String username, String email) {
|
||||
String token = registerAndLogin(username, email);
|
||||
User u = users.findByUsername(username).orElseThrow();
|
||||
u.setRole(Role.ADMIN);
|
||||
users.save(u);
|
||||
return token;
|
||||
}
|
||||
|
||||
private ResponseEntity<Map> postJson(String url, Map<?,?> body, String token) {
|
||||
HttpHeaders h = new HttpHeaders();
|
||||
h.setContentType(MediaType.APPLICATION_JSON);
|
||||
if (token != null) h.setBearerAuth(token);
|
||||
return rest.exchange(url, HttpMethod.POST, new HttpEntity<>(body, h), Map.class);
|
||||
}
|
||||
|
||||
private <T> ResponseEntity<T> get(String url, Class<T> type, String token) {
|
||||
HttpHeaders h = new HttpHeaders();
|
||||
if (token != null) h.setBearerAuth(token);
|
||||
return rest.exchange(url, HttpMethod.GET, new HttpEntity<>(h), type);
|
||||
}
|
||||
|
||||
@Test
|
||||
void postRequiresApproval() {
|
||||
String userToken = registerAndLogin("eve123", "e@example.com");
|
||||
String adminToken = registerAndLoginAsAdmin("admin1", "admin@example.com");
|
||||
|
||||
ResponseEntity<Map> catResp = postJson("/api/categories",
|
||||
Map.of("name", "review", "description", "d", "icon", "i"), adminToken);
|
||||
Long catId = ((Number)catResp.getBody().get("id")).longValue();
|
||||
|
||||
ResponseEntity<Map> tagResp = postJson("/api/tags",
|
||||
Map.of("name", "t1", "description", "d", "icon", "i"), adminToken);
|
||||
Long tagId = ((Number)tagResp.getBody().get("id")).longValue();
|
||||
|
||||
ResponseEntity<Map> postResp = postJson("/api/posts",
|
||||
Map.of("title", "Need", "content", "Review", "categoryId", catId,
|
||||
"tagIds", List.of(tagId)), userToken);
|
||||
Long postId = ((Number)postResp.getBody().get("id")).longValue();
|
||||
|
||||
List<?> list = rest.getForObject("/api/posts", List.class);
|
||||
assertTrue(list.isEmpty(), "Post should not be listed before approval");
|
||||
|
||||
List<Map<String, Object>> pending = get("/api/admin/posts/pending", List.class, adminToken).getBody();
|
||||
assertEquals(1, pending.size());
|
||||
assertEquals(postId.intValue(), ((Number)pending.get(0).get("id")).intValue());
|
||||
|
||||
postJson("/api/admin/posts/" + postId + "/approve", Map.of(), adminToken);
|
||||
|
||||
List<?> listAfter = rest.getForObject("/api/posts", List.class);
|
||||
assertEquals(1, listAfter.size(), "Post should appear after approval");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.openisle.integration;
|
||||
|
||||
import com.openisle.model.Role;
|
||||
import com.openisle.model.User;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import com.openisle.service.EmailSender;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.http.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
|
||||
properties = "app.register.mode=DIRECT")
|
||||
class SearchIntegrationTest {
|
||||
@Autowired
|
||||
private TestRestTemplate rest;
|
||||
@Autowired
|
||||
private UserRepository users;
|
||||
@MockBean
|
||||
private EmailSender emailService;
|
||||
|
||||
private String registerAndLogin(String username, String email) {
|
||||
HttpHeaders h = new HttpHeaders();
|
||||
h.setContentType(MediaType.APPLICATION_JSON);
|
||||
rest.postForEntity("/api/auth/register", new HttpEntity<>(
|
||||
Map.of("username", username, "email", email, "password", "pass123", "reason", "integration test reason more than twenty"), h), Map.class);
|
||||
User u = users.findByUsername(username).orElseThrow();
|
||||
if (u.getVerificationCode() != null) {
|
||||
rest.postForEntity("/api/auth/verify", new HttpEntity<>(
|
||||
Map.of("username", username, "code", u.getVerificationCode()), h), Map.class);
|
||||
}
|
||||
ResponseEntity<Map> resp = rest.postForEntity("/api/auth/login", new HttpEntity<>(
|
||||
Map.of("username", username, "password", "pass123"), h), Map.class);
|
||||
return (String) resp.getBody().get("token");
|
||||
}
|
||||
|
||||
private String registerAndLoginAsAdmin(String username, String email) {
|
||||
String token = registerAndLogin(username, email);
|
||||
User u = users.findByUsername(username).orElseThrow();
|
||||
u.setRole(Role.ADMIN);
|
||||
users.save(u);
|
||||
return token;
|
||||
}
|
||||
|
||||
private ResponseEntity<Map> postJson(String url, Map<?,?> body, String token) {
|
||||
HttpHeaders h = new HttpHeaders();
|
||||
h.setContentType(MediaType.APPLICATION_JSON);
|
||||
if (token != null) h.setBearerAuth(token);
|
||||
return rest.exchange(url, HttpMethod.POST, new HttpEntity<>(body, h), Map.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void globalSearchReturnsMixedResults() {
|
||||
String admin = registerAndLoginAsAdmin("admin1", "a@a.com");
|
||||
String user = registerAndLogin("bob_nice", "b@b.com");
|
||||
|
||||
ResponseEntity<Map> catResp = postJson("/api/categories", Map.of("name", "nic-cat", "description", "d", "icon", "i"), admin);
|
||||
Long catId = ((Number)catResp.getBody().get("id")).longValue();
|
||||
|
||||
ResponseEntity<Map> tagResp = postJson("/api/tags", Map.of("name", "nic-tag", "description", "d", "icon", "i"), admin);
|
||||
Long tagId = ((Number)tagResp.getBody().get("id")).longValue();
|
||||
|
||||
ResponseEntity<Map> postResp = postJson("/api/posts",
|
||||
Map.of("title", "Hello World Nice", "content", "Some content", "categoryId", catId,
|
||||
"tagIds", List.of(tagId)), user);
|
||||
Long postId = ((Number)postResp.getBody().get("id")).longValue();
|
||||
|
||||
postJson("/api/posts/" + postId + "/comments",
|
||||
Map.of("content", "Nice article"), admin);
|
||||
|
||||
List<Map<String, Object>> results = rest.getForObject("/api/search/global?keyword=nic", List.class);
|
||||
assertEquals(5, results.size());
|
||||
assertTrue(results.stream().anyMatch(m -> "user".equals(m.get("type"))));
|
||||
assertTrue(results.stream().anyMatch(m -> "post".equals(m.get("type"))));
|
||||
assertTrue(results.stream().anyMatch(m -> "comment".equals(m.get("type"))));
|
||||
assertTrue(results.stream().anyMatch(m -> "category".equals(m.get("type"))));
|
||||
assertTrue(results.stream().anyMatch(m -> "tag".equals(m.get("type"))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.repository.CommentRepository;
|
||||
import com.openisle.repository.PostRepository;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import com.openisle.repository.ReactionRepository;
|
||||
import com.openisle.repository.CommentSubscriptionRepository;
|
||||
import com.openisle.repository.NotificationRepository;
|
||||
import com.openisle.exception.RateLimitException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class CommentServiceTest {
|
||||
@Test
|
||||
void addCommentRespectsRateLimit() {
|
||||
CommentRepository commentRepo = mock(CommentRepository.class);
|
||||
PostRepository postRepo = mock(PostRepository.class);
|
||||
UserRepository userRepo = mock(UserRepository.class);
|
||||
NotificationService notifService = mock(NotificationService.class);
|
||||
SubscriptionService subService = mock(SubscriptionService.class);
|
||||
ReactionRepository reactionRepo = mock(ReactionRepository.class);
|
||||
CommentSubscriptionRepository subRepo = mock(CommentSubscriptionRepository.class);
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
ImageUploader imageUploader = mock(ImageUploader.class);
|
||||
|
||||
CommentService service = new CommentService(commentRepo, postRepo, userRepo,
|
||||
notifService, subService, reactionRepo, subRepo, nRepo, imageUploader);
|
||||
|
||||
when(commentRepo.countByAuthorAfter(eq("alice"), any())).thenReturn(3L);
|
||||
|
||||
assertThrows(RateLimitException.class,
|
||||
() -> service.addComment("alice", 1L, "hi"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.qcloud.cos.COSClient;
|
||||
import com.qcloud.cos.model.PutObjectRequest;
|
||||
import com.openisle.repository.ImageRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class CosImageUploaderTest {
|
||||
@Test
|
||||
void uploadReturnsUrl() {
|
||||
COSClient client = mock(COSClient.class);
|
||||
ImageRepository repo = mock(ImageRepository.class);
|
||||
CosImageUploader uploader = new CosImageUploader(client, repo, "bucket", "http://cos.example.com");
|
||||
|
||||
String url = uploader.upload("data".getBytes(), "img.png").join();
|
||||
|
||||
verify(client).putObject(any(PutObjectRequest.class));
|
||||
assertTrue(url.matches("http://cos.example.com/dynamic_assert/[a-f0-9]{32}\\.png"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.model.*;
|
||||
import com.openisle.repository.NotificationRepository;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import com.openisle.repository.ReactionRepository;
|
||||
import com.openisle.service.PushNotificationService;
|
||||
import java.util.concurrent.Executor;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class NotificationServiceTest {
|
||||
|
||||
@Test
|
||||
void markReadUpdatesOnlyOwnedNotifications() {
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
UserRepository uRepo = mock(UserRepository.class);
|
||||
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||
EmailSender email = mock(EmailSender.class);
|
||||
PushNotificationService push = mock(PushNotificationService.class);
|
||||
Executor executor = Runnable::run;
|
||||
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||
|
||||
User user = new User();
|
||||
user.setId(1L);
|
||||
user.setUsername("alice");
|
||||
when(uRepo.findByUsername("alice")).thenReturn(Optional.of(user));
|
||||
|
||||
Notification n1 = new Notification();
|
||||
n1.setId(10L);
|
||||
n1.setUser(user);
|
||||
Notification n2 = new Notification();
|
||||
n2.setId(11L);
|
||||
n2.setUser(user);
|
||||
when(nRepo.findAllById(List.of(10L, 11L))).thenReturn(List.of(n1, n2));
|
||||
|
||||
service.markRead("alice", List.of(10L, 11L));
|
||||
|
||||
assertTrue(n1.isRead());
|
||||
assertTrue(n2.isRead());
|
||||
verify(nRepo).saveAll(List.of(n1, n2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listNotificationsWithoutFilter() {
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
UserRepository uRepo = mock(UserRepository.class);
|
||||
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||
EmailSender email = mock(EmailSender.class);
|
||||
PushNotificationService push = mock(PushNotificationService.class);
|
||||
Executor executor = Runnable::run;
|
||||
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||
|
||||
User user = new User();
|
||||
user.setId(2L);
|
||||
user.setUsername("bob");
|
||||
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
|
||||
|
||||
Notification n = new Notification();
|
||||
when(nRepo.findByUserOrderByCreatedAtDesc(user)).thenReturn(List.of(n));
|
||||
|
||||
List<Notification> list = service.listNotifications("bob", null);
|
||||
|
||||
assertEquals(1, list.size());
|
||||
verify(nRepo).findByUserOrderByCreatedAtDesc(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
void countUnreadReturnsRepositoryValue() {
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
UserRepository uRepo = mock(UserRepository.class);
|
||||
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||
EmailSender email = mock(EmailSender.class);
|
||||
PushNotificationService push = mock(PushNotificationService.class);
|
||||
Executor executor = Runnable::run;
|
||||
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||
|
||||
User user = new User();
|
||||
user.setId(3L);
|
||||
user.setUsername("carl");
|
||||
when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user));
|
||||
when(nRepo.countByUserAndRead(user, false)).thenReturn(5L);
|
||||
|
||||
long count = service.countUnread("carl");
|
||||
|
||||
assertEquals(5L, count);
|
||||
verify(nRepo).countByUserAndRead(user, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRegisterRequestNotificationsDeletesOldOnes() {
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
UserRepository uRepo = mock(UserRepository.class);
|
||||
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||
EmailSender email = mock(EmailSender.class);
|
||||
PushNotificationService push = mock(PushNotificationService.class);
|
||||
Executor executor = Runnable::run;
|
||||
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||
|
||||
User admin = new User();
|
||||
admin.setId(10L);
|
||||
User applicant = new User();
|
||||
applicant.setId(20L);
|
||||
|
||||
when(uRepo.findByRole(Role.ADMIN)).thenReturn(List.of(admin));
|
||||
|
||||
service.createRegisterRequestNotifications(applicant, "reason");
|
||||
|
||||
verify(nRepo).deleteByTypeAndFromUser(NotificationType.REGISTER_REQUEST, applicant);
|
||||
verify(nRepo).save(any(Notification.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createActivityRedeemNotificationsDeletesOldOnes() {
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
UserRepository uRepo = mock(UserRepository.class);
|
||||
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||
EmailSender email = mock(EmailSender.class);
|
||||
PushNotificationService push = mock(PushNotificationService.class);
|
||||
Executor executor = Runnable::run;
|
||||
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||
|
||||
User admin = new User();
|
||||
admin.setId(10L);
|
||||
User user = new User();
|
||||
user.setId(20L);
|
||||
|
||||
when(uRepo.findByRole(Role.ADMIN)).thenReturn(List.of(admin));
|
||||
|
||||
service.createActivityRedeemNotifications(user, "contact");
|
||||
|
||||
verify(nRepo).deleteByTypeAndFromUser(NotificationType.ACTIVITY_REDEEM, user);
|
||||
verify(nRepo).save(any(Notification.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNotificationSendsEmailForCommentReply() {
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
UserRepository uRepo = mock(UserRepository.class);
|
||||
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||
EmailSender email = mock(EmailSender.class);
|
||||
PushNotificationService push = mock(PushNotificationService.class);
|
||||
Executor executor = Runnable::run;
|
||||
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||
|
||||
User user = new User();
|
||||
user.setEmail("a@a.com");
|
||||
Post post = new Post();
|
||||
post.setId(1L);
|
||||
Comment comment = new Comment();
|
||||
comment.setId(2L);
|
||||
when(nRepo.save(any(Notification.class))).thenAnswer(i -> i.getArgument(0));
|
||||
|
||||
service.createNotification(user, NotificationType.COMMENT_REPLY, post, comment, null, null, null, null);
|
||||
|
||||
verify(email).sendEmail("a@a.com", "有人回复了你", "https://ex.com/posts/1#comment-2");
|
||||
verify(push).sendNotification(eq(user), contains("/posts/1#comment-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void postViewedNotificationDeletesOldOnes() {
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
UserRepository uRepo = mock(UserRepository.class);
|
||||
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||
EmailSender email = mock(EmailSender.class);
|
||||
PushNotificationService push = mock(PushNotificationService.class);
|
||||
Executor executor = Runnable::run;
|
||||
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||
|
||||
User owner = new User();
|
||||
User viewer = new User();
|
||||
Post post = new Post();
|
||||
|
||||
when(nRepo.save(any(Notification.class))).thenAnswer(i -> i.getArgument(0));
|
||||
|
||||
service.createNotification(owner, NotificationType.POST_VIEWED, post, null, null, viewer, null, null);
|
||||
|
||||
verify(nRepo).deleteByTypeAndFromUserAndPost(NotificationType.POST_VIEWED, viewer, post);
|
||||
verify(nRepo).save(any(Notification.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.model.PasswordStrength;
|
||||
import com.openisle.exception.FieldException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PasswordValidatorTest {
|
||||
|
||||
@Test
|
||||
void lowStrengthRequiresSixChars() {
|
||||
PasswordValidator validator = new PasswordValidator(PasswordStrength.LOW);
|
||||
|
||||
assertThrows(FieldException.class, () -> validator.validate("12345"));
|
||||
assertDoesNotThrow(() -> validator.validate("123456"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mediumStrengthRules() {
|
||||
PasswordValidator validator = new PasswordValidator(PasswordStrength.MEDIUM);
|
||||
|
||||
assertThrows(FieldException.class, () -> validator.validate("abc123"));
|
||||
assertThrows(FieldException.class, () -> validator.validate("abcdefgh"));
|
||||
assertThrows(FieldException.class, () -> validator.validate("12345678"));
|
||||
assertDoesNotThrow(() -> validator.validate("abcd1234"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void highStrengthRules() {
|
||||
PasswordValidator validator = new PasswordValidator(PasswordStrength.HIGH);
|
||||
|
||||
assertThrows(FieldException.class, () -> validator.validate("Abc123$"));
|
||||
assertThrows(FieldException.class, () -> validator.validate("abcd1234$xyz"));
|
||||
assertThrows(FieldException.class, () -> validator.validate("ABCD1234$XYZ"));
|
||||
assertThrows(FieldException.class, () -> validator.validate("AbcdABCDabcd"));
|
||||
assertThrows(FieldException.class, () -> validator.validate("Abcd1234abcd"));
|
||||
assertDoesNotThrow(() -> validator.validate("Abcd1234$xyz"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.model.*;
|
||||
import com.openisle.repository.*;
|
||||
import com.openisle.exception.RateLimitException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class PostServiceTest {
|
||||
@Test
|
||||
void deletePostRemovesReads() {
|
||||
PostRepository postRepo = mock(PostRepository.class);
|
||||
UserRepository userRepo = mock(UserRepository.class);
|
||||
CategoryRepository catRepo = mock(CategoryRepository.class);
|
||||
TagRepository tagRepo = mock(TagRepository.class);
|
||||
NotificationService notifService = mock(NotificationService.class);
|
||||
SubscriptionService subService = mock(SubscriptionService.class);
|
||||
CommentService commentService = mock(CommentService.class);
|
||||
CommentRepository commentRepo = mock(CommentRepository.class);
|
||||
ReactionRepository reactionRepo = mock(ReactionRepository.class);
|
||||
PostSubscriptionRepository subRepo = mock(PostSubscriptionRepository.class);
|
||||
NotificationRepository notificationRepo = mock(NotificationRepository.class);
|
||||
PostReadService postReadService = mock(PostReadService.class);
|
||||
ImageUploader imageUploader = mock(ImageUploader.class);
|
||||
|
||||
PostService service = new PostService(postRepo, userRepo, catRepo, tagRepo,
|
||||
notifService, subService, commentService, commentRepo,
|
||||
reactionRepo, subRepo, notificationRepo, postReadService,
|
||||
imageUploader, PublishMode.DIRECT);
|
||||
|
||||
Post post = new Post();
|
||||
post.setId(1L);
|
||||
User author = new User();
|
||||
author.setId(1L);
|
||||
author.setRole(Role.USER);
|
||||
post.setAuthor(author);
|
||||
|
||||
when(postRepo.findById(1L)).thenReturn(Optional.of(post));
|
||||
when(userRepo.findByUsername("alice")).thenReturn(Optional.of(author));
|
||||
when(commentRepo.findByPostAndParentIsNullOrderByCreatedAtAsc(post)).thenReturn(List.of());
|
||||
when(reactionRepo.findByPost(post)).thenReturn(List.of());
|
||||
when(subRepo.findByPost(post)).thenReturn(List.of());
|
||||
when(notificationRepo.findByPost(post)).thenReturn(List.of());
|
||||
|
||||
service.deletePost(1L, "alice");
|
||||
|
||||
verify(postReadService).deleteByPost(post);
|
||||
verify(postRepo).delete(post);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPostRespectsRateLimit() {
|
||||
PostRepository postRepo = mock(PostRepository.class);
|
||||
UserRepository userRepo = mock(UserRepository.class);
|
||||
CategoryRepository catRepo = mock(CategoryRepository.class);
|
||||
TagRepository tagRepo = mock(TagRepository.class);
|
||||
NotificationService notifService = mock(NotificationService.class);
|
||||
SubscriptionService subService = mock(SubscriptionService.class);
|
||||
CommentService commentService = mock(CommentService.class);
|
||||
CommentRepository commentRepo = mock(CommentRepository.class);
|
||||
ReactionRepository reactionRepo = mock(ReactionRepository.class);
|
||||
PostSubscriptionRepository subRepo = mock(PostSubscriptionRepository.class);
|
||||
NotificationRepository notificationRepo = mock(NotificationRepository.class);
|
||||
PostReadService postReadService = mock(PostReadService.class);
|
||||
ImageUploader imageUploader = mock(ImageUploader.class);
|
||||
|
||||
PostService service = new PostService(postRepo, userRepo, catRepo, tagRepo,
|
||||
notifService, subService, commentService, commentRepo,
|
||||
reactionRepo, subRepo, notificationRepo, postReadService,
|
||||
imageUploader, PublishMode.DIRECT);
|
||||
|
||||
when(postRepo.countByAuthorAfter(eq("alice"), any())).thenReturn(1L);
|
||||
|
||||
assertThrows(RateLimitException.class,
|
||||
() -> service.createPost("alice", 1L, "t", "c", List.of(1L)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.model.*;
|
||||
import com.openisle.repository.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class ReactionServiceTest {
|
||||
@Test
|
||||
void reactToPostSendsEmailEveryFive() {
|
||||
ReactionRepository reactionRepo = mock(ReactionRepository.class);
|
||||
UserRepository userRepo = mock(UserRepository.class);
|
||||
PostRepository postRepo = mock(PostRepository.class);
|
||||
CommentRepository commentRepo = mock(CommentRepository.class);
|
||||
NotificationService notif = mock(NotificationService.class);
|
||||
EmailSender email = mock(EmailSender.class);
|
||||
ReactionService service = new ReactionService(reactionRepo, userRepo, postRepo, commentRepo, notif, email);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||
|
||||
User user = new User();
|
||||
user.setId(1L);
|
||||
user.setUsername("bob");
|
||||
User author = new User();
|
||||
author.setId(2L);
|
||||
author.setEmail("a@a.com");
|
||||
Post post = new Post();
|
||||
post.setId(3L);
|
||||
post.setAuthor(author);
|
||||
|
||||
when(userRepo.findByUsername("bob")).thenReturn(Optional.of(user));
|
||||
when(postRepo.findById(3L)).thenReturn(Optional.of(post));
|
||||
when(reactionRepo.findByUserAndPostAndType(user, post, ReactionType.LIKE)).thenReturn(Optional.empty());
|
||||
when(reactionRepo.save(any(Reaction.class))).thenAnswer(i -> i.getArgument(0));
|
||||
when(reactionRepo.countReceived(author.getUsername())).thenReturn(5L);
|
||||
|
||||
service.reactToPost("bob", 3L, ReactionType.LIKE);
|
||||
|
||||
verify(email).sendEmail("a@a.com", "你有新的互动", "https://ex.com/messages");
|
||||
verify(notif).sendCustomPush(author, "你有新的互动", "https://ex.com/messages");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.model.Post;
|
||||
import com.openisle.model.PostStatus;
|
||||
import com.openisle.repository.CommentRepository;
|
||||
import com.openisle.repository.PostRepository;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import com.openisle.repository.CategoryRepository;
|
||||
import com.openisle.repository.TagRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SearchServiceTest {
|
||||
|
||||
@Test
|
||||
void globalSearchDeduplicatesPosts() {
|
||||
UserRepository userRepo = Mockito.mock(UserRepository.class);
|
||||
PostRepository postRepo = Mockito.mock(PostRepository.class);
|
||||
CommentRepository commentRepo = Mockito.mock(CommentRepository.class);
|
||||
CategoryRepository categoryRepo = Mockito.mock(CategoryRepository.class);
|
||||
TagRepository tagRepo = Mockito.mock(TagRepository.class);
|
||||
SearchService service = new SearchService(userRepo, postRepo, commentRepo, categoryRepo, tagRepo);
|
||||
|
||||
Post post1 = new Post();
|
||||
post1.setId(1L);
|
||||
post1.setTitle("hello");
|
||||
Post post2 = new Post();
|
||||
post2.setId(2L);
|
||||
post2.setTitle("world");
|
||||
|
||||
Mockito.when(postRepo.findByTitleContainingIgnoreCaseOrContentContainingIgnoreCaseAndStatus(
|
||||
Mockito.anyString(), Mockito.anyString(), Mockito.eq(PostStatus.PUBLISHED)))
|
||||
.thenReturn(List.of(post1));
|
||||
Mockito.when(postRepo.findByTitleContainingIgnoreCaseAndStatus(Mockito.anyString(), Mockito.eq(PostStatus.PUBLISHED)))
|
||||
.thenReturn(List.of(post1, post2));
|
||||
Mockito.when(commentRepo.findByContentContainingIgnoreCase(Mockito.anyString()))
|
||||
.thenReturn(List.of());
|
||||
Mockito.when(userRepo.findByUsernameContainingIgnoreCase(Mockito.anyString()))
|
||||
.thenReturn(List.of());
|
||||
|
||||
List<SearchService.SearchResult> results = service.globalSearch("h");
|
||||
|
||||
assertEquals(2, results.size());
|
||||
assertEquals(1L, results.get(0).id());
|
||||
assertEquals(2L, results.get(1).id());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.exception.FieldException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class UsernameValidatorTest {
|
||||
|
||||
@Test
|
||||
void rejectsEmptyUsername() {
|
||||
UsernameValidator validator = new UsernameValidator();
|
||||
assertThrows(FieldException.class, () -> validator.validate(""));
|
||||
assertThrows(FieldException.class, () -> validator.validate(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsShortUsername() {
|
||||
UsernameValidator validator = new UsernameValidator();
|
||||
assertDoesNotThrow(() -> validator.validate("a"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user