fix: 后端代码格式化

This commit is contained in:
Tim
2025-09-18 14:42:25 +08:00
parent 70f7442f0c
commit 72b2b82e02
325 changed files with 15341 additions and 12370 deletions

View File

@@ -1,83 +1,90 @@
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;
import com.openisle.config.CustomAccessDeniedHandler;
import com.openisle.config.SecurityConfig;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.JwtService;
import com.openisle.service.UserVisitService;
import java.util.Optional;
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;
@WebMvcTest(AdminController.class)
@AutoConfigureMockMvc
@Import({SecurityConfig.class, CustomAccessDeniedHandler.class})
@Import({ SecurityConfig.class, CustomAccessDeniedHandler.class })
class AdminControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private JwtService jwtService;
@MockBean
private UserRepository userRepository;
@MockBean
private UserVisitService userVisitService;
@Autowired
private MockMvc mockMvc;
@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));
@MockBean
private JwtService jwtService;
mockMvc.perform(get("/api/admin/hello").header("Authorization", "Bearer adminToken"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Hello, Admin User"));
}
@MockBean
private UserRepository userRepository;
@Test
void adminHelloMissingToken() throws Exception {
mockMvc.perform(get("/api/admin/hello"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Missing token"));
}
@MockBean
private UserVisitService userVisitService;
@Test
void adminHelloInvalidToken() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("bad")).thenThrow(new RuntimeException());
@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 bad"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Invalid or expired token"));
}
mockMvc
.perform(get("/api/admin/hello").header("Authorization", "Bearer adminToken"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Hello, Admin User"));
}
@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));
@Test
void adminHelloMissingToken() throws Exception {
mockMvc
.perform(get("/api/admin/hello"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Missing token"));
}
mockMvc.perform(get("/api/admin/hello").header("Authorization", "Bearer userToken"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Unauthorized"));
}
@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"));
}
}

View File

@@ -1,11 +1,18 @@
package com.openisle.controller;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.openisle.model.Notification;
import com.openisle.model.NotificationType;
import com.openisle.model.User;
import com.openisle.repository.NotificationRepository;
import com.openisle.repository.UserRepository;
import com.openisle.service.EmailSender;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
@@ -13,64 +20,59 @@ 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 java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(AdminUserController.class)
@AutoConfigureMockMvc(addFilters = false)
class AdminUserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserRepository userRepository;
@MockBean
private NotificationRepository notificationRepository;
@MockBean
private EmailSender emailSender;
@Autowired
private MockMvc mockMvc;
@Test
void approveMarksNotificationsRead() throws Exception {
User u = new User();
u.setId(1L);
u.setEmail("a@a.com");
when(userRepository.findById(1L)).thenReturn(Optional.of(u));
@MockBean
private UserRepository userRepository;
Notification n = new Notification();
n.setId(2L);
n.setRead(false);
when(notificationRepository.findByTypeAndFromUser(NotificationType.REGISTER_REQUEST, u))
.thenReturn(List.of(n));
@MockBean
private NotificationRepository notificationRepository;
mockMvc.perform(post("/api/admin/users/1/approve"))
.andExpect(status().isOk());
@MockBean
private EmailSender emailSender;
assertTrue(n.isRead());
verify(notificationRepository).saveAll(List.of(n));
}
@Test
void approveMarksNotificationsRead() throws Exception {
User u = new User();
u.setId(1L);
u.setEmail("a@a.com");
when(userRepository.findById(1L)).thenReturn(Optional.of(u));
@Test
void rejectMarksNotificationsRead() throws Exception {
User u = new User();
u.setId(1L);
u.setEmail("a@a.com");
when(userRepository.findById(1L)).thenReturn(Optional.of(u));
Notification n = new Notification();
n.setId(2L);
n.setRead(false);
when(
notificationRepository.findByTypeAndFromUser(NotificationType.REGISTER_REQUEST, u)
).thenReturn(List.of(n));
Notification n = new Notification();
n.setId(2L);
n.setRead(false);
when(notificationRepository.findByTypeAndFromUser(NotificationType.REGISTER_REQUEST, u))
.thenReturn(List.of(n));
mockMvc.perform(post("/api/admin/users/1/approve")).andExpect(status().isOk());
mockMvc.perform(post("/api/admin/users/1/reject"))
.andExpect(status().isOk());
assertTrue(n.isRead());
verify(notificationRepository).saveAll(List.of(n));
}
assertTrue(n.isRead());
verify(notificationRepository).saveAll(List.of(n));
}
@Test
void rejectMarksNotificationsRead() throws Exception {
User u = new User();
u.setId(1L);
u.setEmail("a@a.com");
when(userRepository.findById(1L)).thenReturn(Optional.of(u));
Notification n = new Notification();
n.setId(2L);
n.setRead(false);
when(
notificationRepository.findByTypeAndFromUser(NotificationType.REGISTER_REQUEST, u)
).thenReturn(List.of(n));
mockMvc.perform(post("/api/admin/users/1/reject")).andExpect(status().isOk());
assertTrue(n.isRead());
verify(notificationRepository).saveAll(List.of(n));
}
}

View File

@@ -1,10 +1,18 @@
package com.openisle.controller;
import com.openisle.model.User;
import com.openisle.service.*;
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;
import com.openisle.model.RegisterMode;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.*;
import com.openisle.util.VerifyType;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -14,100 +22,118 @@ 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;
@MockBean
private GithubAuthService githubAuthService;
@MockBean
private DiscordAuthService discordAuthService;
@MockBean
private TwitterAuthService twitterAuthService;
@MockBean
private NotificationService notificationService;
@MockBean
private UserRepository userRepository;
@Autowired
private MockMvc mockMvc;
@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);
@MockBean
private UserService userService;
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());
@MockBean
private JwtService jwtService;
Mockito.verify(emailService).sendEmail(eq("a@b.com"), any(), any());
}
@MockBean
private EmailSender emailService;
@Test
void verifyCodeEndpoint() throws Exception {
User user = new User();
user.setUsername("u");
Mockito.when(userService.verifyCode(user, "123", VerifyType.REGISTER)).thenReturn(true);
Mockito.when(jwtService.generateReasonToken("u")).thenReturn("reason_token");
@MockBean
private CaptchaService captchaService;
mockMvc.perform(post("/api/auth/verify")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"u\",\"code\":\"123\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Verified"));
}
@MockBean
private GoogleAuthService googleAuthService;
@Test
void loginReturnsToken() throws Exception {
User user = new User();
user.setUsername("u");
user.setVerified(true);
Mockito.when(userService.findByUsername("u")).thenReturn(Optional.of(user));
Mockito.when(userService.matchesPassword(user, "p")).thenReturn(true);
Mockito.when(jwtService.generateToken("u")).thenReturn("token");
@MockBean
private RegisterModeService registerModeService;
mockMvc.perform(post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"u\",\"password\":\"p\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.token").value("token"));
}
@MockBean
private GithubAuthService githubAuthService;
@Test
void loginFails() throws Exception {
Mockito.when(userService.findByUsername("u")).thenReturn(Optional.empty());
@MockBean
private DiscordAuthService discordAuthService;
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"));
}
@MockBean
private TwitterAuthService twitterAuthService;
@MockBean
private NotificationService notificationService;
@MockBean
private UserRepository userRepository;
@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 {
User user = new User();
user.setUsername("u");
Mockito.when(userService.verifyCode(user, "123", VerifyType.REGISTER)).thenReturn(true);
Mockito.when(jwtService.generateReasonToken("u")).thenReturn("reason_token");
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");
user.setVerified(true);
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"));
}
}

View File

@@ -1,10 +1,15 @@
package com.openisle.controller;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.openisle.mapper.CategoryMapper;
import com.openisle.mapper.PostMapper;
import com.openisle.model.Category;
import com.openisle.service.CategoryService;
import com.openisle.service.PostService;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -15,89 +20,98 @@ import org.springframework.context.annotation.Import;
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)
@Import(CategoryMapper.class)
class CategoryControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CategoryService categoryService;
@Autowired
private MockMvc mockMvc;
@MockBean
private PostService postService;
@MockBean
private CategoryService categoryService;
@MockBean
private PostMapper postMapper;
@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);
@MockBean
private PostMapper postMapper;
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"));
@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(get("/api/categories/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
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"));
@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/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
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 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));
@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(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"));
}
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"));
}
@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"));
}
}

View File

@@ -1,5 +1,12 @@
package com.openisle.controller;
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 com.openisle.dto.CommentDto;
import com.openisle.mapper.CommentMapper;
import com.openisle.model.Comment;
@@ -9,6 +16,8 @@ import com.openisle.service.CaptchaService;
import com.openisle.service.CommentService;
import com.openisle.service.LevelService;
import com.openisle.service.ReactionService;
import java.time.LocalDateTime;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -18,84 +27,86 @@ 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;
@MockBean
private CommentMapper commentMapper;
@Autowired
private MockMvc mockMvc;
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;
}
@MockBean
private CommentService commentService;
@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());
CommentDto dto = new CommentDto();
dto.setId(comment.getId());
dto.setContent(comment.getContent());
Mockito.when(commentMapper.toDto(comment)).thenReturn(dto);
Mockito.when(commentMapper.toDtoWithReplies(comment)).thenReturn(dto);
@MockBean
private CaptchaService captchaService;
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"));
@MockBean
private LevelService levelService;
mockMvc.perform(get("/api/posts/1/comments"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(1));
}
@MockBean
private ReactionService reactionService;
@Test
void replyComment() throws Exception {
Comment reply = createComment(2L, "re", "alice");
Mockito.when(commentService.addReply(eq("alice"), eq(1L), eq("re"))).thenReturn(reply);
CommentDto dto = new CommentDto();
dto.setId(reply.getId());
dto.setContent(reply.getContent());
Mockito.when(commentMapper.toDto(reply)).thenReturn(dto);
@MockBean
private CommentMapper commentMapper;
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));
}
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());
CommentDto dto = new CommentDto();
dto.setId(comment.getId());
dto.setContent(comment.getContent());
Mockito.when(commentMapper.toDto(comment)).thenReturn(dto);
Mockito.when(commentMapper.toDtoWithReplies(comment)).thenReturn(dto);
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);
CommentDto dto = new CommentDto();
dto.setId(reply.getId());
dto.setContent(reply.getContent());
Mockito.when(commentMapper.toDto(reply)).thenReturn(dto);
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));
}
}

View File

@@ -1,68 +1,74 @@
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;
import com.openisle.config.CustomAccessDeniedHandler;
import com.openisle.config.SecurityConfig;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.JwtService;
import com.openisle.service.UserVisitService;
import java.util.Optional;
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;
@WebMvcTest(HelloController.class)
@AutoConfigureMockMvc
@Import({SecurityConfig.class, CustomAccessDeniedHandler.class})
@Import({ SecurityConfig.class, CustomAccessDeniedHandler.class })
class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private JwtService jwtService;
@MockBean
private UserRepository userRepository;
@MockBean
private UserVisitService userVisitService;
@Autowired
private MockMvc mockMvc;
@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));
@MockBean
private JwtService jwtService;
mockMvc.perform(get("/api/hello").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Hello, Authenticated User"));
}
@MockBean
private UserRepository userRepository;
@Test
void helloMissingToken() throws Exception {
mockMvc.perform(get("/api/hello"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Missing token"));
}
@MockBean
private UserVisitService userVisitService;
@Test
void helloInvalidToken() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("bad")).thenThrow(new RuntimeException());
@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 bad"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Invalid or expired token"));
}
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"));
}
}

View File

@@ -1,8 +1,14 @@
package com.openisle.controller;
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 com.openisle.dto.CommentMedalDto;
import com.openisle.model.MedalType;
import com.openisle.service.MedalService;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -12,63 +18,66 @@ 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.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(MedalController.class)
@AutoConfigureMockMvc(addFilters = false)
class MedalControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private MedalService medalService;
@Autowired
private MockMvc mockMvc;
@Test
void listMedals() throws Exception {
CommentMedalDto medal = new CommentMedalDto();
medal.setTitle("评论达人");
medal.setType(MedalType.COMMENT);
Mockito.when(medalService.getMedals(null)).thenReturn(List.of(medal));
@MockBean
private MedalService medalService;
mockMvc.perform(get("/api/medals"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("评论达人"));
}
@Test
void listMedals() throws Exception {
CommentMedalDto medal = new CommentMedalDto();
medal.setTitle("评论达人");
medal.setType(MedalType.COMMENT);
Mockito.when(medalService.getMedals(null)).thenReturn(List.of(medal));
@Test
void listMedalsWithUser() throws Exception {
CommentMedalDto medal = new CommentMedalDto();
medal.setCompleted(true);
medal.setType(MedalType.COMMENT);
Mockito.when(medalService.getMedals(1L)).thenReturn(List.of(medal));
mockMvc
.perform(get("/api/medals"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("评论达人"));
}
mockMvc.perform(get("/api/medals").param("userId", "1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].completed").value(true));
}
@Test
void listMedalsWithUser() throws Exception {
CommentMedalDto medal = new CommentMedalDto();
medal.setCompleted(true);
medal.setType(MedalType.COMMENT);
Mockito.when(medalService.getMedals(1L)).thenReturn(List.of(medal));
@Test
void selectMedal() throws Exception {
mockMvc.perform(post("/api/medals/select")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"type\":\"COMMENT\"}")
.principal(() -> "user"))
.andExpect(status().isOk());
}
mockMvc
.perform(get("/api/medals").param("userId", "1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].completed").value(true));
}
@Test
void selectMedalBadRequest() throws Exception {
Mockito.doThrow(new IllegalArgumentException()).when(medalService)
.selectMedal("user", MedalType.COMMENT);
mockMvc.perform(post("/api/medals/select")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"type\":\"COMMENT\"}")
.principal(() -> "user"))
.andExpect(status().isBadRequest());
}
@Test
void selectMedal() throws Exception {
mockMvc
.perform(
post("/api/medals/select")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"type\":\"COMMENT\"}")
.principal(() -> "user")
)
.andExpect(status().isOk());
}
@Test
void selectMedalBadRequest() throws Exception {
Mockito.doThrow(new IllegalArgumentException())
.when(medalService)
.selectMedal("user", MedalType.COMMENT);
mockMvc
.perform(
post("/api/medals/select")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"type\":\"COMMENT\"}")
.principal(() -> "user")
)
.andExpect(status().isBadRequest());
}
}

View File

@@ -1,5 +1,9 @@
package com.openisle.controller;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.openisle.dto.NotificationDto;
import com.openisle.dto.PostSummaryDto;
import com.openisle.mapper.NotificationMapper;
@@ -7,6 +11,8 @@ import com.openisle.model.Notification;
import com.openisle.model.NotificationType;
import com.openisle.model.Post;
import com.openisle.service.NotificationService;
import java.time.LocalDateTime;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
@@ -16,88 +22,92 @@ 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;
@Autowired
private MockMvc mockMvc;
@MockBean
private NotificationService notificationService;
@MockBean
private NotificationService notificationService;
@MockBean
private NotificationMapper notificationMapper;
@MockBean
private NotificationMapper notificationMapper;
@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());
when(notificationService.listNotifications("alice", null, 0, 30))
.thenReturn(List.of(n));
@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());
when(notificationService.listNotifications("alice", null, 0, 30)).thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
dto.setId(1L);
PostSummaryDto ps = new PostSummaryDto();
ps.setId(2L);
dto.setPost(ps);
when(notificationMapper.toDto(n)).thenReturn(dto);
NotificationDto dto = new NotificationDto();
dto.setId(1L);
PostSummaryDto ps = new PostSummaryDto();
ps.setId(2L);
dto.setPost(ps);
when(notificationMapper.toDto(n)).thenReturn(dto);
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));
}
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 listUnreadNotifications() throws Exception {
Notification n = new Notification();
n.setId(5L);
n.setType(NotificationType.POST_VIEWED);
when(notificationService.listNotifications("alice", false, 0, 30))
.thenReturn(List.of(n));
@Test
void listUnreadNotifications() throws Exception {
Notification n = new Notification();
n.setId(5L);
n.setType(NotificationType.POST_VIEWED);
when(notificationService.listNotifications("alice", false, 0, 30)).thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
dto.setId(5L);
when(notificationMapper.toDto(n)).thenReturn(dto);
NotificationDto dto = new NotificationDto();
dto.setId(5L);
when(notificationMapper.toDto(n)).thenReturn(dto);
mockMvc.perform(get("/api/notifications/unread")
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(5));
}
mockMvc
.perform(
get("/api/notifications/unread").principal(
new UsernamePasswordAuthenticationToken("alice", "p")
)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(5));
}
@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());
@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));
}
verify(notificationService).markRead("alice", List.of(1L, 2L));
}
@Test
void unreadCountEndpoint() throws Exception {
when(notificationService.countUnread("alice")).thenReturn(3L);
@Test
void unreadCountEndpoint() throws Exception {
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));
}
mockMvc
.perform(
get("/api/notifications/unread-count").principal(
new UsernamePasswordAuthenticationToken("alice", "p")
)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.count").value(3));
}
}

View File

@@ -1,13 +1,20 @@
package com.openisle.controller;
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;
import com.openisle.config.CustomAccessDeniedHandler;
import com.openisle.config.SecurityConfig;
import com.openisle.service.PointService;
import com.openisle.mapper.PointHistoryMapper;
import com.openisle.service.JwtService;
import com.openisle.repository.UserRepository;
import com.openisle.model.User;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.JwtService;
import com.openisle.service.PointService;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -17,49 +24,47 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import java.util.Map;
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(PointHistoryController.class)
@AutoConfigureMockMvc
@Import({SecurityConfig.class, CustomAccessDeniedHandler.class})
@Import({ SecurityConfig.class, CustomAccessDeniedHandler.class })
class PointHistoryControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private JwtService jwtService;
@MockBean
private UserRepository userRepository;
@MockBean
private PointService pointService;
@MockBean
private PointHistoryMapper pointHistoryMapper;
@Autowired
private MockMvc mockMvc;
@Test
void trendReturnsSeries() 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));
List<Map<String, Object>> data = List.of(
Map.of("date", java.time.LocalDate.now().minusDays(1).toString(), "value", 100),
Map.of("date", java.time.LocalDate.now().toString(), "value", 110)
);
Mockito.when(pointService.trend(Mockito.eq("user"), Mockito.anyInt())).thenReturn(data);
@MockBean
private JwtService jwtService;
mockMvc.perform(get("/api/point-histories/trend").param("days", "2")
.header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(100))
.andExpect(jsonPath("$[1].value").value(110));
}
@MockBean
private UserRepository userRepository;
@MockBean
private PointService pointService;
@MockBean
private PointHistoryMapper pointHistoryMapper;
@Test
void trendReturnsSeries() 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));
List<Map<String, Object>> data = List.of(
Map.of("date", java.time.LocalDate.now().minusDays(1).toString(), "value", 100),
Map.of("date", java.time.LocalDate.now().toString(), "value", 110)
);
Mockito.when(pointService.trend(Mockito.eq("user"), Mockito.anyInt())).thenReturn(data);
mockMvc
.perform(
get("/api/point-histories/trend").param("days", "2").header("Authorization", "Bearer token")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(100))
.andExpect(jsonPath("$[1].value").value(110));
}
}

View File

@@ -1,5 +1,10 @@
package com.openisle.controller;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.openisle.mapper.CategoryMapper;
import com.openisle.mapper.CommentMapper;
import com.openisle.mapper.PostMapper;
@@ -8,6 +13,9 @@ import com.openisle.mapper.TagMapper;
import com.openisle.mapper.UserMapper;
import com.openisle.model.*;
import com.openisle.service.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
@@ -15,297 +23,356 @@ 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.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.util.ReflectionTestUtils;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import static org.mockito.ArgumentMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.mockito.Mockito.*;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(PostController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import({PostMapper.class, CommentMapper.class, ReactionMapper.class,
UserMapper.class, TagMapper.class, CategoryMapper.class})
@Import(
{
PostMapper.class,
CommentMapper.class,
ReactionMapper.class,
UserMapper.class,
TagMapper.class,
CategoryMapper.class,
}
)
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;
@MockBean
private SubscriptionService subscriptionService;
@MockBean
private UserVisitService userVisitService;
@MockBean
private PostReadService postReadService;
@MockBean
private MedalService medalService;
@MockBean
private com.openisle.repository.PollVoteRepository pollVoteRepository;
@Autowired
private MockMvc mockMvc;
@Test
void createAndGetPost() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
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(Set.of(tag));
@Autowired
private PostController postController;
when(postService.createPost(eq("alice"), eq(1L), eq("t"), eq("c"), eq(List.of(1L)),
isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull())).thenReturn(post);
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
@MockBean
private PostService postService;
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"))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.author.username").value("alice"))
.andExpect(jsonPath("$.category.name").value("tech"))
.andExpect(jsonPath("$.tags[0].name").value("java"))
.andExpect(jsonPath("$.subscribed").value(false));
@MockBean
private CommentService commentService;
mockMvc.perform(get("/api/posts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.subscribed").value(false));
}
@MockBean
private ReactionService reactionService;
@Test
void updatePostReturnsDetailDto() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
Post post = new Post();
post.setId(1L);
post.setTitle("t2");
post.setContent("c2");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of(tag));
@MockBean
private CaptchaService captchaService;
when(postService.updatePost(eq(1L), eq("alice"), eq(1L), eq("t2"), eq("c2"), eq(List.of(1L)))).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
@MockBean
private DraftService draftService;
mockMvc.perform(put("/api/posts/1")
.contentType("application/json")
.content("{\"title\":\"t2\",\"content\":\"c2\",\"categoryId\":1,\"tagIds\":[1]}")
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("t2"))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.author.username").value("alice"));
}
@MockBean
private LevelService levelService;
@Test
void listPosts() throws Exception {
User user = new User();
user.setUsername("bob");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
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(Set.of(tag));
@MockBean
private SubscriptionService subscriptionService;
when(postService.listPostsByCategories(null, null, null)).thenReturn(List.of(post));
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(anyLong())).thenReturn(List.of());
when(commentService.getLastCommentTime(anyLong())).thenReturn(null);
@MockBean
private UserVisitService userVisitService;
mockMvc.perform(get("/api/posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("hello"))
.andExpect(jsonPath("$[0].comments").doesNotExist())
.andExpect(jsonPath("$[0].author.username").value("bob"))
.andExpect(jsonPath("$[0].category.name").value("tech"))
.andExpect(jsonPath("$[0].tags[0].name").value("java"))
.andExpect(jsonPath("$[0].subscribed").value(false));
}
@MockBean
private PostReadService postReadService;
@Test
void createPostRejectsInvalidCaptcha() throws Exception {
ReflectionTestUtils.setField(postController, "captchaEnabled", true);
ReflectionTestUtils.setField(postController, "postCaptchaEnabled", true);
when(captchaService.verify("bad")).thenReturn(false);
@MockBean
private MedalService medalService;
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());
@MockBean
private com.openisle.repository.PollVoteRepository pollVoteRepository;
verify(postService, never()).createPost(any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
void createAndGetPost() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
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(Set.of(tag));
@Test
void getPostWithNestedData() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
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(Set.of(tag));
when(
postService.createPost(
eq("alice"),
eq(1L),
eq("t"),
eq("c"),
eq(List.of(1L)),
isNull(),
isNull(),
isNull(),
isNull(),
isNull(),
isNull(),
isNull(),
isNull(),
isNull()
)
).thenReturn(post);
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
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);
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"))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.author.username").value("alice"))
.andExpect(jsonPath("$.category.name").value("tech"))
.andExpect(jsonPath("$.tags[0].name").value("java"))
.andExpect(jsonPath("$.subscribed").value(false));
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);
mockMvc
.perform(get("/api/posts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.subscribed").value(false));
}
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);
@Test
void updatePostReturnsDetailDto() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
Post post = new Post();
post.setId(1L);
post.setTitle("t2");
post.setContent("c2");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of(tag));
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);
when(
postService.updatePost(eq(1L), eq("alice"), eq(1L), eq("t2"), eq("c2"), eq(List.of(1L)))
).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of(comment));
when(commentService.getReplies(2L)).thenReturn(List.of(reply));
when(commentService.getReplies(3L)).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of(pr));
when(reactionService.getReactionsForComment(2L)).thenReturn(List.of(cr));
when(reactionService.getReactionsForComment(3L)).thenReturn(List.of());
mockMvc
.perform(
put("/api/posts/1")
.contentType("application/json")
.content("{\"title\":\"t2\",\"content\":\"c2\",\"categoryId\":1,\"tagIds\":[1]}")
.principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("t2"))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.author.username").value("alice"));
}
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))
.andExpect(jsonPath("$.author.username").value("alice"))
.andExpect(jsonPath("$.category.name").value("tech"))
.andExpect(jsonPath("$.tags[0].name").value("java"));
}
@Test
void listPosts() throws Exception {
User user = new User();
user.setUsername("bob");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
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(Set.of(tag));
@Test
void getPostSubscriptionStatus() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
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(Set.of());
when(postService.listPostsByCategories(null, null, null)).thenReturn(List.of(post));
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(anyLong())).thenReturn(List.of());
when(commentService.getLastCommentTime(anyLong())).thenReturn(null);
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
when(subscriptionService.isPostSubscribed("alice", 1L)).thenReturn(true);
mockMvc
.perform(get("/api/posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("hello"))
.andExpect(jsonPath("$[0].comments").doesNotExist())
.andExpect(jsonPath("$[0].author.username").value("bob"))
.andExpect(jsonPath("$[0].category.name").value("tech"))
.andExpect(jsonPath("$[0].tags[0].name").value("java"))
.andExpect(jsonPath("$[0].subscribed").value(false));
}
mockMvc.perform(get("/api/posts/1").principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.subscribed").value(true));
@Test
void createPostRejectsInvalidCaptcha() throws Exception {
ReflectionTestUtils.setField(postController, "captchaEnabled", true);
ReflectionTestUtils.setField(postController, "postCaptchaEnabled", true);
when(captchaService.verify("bad")).thenReturn(false);
mockMvc.perform(get("/api/posts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.subscribed").value(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(),
any(),
any(),
any(),
any(),
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");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
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(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);
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of(comment));
when(commentService.getReplies(2L)).thenReturn(List.of(reply));
when(commentService.getReplies(3L)).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of(pr));
when(reactionService.getReactionsForComment(2L)).thenReturn(List.of(cr));
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))
.andExpect(jsonPath("$.author.username").value("alice"))
.andExpect(jsonPath("$.category.name").value("tech"))
.andExpect(jsonPath("$.tags[0].name").value("java"));
}
@Test
void getPostSubscriptionStatus() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
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(Set.of());
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
when(subscriptionService.isPostSubscribed("alice", 1L)).thenReturn(true);
mockMvc
.perform(get("/api/posts/1").principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.subscribed").value(true));
mockMvc
.perform(get("/api/posts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.subscribed").value(false));
}
}

View File

@@ -1,5 +1,8 @@
package com.openisle.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.openisle.service.PushSubscriptionService;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
@@ -11,26 +14,26 @@ 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;
@Autowired
private MockMvc mockMvc;
@MockBean
private PushSubscriptionService pushSubscriptionService;
@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");
}
@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");
}
}

View File

@@ -1,14 +1,20 @@
package com.openisle.controller;
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 com.openisle.mapper.ReactionMapper;
import com.openisle.model.Comment;
import com.openisle.model.Message;
import com.openisle.model.Post;
import com.openisle.model.Reaction;
import com.openisle.model.ReactionType;
import com.openisle.model.User;
import com.openisle.model.Message;
import com.openisle.service.ReactionService;
import com.openisle.service.LevelService;
import com.openisle.mapper.ReactionMapper;
import com.openisle.service.ReactionService;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -19,91 +25,103 @@ import org.springframework.context.annotation.Import;
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)
@Import(ReactionMapper.class)
class ReactionControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private ReactionService reactionService;
@MockBean
private LevelService levelService;
@Autowired
private MockMvc mockMvc;
@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);
@MockBean
private ReactionService reactionService;
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));
}
@MockBean
private LevelService levelService;
@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);
@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/comments/2/reactions")
.contentType("application/json")
.content("{\"type\":\"RECOMMEND\"}")
.principal(new UsernamePasswordAuthenticationToken("u2", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.commentId").value(2));
}
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 reactToMessage() throws Exception {
User user = new User();
user.setUsername("u3");
Message message = new Message();
message.setId(3L);
Reaction reaction = new Reaction();
reaction.setId(3L);
reaction.setUser(user);
reaction.setMessage(message);
reaction.setType(ReactionType.LIKE);
Mockito.when(reactionService.reactToMessage(eq("u3"), eq(3L), eq(ReactionType.LIKE))).thenReturn(reaction);
@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/messages/3/reactions")
.contentType("application/json")
.content("{\"type\":\"LIKE\"}")
.principal(new UsernamePasswordAuthenticationToken("u3", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.messageId").value(3));
}
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"));
}
@Test
void reactToMessage() throws Exception {
User user = new User();
user.setUsername("u3");
Message message = new Message();
message.setId(3L);
Reaction reaction = new Reaction();
reaction.setId(3L);
reaction.setUser(user);
reaction.setMessage(message);
reaction.setType(ReactionType.LIKE);
Mockito.when(
reactionService.reactToMessage(eq("u3"), eq(3L), eq(ReactionType.LIKE))
).thenReturn(reaction);
mockMvc
.perform(
post("/api/messages/3/reactions")
.contentType("application/json")
.content("{\"type\":\"LIKE\"}")
.principal(new UsernamePasswordAuthenticationToken("u3", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.messageId").value(3));
}
@Test
void listReactionTypes() throws Exception {
mockMvc
.perform(get("/api/reaction-types"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0]").value("LIKE"));
}
}

View File

@@ -1,14 +1,18 @@
package com.openisle.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.openisle.dto.PostSummaryDto;
import com.openisle.dto.UserDto;
import com.openisle.mapper.PostMapper;
import com.openisle.mapper.UserMapper;
import com.openisle.model.Comment;
import com.openisle.model.Post;
import com.openisle.model.User;
import com.openisle.model.PostStatus;
import com.openisle.model.User;
import com.openisle.service.SearchService;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -17,94 +21,98 @@ 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;
@MockBean
private UserMapper userMapper;
@MockBean
private PostMapper postMapper;
@Autowired
private MockMvc mockMvc;
@Test
void userSearchEndpoint() throws Exception {
User user = new User();
user.setId(1L);
user.setUsername("alice");
Mockito.when(searchService.searchUsers("ali")).thenReturn(List.of(user));
UserDto userDto = new UserDto();
userDto.setId(1L);
userDto.setUsername("alice");
Mockito.when(userMapper.toDto(user)).thenReturn(userDto);
@MockBean
private SearchService searchService;
mockMvc.perform(get("/api/search/users").param("keyword", "ali"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].username").value("alice"));
}
@MockBean
private UserMapper userMapper;
@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)
));
@MockBean
private PostMapper postMapper;
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 userSearchEndpoint() throws Exception {
User user = new User();
user.setId(1L);
user.setUsername("alice");
Mockito.when(searchService.searchUsers("ali")).thenReturn(List.of(user));
UserDto userDto = new UserDto();
userDto.setId(1L);
userDto.setUsername("alice");
Mockito.when(userMapper.toDto(user)).thenReturn(userDto);
@Test
void searchPostsByTitle() throws Exception {
Post p = new Post();
p.setId(2L);
p.setTitle("spring");
Mockito.when(searchService.searchPostsByTitle("spr")).thenReturn(List.of(p));
PostSummaryDto summaryDto1 = new PostSummaryDto();
summaryDto1.setId(2L);
summaryDto1.setTitle("spring");
Mockito.when(postMapper.toSummaryDto(p)).thenReturn(summaryDto1);
mockMvc
.perform(get("/api/search/users").param("keyword", "ali"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].username").value("alice"));
}
mockMvc.perform(get("/api/search/posts/title").param("keyword", "spr"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("spring"));
}
@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)
)
);
@Test
void searchPosts() throws Exception {
Post p = new Post();
p.setId(5L);
p.setTitle("hello");
Mockito.when(searchService.searchPosts("he")).thenReturn(List.of(p));
PostSummaryDto summaryDto2 = new PostSummaryDto();
summaryDto2.setId(5L);
summaryDto2.setTitle("hello");
Mockito.when(postMapper.toSummaryDto(p)).thenReturn(summaryDto2);
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"));
}
mockMvc.perform(get("/api/search/posts").param("keyword", "he"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(5));
}
@Test
void searchPostsByTitle() throws Exception {
Post p = new Post();
p.setId(2L);
p.setTitle("spring");
Mockito.when(searchService.searchPostsByTitle("spr")).thenReturn(List.of(p));
PostSummaryDto summaryDto1 = new PostSummaryDto();
summaryDto1.setId(2L);
summaryDto1.setTitle("spring");
Mockito.when(postMapper.toSummaryDto(p)).thenReturn(summaryDto1);
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));
PostSummaryDto summaryDto2 = new PostSummaryDto();
summaryDto2.setId(5L);
summaryDto2.setTitle("hello");
Mockito.when(postMapper.toSummaryDto(p)).thenReturn(summaryDto2);
mockMvc
.perform(get("/api/search/posts").param("keyword", "he"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(5));
}
}

View File

@@ -1,13 +1,18 @@
package com.openisle.controller;
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;
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.service.StatService;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.JwtService;
import com.openisle.service.StatService;
import com.openisle.service.UserVisitService;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -17,121 +22,132 @@ 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})
@Import({ SecurityConfig.class, CustomAccessDeniedHandler.class })
class StatControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private JwtService jwtService;
@MockBean
private UserRepository userRepository;
@MockBean
private UserVisitService userVisitService;
@MockBean
private StatService statService;
@Autowired
private MockMvc mockMvc;
@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);
@MockBean
private JwtService jwtService;
mockMvc.perform(get("/api/stats/dau").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.dau").value(3));
}
@MockBean
private UserRepository userRepository;
@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);
@MockBean
private UserVisitService userVisitService;
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));
}
@MockBean
private StatService statService;
@Test
void newUsersRangeReturnsSeries() 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), 5L);
map.put(java.time.LocalDate.now(), 6L);
Mockito.when(statService.countNewUsersRange(Mockito.any(), Mockito.any())).thenReturn(map);
@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/new-users-range").param("days", "2").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(5))
.andExpect(jsonPath("$[1].value").value(6));
}
mockMvc
.perform(get("/api/stats/dau").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.dau").value(3));
}
@Test
void postsRangeReturnsSeries() 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), 7L);
map.put(java.time.LocalDate.now(), 8L);
Mockito.when(statService.countPostsRange(Mockito.any(), Mockito.any())).thenReturn(map);
@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/posts-range").param("days", "2").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(7))
.andExpect(jsonPath("$[1].value").value(8));
}
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));
}
@Test
void commentsRangeReturnsSeries() 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), 9L);
map.put(java.time.LocalDate.now(), 10L);
Mockito.when(statService.countCommentsRange(Mockito.any(), Mockito.any())).thenReturn(map);
@Test
void newUsersRangeReturnsSeries() 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), 5L);
map.put(java.time.LocalDate.now(), 6L);
Mockito.when(statService.countNewUsersRange(Mockito.any(), Mockito.any())).thenReturn(map);
mockMvc.perform(get("/api/stats/comments-range").param("days", "2").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(9))
.andExpect(jsonPath("$[1].value").value(10));
}
mockMvc
.perform(
get("/api/stats/new-users-range").param("days", "2").header("Authorization", "Bearer token")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(5))
.andExpect(jsonPath("$[1].value").value(6));
}
@Test
void postsRangeReturnsSeries() 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), 7L);
map.put(java.time.LocalDate.now(), 8L);
Mockito.when(statService.countPostsRange(Mockito.any(), Mockito.any())).thenReturn(map);
mockMvc
.perform(
get("/api/stats/posts-range").param("days", "2").header("Authorization", "Bearer token")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(7))
.andExpect(jsonPath("$[1].value").value(8));
}
@Test
void commentsRangeReturnsSeries() 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), 9L);
map.put(java.time.LocalDate.now(), 10L);
Mockito.when(statService.countCommentsRange(Mockito.any(), Mockito.any())).thenReturn(map);
mockMvc
.perform(
get("/api/stats/comments-range").param("days", "2").header("Authorization", "Bearer token")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(9))
.andExpect(jsonPath("$[1].value").value(10));
}
}

View File

@@ -1,11 +1,17 @@
package com.openisle.controller;
import com.openisle.mapper.TagMapper;
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.*;
import com.openisle.mapper.PostMapper;
import com.openisle.mapper.TagMapper;
import com.openisle.model.Tag;
import com.openisle.repository.UserRepository;
import com.openisle.service.TagService;
import com.openisle.service.PostService;
import com.openisle.service.TagService;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -16,94 +22,102 @@ import org.springframework.context.annotation.Import;
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)
@Import(TagMapper.class)
class TagControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private TagService tagService;
@Autowired
private MockMvc mockMvc;
@MockBean
private PostService postService;
@MockBean
private TagService tagService;
@MockBean
private UserRepository userRepository;
@MockBean
private PostService postService;
@MockBean
private PostMapper postMapper;
@MockBean
private UserRepository userRepository;
@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);
@MockBean
private PostMapper postMapper;
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"));
@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(get("/api/tags/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
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"));
@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.searchTags(null)).thenReturn(List.of(t));
mockMvc
.perform(get("/api/tags/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
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 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.searchTags(null)).thenReturn(List.of(t));
@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(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"));
}
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"));
}
@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"));
}
}

View File

@@ -1,12 +1,18 @@
package com.openisle.controller;
import com.openisle.model.User;
import com.openisle.service.*;
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.*;
import com.openisle.dto.CommentInfoDto;
import com.openisle.dto.PostMetaDto;
import com.openisle.dto.UserDto;
import com.openisle.mapper.TagMapper;
import com.openisle.mapper.UserMapper;
import com.openisle.dto.UserDto;
import com.openisle.dto.PostMetaDto;
import com.openisle.dto.CommentInfoDto;
import com.openisle.model.User;
import com.openisle.service.*;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -18,217 +24,254 @@ 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;
@MockBean
private TagService tagService;
@MockBean
private JwtService jwtService;
@MockBean
private UserMapper userMapper;
@MockBean
private TagMapper tagMapper;
@Autowired
private MockMvc mockMvc;
@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));
UserDto dto = new UserDto();
dto.setId(1L);
dto.setUsername("alice");
dto.setAvatar("http://x/avatar.png");
Mockito.when(userMapper.toDto(eq(u), any())).thenReturn(dto);
@MockBean
private ReactionService reactionService;
mockMvc.perform(get("/api/users/me").principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.avatar").value("http://x/avatar.png"));
}
@MockBean
private SubscriptionService subscriptionService;
@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"));
@MockBean
private UserService userService;
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"));
@MockBean
private ImageUploader imageUploader;
Mockito.verify(userService).updateAvatar("alice", "http://img/a.png");
}
@MockBean
private PostService postService;
@Test
void uploadAvatarRejectsNonImage() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "a.txt", MediaType.TEXT_PLAIN_VALUE, "text".getBytes());
@MockBean
private CommentService commentService;
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"));
@MockBean
private LevelService levelService;
Mockito.verify(imageUploader, Mockito.never()).upload(any(), any());
}
@MockBean
private TagService tagService;
@Test
void getUserByName() throws Exception {
User u = new User();
u.setId(2L);
u.setUsername("bob");
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(u));
UserDto dto = new UserDto();
dto.setId(2L);
dto.setUsername("bob");
Mockito.when(userMapper.toDto(eq(u), any())).thenReturn(dto);
@MockBean
private JwtService jwtService;
mockMvc.perform(get("/api/users/bob"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(2));
}
@MockBean
private UserMapper userMapper;
@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));
PostMetaDto meta = new PostMetaDto();
meta.setId(3L);
meta.setTitle("hello");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(meta);
@MockBean
private TagMapper tagMapper;
mockMvc.perform(get("/api/users/bob/posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("hello"));
}
@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));
UserDto dto = new UserDto();
dto.setId(1L);
dto.setUsername("alice");
dto.setAvatar("http://x/avatar.png");
Mockito.when(userMapper.toDto(eq(u), any())).thenReturn(dto);
@Test
void listSubscribedPosts() 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(6L);
post.setTitle("fav");
post.setCreatedAt(java.time.LocalDateTime.now());
post.setCategory(cat);
post.setAuthor(user);
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
Mockito.when(subscriptionService.getSubscribedPosts("bob")).thenReturn(java.util.List.of(post));
PostMetaDto meta = new PostMetaDto();
meta.setId(6L);
meta.setTitle("fav");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(meta);
mockMvc
.perform(
get("/api/users/me").principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.avatar").value("http://x/avatar.png"));
}
mockMvc.perform(get("/api/users/bob/subscribed-posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("fav"));
}
@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")
);
@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));
CommentInfoDto info = new CommentInfoDto();
info.setId(4L);
info.setContent("hi");
Mockito.when(userMapper.toCommentInfoDto(comment)).thenReturn(info);
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"));
mockMvc.perform(get("/api/users/bob/replies"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(4));
}
Mockito.verify(userService).updateAvatar("alice", "http://img/a.png");
}
@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);
@Test
void uploadAvatarRejectsNonImage() throws Exception {
MockMultipartFile file = new MockMultipartFile(
"file",
"a.txt",
MediaType.TEXT_PLAIN_VALUE,
"text".getBytes()
);
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));
UserDto dtoAgg = new UserDto();
dtoAgg.setId(2L);
dtoAgg.setUsername("bob");
Mockito.when(userMapper.toDto(eq(user), any())).thenReturn(dtoAgg);
PostMetaDto metaAgg = new PostMetaDto();
metaAgg.setId(3L);
metaAgg.setTitle("hello");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(metaAgg);
CommentInfoDto infoAgg = new CommentInfoDto();
infoAgg.setId(4L);
infoAgg.setContent("hi");
Mockito.when(userMapper.toCommentInfoDto(comment)).thenReturn(infoAgg);
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"));
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));
}
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));
UserDto dto = new UserDto();
dto.setId(2L);
dto.setUsername("bob");
Mockito.when(userMapper.toDto(eq(u), any())).thenReturn(dto);
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));
PostMetaDto meta = new PostMetaDto();
meta.setId(3L);
meta.setTitle("hello");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(meta);
mockMvc
.perform(get("/api/users/bob/posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("hello"));
}
@Test
void listSubscribedPosts() 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(6L);
post.setTitle("fav");
post.setCreatedAt(java.time.LocalDateTime.now());
post.setCategory(cat);
post.setAuthor(user);
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
Mockito.when(subscriptionService.getSubscribedPosts("bob")).thenReturn(java.util.List.of(post));
PostMetaDto meta = new PostMetaDto();
meta.setId(6L);
meta.setTitle("fav");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(meta);
mockMvc
.perform(get("/api/users/bob/subscribed-posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("fav"));
}
@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)
);
CommentInfoDto info = new CommentInfoDto();
info.setId(4L);
info.setContent("hi");
Mockito.when(userMapper.toCommentInfoDto(comment)).thenReturn(info);
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)
);
UserDto dtoAgg = new UserDto();
dtoAgg.setId(2L);
dtoAgg.setUsername("bob");
Mockito.when(userMapper.toDto(eq(user), any())).thenReturn(dtoAgg);
PostMetaDto metaAgg = new PostMetaDto();
metaAgg.setId(3L);
metaAgg.setTitle("hello");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(metaAgg);
CommentInfoDto infoAgg = new CommentInfoDto();
infoAgg.setId(4L);
infoAgg.setContent("hi");
Mockito.when(userMapper.toCommentInfoDto(comment)).thenReturn(infoAgg);
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));
}
}

View File

@@ -1,11 +1,16 @@
package com.openisle.integration;
import static org.junit.jupiter.api.Assertions.*;
import com.openisle.controller.ActivityController;
import com.openisle.model.User;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.AvatarGenerator;
import com.openisle.service.EmailSender;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@@ -13,151 +18,193 @@ 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")
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = "app.register.mode=DIRECT"
)
class ComplexFlowIntegrationTest {
@Autowired
private TestRestTemplate rest;
@Autowired
private TestRestTemplate rest;
@Autowired
private UserRepository users;
@Autowired
private UserRepository users;
@MockBean
private EmailSender emailService;
@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);
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;
}
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;
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();
}
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);
}
ResponseEntity<Map> tagResp = postJson(
"/api/tags",
Map.of("name", "spring", "description", "d", "icon", "i"),
adminToken
);
Long tagId = ((Number) tagResp.getBody().get("id")).longValue();
@Test
void nestedCommentsVisibleInPost() {
String t1 = registerAndLogin("alice1", "a@example.com");
String t2 = registerAndLogin("bob123", "b@example.com");
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();
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();
postJson("/api/posts/" + postId + "/reactions", Map.of("type", "LIKE"), t2);
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> cResp = postJson(
"/api/posts/" + postId + "/comments",
Map.of("content", "hi"),
t1
);
Long commentId = ((Number) cResp.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();
postJson("/api/comments/" + commentId + "/reactions", Map.of("type", "DISLIKE"), t2);
ResponseEntity<Map> c1Resp = postJson("/api/posts/" + postId + "/comments",
Map.of("content", "first"), t2);
Long c1 = ((Number)c1Resp.getBody().get("id")).longValue();
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"));
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"));
}
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"));
}
}

View File

@@ -1,10 +1,14 @@
package com.openisle.integration;
import static org.junit.jupiter.api.Assertions.*;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.EmailSender;
import com.openisle.service.PushNotificationService;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@@ -12,89 +16,119 @@ 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"})
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = { "app.post.publish-mode=REVIEW", "app.register.mode=DIRECT" }
)
class PublishModeIntegrationTest {
@Autowired
private TestRestTemplate rest;
@Autowired
private TestRestTemplate rest;
@Autowired
private UserRepository users;
@Autowired
private UserRepository users;
@MockBean
private EmailSender emailService;
@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 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 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 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);
}
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");
@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> 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> 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();
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<?> 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());
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);
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");
}
List<?> listAfter = rest.getForObject("/api/posts", List.class);
assertEquals(1, listAfter.size(), "Post should appear after approval");
}
}

View File

@@ -1,9 +1,13 @@
package com.openisle.integration;
import static org.junit.jupiter.api.Assertions.*;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.EmailSender;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@@ -11,76 +15,118 @@ 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")
@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");
@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 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 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");
@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", "niccat", "description", "d", "icon", "i"), admin);
Long catId = ((Number)catResp.getBody().get("id")).longValue();
ResponseEntity<Map> catResp = postJson(
"/api/categories",
Map.of("name", "niccat", "description", "d", "icon", "i"),
admin
);
Long catId = ((Number) catResp.getBody().get("id")).longValue();
ResponseEntity<Map> tagResp = postJson("/api/tags", Map.of("name", "nictag", "description", "d", "icon", "i"), admin);
Long tagId = ((Number)tagResp.getBody().get("id")).longValue();
ResponseEntity<Map> tagResp = postJson(
"/api/tags",
Map.of("name", "nictag", "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();
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);
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"))));
}
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"))));
}
}

View File

@@ -1,41 +1,51 @@
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.repository.PointHistoryRepository;
import com.openisle.service.PointService;
import com.openisle.exception.RateLimitException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.openisle.exception.RateLimitException;
import com.openisle.repository.CommentRepository;
import com.openisle.repository.CommentSubscriptionRepository;
import com.openisle.repository.NotificationRepository;
import com.openisle.repository.PointHistoryRepository;
import com.openisle.repository.PostRepository;
import com.openisle.repository.ReactionRepository;
import com.openisle.repository.UserRepository;
import com.openisle.service.PointService;
import org.junit.jupiter.api.Test;
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);
PointHistoryRepository pointHistoryRepo = mock(PointHistoryRepository.class);
PointService pointService = mock(PointService.class);
ImageUploader imageUploader = mock(ImageUploader.class);
CommentService service = new CommentService(commentRepo, postRepo, userRepo,
notifService, subService, reactionRepo, subRepo, nRepo, pointHistoryRepo, pointService, imageUploader);
@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);
PointHistoryRepository pointHistoryRepo = mock(PointHistoryRepository.class);
PointService pointService = mock(PointService.class);
ImageUploader imageUploader = mock(ImageUploader.class);
when(commentRepo.countByAuthorAfter(eq("alice"), any())).thenReturn(3L);
CommentService service = new CommentService(
commentRepo,
postRepo,
userRepo,
notifService,
subService,
reactionRepo,
subRepo,
nRepo,
pointHistoryRepo,
pointService,
imageUploader
);
assertThrows(RateLimitException.class,
() -> service.addComment("alice", 1L, "hi"));
}
when(commentRepo.countByAuthorAfter(eq("alice"), any())).thenReturn(3L);
assertThrows(RateLimitException.class, () -> service.addComment("alice", 1L, "hi"));
}
}

View File

@@ -1,23 +1,29 @@
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.*;
import com.openisle.repository.ImageRepository;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import org.junit.jupiter.api.Test;
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();
@Test
void uploadReturnsUrl() {
COSClient client = mock(COSClient.class);
ImageRepository repo = mock(ImageRepository.class);
CosImageUploader uploader = new CosImageUploader(
client,
repo,
"bucket",
"http://cos.example.com"
);
verify(client).putObject(any(PutObjectRequest.class));
assertTrue(url.matches("http://cos.example.com/dynamic_assert/[a-f0-9]{32}\\.png"));
}
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"));
}
}

View File

@@ -1,107 +1,165 @@
package com.openisle.service;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.openisle.dto.MedalDto;
import com.openisle.model.MedalType;
import com.openisle.model.User;
import com.openisle.repository.CommentRepository;
import com.openisle.repository.PostRepository;
import com.openisle.repository.UserRepository;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
class MedalServiceTest {
@Test
void getMedalsWithoutUser() {
CommentRepository commentRepo = mock(CommentRepository.class);
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
ContributorService contributorService = mock(ContributorService.class);
MedalService service = new MedalService(commentRepo, postRepo, userRepo, contributorService);
@Test
void getMedalsWithoutUser() {
CommentRepository commentRepo = mock(CommentRepository.class);
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
ContributorService contributorService = mock(ContributorService.class);
List<MedalDto> medals = service.getMedals(null);
medals.forEach(m -> assertFalse(m.isCompleted()));
assertEquals(6, medals.size());
}
MedalService service = new MedalService(commentRepo, postRepo, userRepo, contributorService);
@Test
void getMedalsWithUser() {
CommentRepository commentRepo = mock(CommentRepository.class);
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
ContributorService contributorService = mock(ContributorService.class);
List<MedalDto> medals = service.getMedals(null);
medals.forEach(m -> assertFalse(m.isCompleted()));
assertEquals(6, medals.size());
}
when(commentRepo.countByAuthor_Id(1L)).thenReturn(120L);
when(postRepo.countByAuthor_Id(1L)).thenReturn(80L);
when(contributorService.getContributionLines(anyString())).thenReturn(0L);
when(userRepo.countByCreatedAtBefore(any())).thenReturn(50L);
User user = new User();
user.setId(1L);
user.setCreatedAt(LocalDateTime.of(2025, 9, 15, 0, 0));
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
when(userRepo.findByUsername("user")).thenReturn(Optional.of(user));
@Test
void getMedalsWithUser() {
CommentRepository commentRepo = mock(CommentRepository.class);
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
ContributorService contributorService = mock(ContributorService.class);
MedalService service = new MedalService(commentRepo, postRepo, userRepo, contributorService);
List<MedalDto> medals = service.getMedals(1L);
when(commentRepo.countByAuthor_Id(1L)).thenReturn(120L);
when(postRepo.countByAuthor_Id(1L)).thenReturn(80L);
when(contributorService.getContributionLines(anyString())).thenReturn(0L);
when(userRepo.countByCreatedAtBefore(any())).thenReturn(50L);
User user = new User();
user.setId(1L);
user.setCreatedAt(LocalDateTime.of(2025, 9, 15, 0, 0));
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
when(userRepo.findByUsername("user")).thenReturn(Optional.of(user));
assertEquals(MedalType.COMMENT, user.getDisplayMedal());
assertTrue(medals.stream().filter(m -> m.getType() == MedalType.COMMENT).findFirst().orElseThrow().isCompleted());
assertTrue(medals.stream().filter(m -> m.getType() == MedalType.COMMENT).findFirst().orElseThrow().isSelected());
assertFalse(medals.stream().filter(m -> m.getType() == MedalType.POST).findFirst().orElseThrow().isCompleted());
assertFalse(medals.stream().filter(m -> m.getType() == MedalType.POST).findFirst().orElseThrow().isSelected());
assertTrue(medals.stream().filter(m -> m.getType() == MedalType.SEED).findFirst().orElseThrow().isCompleted());
assertFalse(medals.stream().filter(m -> m.getType() == MedalType.SEED).findFirst().orElseThrow().isSelected());
assertTrue(medals.stream().filter(m -> m.getType() == MedalType.PIONEER).findFirst().orElseThrow().isCompleted());
assertFalse(medals.stream().filter(m -> m.getType() == MedalType.PIONEER).findFirst().orElseThrow().isSelected());
verify(userRepo).save(user);
}
MedalService service = new MedalService(commentRepo, postRepo, userRepo, contributorService);
List<MedalDto> medals = service.getMedals(1L);
@Test
void selectMedal() {
CommentRepository commentRepo = mock(CommentRepository.class);
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
ContributorService contributorService = mock(ContributorService.class);
assertEquals(MedalType.COMMENT, user.getDisplayMedal());
assertTrue(
medals
.stream()
.filter(m -> m.getType() == MedalType.COMMENT)
.findFirst()
.orElseThrow()
.isCompleted()
);
assertTrue(
medals
.stream()
.filter(m -> m.getType() == MedalType.COMMENT)
.findFirst()
.orElseThrow()
.isSelected()
);
assertFalse(
medals
.stream()
.filter(m -> m.getType() == MedalType.POST)
.findFirst()
.orElseThrow()
.isCompleted()
);
assertFalse(
medals
.stream()
.filter(m -> m.getType() == MedalType.POST)
.findFirst()
.orElseThrow()
.isSelected()
);
assertTrue(
medals
.stream()
.filter(m -> m.getType() == MedalType.SEED)
.findFirst()
.orElseThrow()
.isCompleted()
);
assertFalse(
medals
.stream()
.filter(m -> m.getType() == MedalType.SEED)
.findFirst()
.orElseThrow()
.isSelected()
);
assertTrue(
medals
.stream()
.filter(m -> m.getType() == MedalType.PIONEER)
.findFirst()
.orElseThrow()
.isCompleted()
);
assertFalse(
medals
.stream()
.filter(m -> m.getType() == MedalType.PIONEER)
.findFirst()
.orElseThrow()
.isSelected()
);
verify(userRepo).save(user);
}
when(commentRepo.countByAuthor_Id(1L)).thenReturn(120L);
when(postRepo.countByAuthor_Id(1L)).thenReturn(0L);
when(contributorService.getContributionLines(anyString())).thenReturn(0L);
when(userRepo.countByCreatedAtBefore(any())).thenReturn(0L);
User user = new User();
user.setId(1L);
user.setCreatedAt(LocalDateTime.of(2025, 9, 15, 0, 0));
when(userRepo.findByUsername("user")).thenReturn(Optional.of(user));
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
@Test
void selectMedal() {
CommentRepository commentRepo = mock(CommentRepository.class);
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
ContributorService contributorService = mock(ContributorService.class);
MedalService service = new MedalService(commentRepo, postRepo, userRepo, contributorService);
service.selectMedal("user", MedalType.COMMENT);
assertEquals(MedalType.COMMENT, user.getDisplayMedal());
}
when(commentRepo.countByAuthor_Id(1L)).thenReturn(120L);
when(postRepo.countByAuthor_Id(1L)).thenReturn(0L);
when(contributorService.getContributionLines(anyString())).thenReturn(0L);
when(userRepo.countByCreatedAtBefore(any())).thenReturn(0L);
User user = new User();
user.setId(1L);
user.setCreatedAt(LocalDateTime.of(2025, 9, 15, 0, 0));
when(userRepo.findByUsername("user")).thenReturn(Optional.of(user));
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
@Test
void selectMedalNotCompleted() {
CommentRepository commentRepo = mock(CommentRepository.class);
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
ContributorService contributorService = mock(ContributorService.class);
MedalService service = new MedalService(commentRepo, postRepo, userRepo, contributorService);
service.selectMedal("user", MedalType.COMMENT);
assertEquals(MedalType.COMMENT, user.getDisplayMedal());
}
when(commentRepo.countByAuthor_Id(1L)).thenReturn(10L);
when(postRepo.countByAuthor_Id(1L)).thenReturn(0L);
when(contributorService.getContributionLines(anyString())).thenReturn(0L);
when(userRepo.countByCreatedAtBefore(any())).thenReturn(0L);
User user = new User();
user.setId(1L);
user.setCreatedAt(LocalDateTime.of(2025, 9, 15, 0, 0));
when(userRepo.findByUsername("user")).thenReturn(Optional.of(user));
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
@Test
void selectMedalNotCompleted() {
CommentRepository commentRepo = mock(CommentRepository.class);
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
ContributorService contributorService = mock(ContributorService.class);
MedalService service = new MedalService(commentRepo, postRepo, userRepo, contributorService);
assertThrows(IllegalArgumentException.class, () -> service.selectMedal("user", MedalType.COMMENT));
}
when(commentRepo.countByAuthor_Id(1L)).thenReturn(10L);
when(postRepo.countByAuthor_Id(1L)).thenReturn(0L);
when(contributorService.getContributionLines(anyString())).thenReturn(0L);
when(userRepo.countByCreatedAtBefore(any())).thenReturn(0L);
User user = new User();
user.setId(1L);
user.setCreatedAt(LocalDateTime.of(2025, 9, 15, 0, 0));
when(userRepo.findByUsername("user")).thenReturn(Optional.of(user));
when(userRepo.findById(1L)).thenReturn(Optional.of(user));
MedalService service = new MedalService(commentRepo, postRepo, userRepo, contributorService);
assertThrows(IllegalArgumentException.class, () ->
service.selectMedal("user", MedalType.COMMENT)
);
}
}

View File

@@ -1,274 +1,420 @@
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 java.util.HashSet;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.openisle.model.*;
import com.openisle.repository.NotificationRepository;
import com.openisle.repository.ReactionRepository;
import com.openisle.repository.UserRepository;
import com.openisle.service.PushNotificationService;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executor;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
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");
@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));
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));
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));
service.markRead("alice", List.of(10L, 11L));
assertTrue(n1.isRead());
assertTrue(n2.isRead());
verify(nRepo).saveAll(List.of(n1, n2));
}
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");
@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");
user.setDisabledNotificationTypes(new HashSet<>());
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
User user = new User();
user.setId(2L);
user.setUsername("bob");
user.setDisabledNotificationTypes(new HashSet<>());
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
Notification n = new Notification();
when(nRepo.findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(n)));
Notification n = new Notification();
when(nRepo.findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class))).thenReturn(
new PageImpl<>(List.of(n))
);
List<Notification> list = service.listNotifications("bob", null, 0, 10);
List<Notification> list = service.listNotifications("bob", null, 0, 10);
assertEquals(1, list.size());
verify(nRepo).findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class));
}
assertEquals(1, list.size());
verify(nRepo).findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class));
}
@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");
@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");
user.setDisabledNotificationTypes(new HashSet<>());
when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user));
when(nRepo.countByUserAndRead(user, false)).thenReturn(5L);
User user = new User();
user.setId(3L);
user.setUsername("carl");
user.setDisabledNotificationTypes(new HashSet<>());
when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user));
when(nRepo.countByUserAndRead(user, false)).thenReturn(5L);
long count = service.countUnread("carl");
long count = service.countUnread("carl");
assertEquals(5L, count);
verify(nRepo).countByUserAndRead(user, false);
}
assertEquals(5L, count);
verify(nRepo).countByUserAndRead(user, false);
}
@Test
void listNotificationsFiltersDisabledTypes() {
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");
@Test
void listNotificationsFiltersDisabledTypes() {
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(4L);
user.setUsername("dana");
when(uRepo.findByUsername("dana")).thenReturn(Optional.of(user));
User user = new User();
user.setId(4L);
user.setUsername("dana");
when(uRepo.findByUsername("dana")).thenReturn(Optional.of(user));
Notification n = new Notification();
when(nRepo.findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(n)));
Notification n = new Notification();
when(
nRepo.findByUserAndTypeNotInOrderByCreatedAtDesc(
eq(user),
eq(user.getDisabledNotificationTypes()),
any(Pageable.class)
)
).thenReturn(new PageImpl<>(List.of(n)));
List<Notification> list = service.listNotifications("dana", null, 0, 10);
List<Notification> list = service.listNotifications("dana", null, 0, 10);
assertEquals(1, list.size());
verify(nRepo).findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class));
}
assertEquals(1, list.size());
verify(nRepo).findByUserAndTypeNotInOrderByCreatedAtDesc(
eq(user),
eq(user.getDisabledNotificationTypes()),
any(Pageable.class)
);
}
@Test
void countUnreadFiltersDisabledTypes() {
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");
@Test
void countUnreadFiltersDisabledTypes() {
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(5L);
user.setUsername("erin");
when(uRepo.findByUsername("erin")).thenReturn(Optional.of(user));
when(nRepo.countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes())))
.thenReturn(2L);
User user = new User();
user.setId(5L);
user.setUsername("erin");
when(uRepo.findByUsername("erin")).thenReturn(Optional.of(user));
when(
nRepo.countByUserAndReadAndTypeNotIn(
eq(user),
eq(false),
eq(user.getDisabledNotificationTypes())
)
).thenReturn(2L);
long count = service.countUnread("erin");
long count = service.countUnread("erin");
assertEquals(2L, count);
verify(nRepo).countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes()));
}
assertEquals(2L, count);
verify(nRepo).countByUserAndReadAndTypeNotIn(
eq(user),
eq(false),
eq(user.getDisabledNotificationTypes())
);
}
@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");
@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);
User admin = new User();
admin.setId(10L);
User applicant = new User();
applicant.setId(20L);
when(uRepo.findByRole(Role.ADMIN)).thenReturn(List.of(admin));
when(uRepo.findByRole(Role.ADMIN)).thenReturn(List.of(admin));
service.createRegisterRequestNotifications(applicant, "reason");
service.createRegisterRequestNotifications(applicant, "reason");
verify(nRepo).deleteByTypeAndFromUser(NotificationType.REGISTER_REQUEST, applicant);
verify(nRepo).save(any(Notification.class));
}
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");
@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);
User admin = new User();
admin.setId(10L);
User user = new User();
user.setId(20L);
when(uRepo.findByRole(Role.ADMIN)).thenReturn(List.of(admin));
when(uRepo.findByRole(Role.ADMIN)).thenReturn(List.of(admin));
service.createActivityRedeemNotifications(user, "contact");
service.createActivityRedeemNotifications(user, "contact");
verify(nRepo).deleteByTypeAndFromUser(NotificationType.ACTIVITY_REDEEM, user);
verify(nRepo).save(any(Notification.class));
}
verify(nRepo).deleteByTypeAndFromUser(NotificationType.ACTIVITY_REDEEM, user);
verify(nRepo).save(any(Notification.class));
}
@Test
void createPointRedeemNotificationsDeletesOldOnes() {
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");
@Test
void createPointRedeemNotificationsDeletesOldOnes() {
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);
User admin = new User();
admin.setId(10L);
User user = new User();
user.setId(20L);
when(uRepo.findByRole(Role.ADMIN)).thenReturn(List.of(admin));
when(uRepo.findByRole(Role.ADMIN)).thenReturn(List.of(admin));
service.createPointRedeemNotifications(user, "contact");
service.createPointRedeemNotifications(user, "contact");
verify(nRepo).deleteByTypeAndFromUser(NotificationType.POINT_REDEEM, user);
verify(nRepo).save(any(Notification.class));
}
verify(nRepo).deleteByTypeAndFromUser(NotificationType.POINT_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");
@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));
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);
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"));
}
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");
@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();
User owner = new User();
User viewer = new User();
Post post = new Post();
when(nRepo.save(any(Notification.class))).thenAnswer(i -> i.getArgument(0));
when(nRepo.save(any(Notification.class))).thenAnswer(i -> i.getArgument(0));
service.createNotification(owner, NotificationType.POST_VIEWED, post, null, null, viewer, null, null);
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));
}
verify(nRepo).deleteByTypeAndFromUserAndPost(NotificationType.POST_VIEWED, viewer, post);
verify(nRepo).save(any(Notification.class));
}
}

View File

@@ -1,40 +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.*;
import com.openisle.exception.FieldException;
import com.openisle.model.PasswordStrength;
import org.junit.jupiter.api.Test;
class PasswordValidatorTest {
@Test
void lowStrengthRequiresSixChars() {
PasswordValidator validator = new PasswordValidator(PasswordStrength.LOW);
@Test
void lowStrengthRequiresSixChars() {
PasswordValidator validator = new PasswordValidator(PasswordStrength.LOW);
assertThrows(FieldException.class, () -> validator.validate("12345"));
assertDoesNotThrow(() -> validator.validate("123456"));
}
assertThrows(FieldException.class, () -> validator.validate("12345"));
assertDoesNotThrow(() -> validator.validate("123456"));
}
@Test
void mediumStrengthRules() {
PasswordValidator validator = new PasswordValidator(PasswordStrength.MEDIUM);
@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"));
}
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);
@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"));
}
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"));
}
}

View File

@@ -1,67 +1,66 @@
package com.openisle.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.openisle.model.PointHistory;
import com.openisle.model.PointHistoryType;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.PointHistoryRepository;
import com.openisle.repository.UserRepository;
import java.time.LocalDateTime;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import java.time.LocalDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
@DataJpaTest
@Import(PointService.class)
class PointServiceRecalculateUserPointsTest {
@Autowired
private PointService pointService;
@Autowired
private PointService pointService;
@Autowired
private UserRepository userRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private PointHistoryRepository pointHistoryRepository;
@Autowired
private PointHistoryRepository pointHistoryRepository;
@Test
void recalculatesBalanceAfterDeletion() {
User user = new User();
user.setUsername("u");
user.setEmail("u@example.com");
user.setPassword("p");
user.setRole(Role.USER);
userRepository.save(user);
@Test
void recalculatesBalanceAfterDeletion() {
User user = new User();
user.setUsername("u");
user.setEmail("u@example.com");
user.setPassword("p");
user.setRole(Role.USER);
userRepository.save(user);
PointHistory h1 = new PointHistory();
h1.setUser(user);
h1.setType(PointHistoryType.POST);
h1.setAmount(30);
h1.setBalance(30);
h1.setCreatedAt(LocalDateTime.now().minusMinutes(2));
pointHistoryRepository.save(h1);
PointHistory h1 = new PointHistory();
h1.setUser(user);
h1.setType(PointHistoryType.POST);
h1.setAmount(30);
h1.setBalance(30);
h1.setCreatedAt(LocalDateTime.now().minusMinutes(2));
pointHistoryRepository.save(h1);
PointHistory h2 = new PointHistory();
h2.setUser(user);
h2.setType(PointHistoryType.COMMENT);
h2.setAmount(10);
h2.setBalance(40);
h2.setCreatedAt(LocalDateTime.now().minusMinutes(1));
pointHistoryRepository.save(h2);
PointHistory h2 = new PointHistory();
h2.setUser(user);
h2.setType(PointHistoryType.COMMENT);
h2.setAmount(10);
h2.setBalance(40);
h2.setCreatedAt(LocalDateTime.now().minusMinutes(1));
pointHistoryRepository.save(h2);
user.setPoint(40);
userRepository.save(user);
user.setPoint(40);
userRepository.save(user);
pointHistoryRepository.delete(h1);
pointHistoryRepository.delete(h1);
int total = pointService.recalculateUserPoints(user);
int total = pointService.recalculateUserPoints(user);
assertEquals(10, total);
assertEquals(10, userRepository.findById(user.getId()).orElseThrow().getPoint());
assertEquals(10, pointHistoryRepository.findById(h2.getId()).orElseThrow().getBalance());
}
assertEquals(10, total);
assertEquals(10, userRepository.findById(user.getId()).orElseThrow().getPoint());
assertEquals(10, pointHistoryRepository.findById(h2.getId()).orElseThrow().getBalance());
}
}

View File

@@ -1,5 +1,7 @@
package com.openisle.service;
import static org.junit.jupiter.api.Assertions.*;
import com.openisle.model.*;
import com.openisle.repository.*;
import org.junit.jupiter.api.Test;
@@ -8,83 +10,81 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@TestPropertySource(locations = "classpath:application.properties")
@Transactional
public class PostCommentStatsTest {
@Autowired
private PostRepository postRepository;
@Autowired
private PostRepository postRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private TagRepository tagRepository;
@Autowired
private TagRepository tagRepository;
@Autowired
private CommentService commentService;
@Autowired
private CommentService commentService;
@Test
public void testPostCommentStatsUpdate() {
// Create test user
User user = new User();
user.setUsername("testuser");
user.setEmail("test@example.com");
user.setPassword("hash");
user = userRepository.save(user);
@Test
public void testPostCommentStatsUpdate() {
// Create test user
User user = new User();
user.setUsername("testuser");
user.setEmail("test@example.com");
user.setPassword("hash");
user = userRepository.save(user);
// Create test category
Category category = new Category();
category.setName("Test Category");
category.setDescription("Test Category Description");
category.setIcon("test-icon");
category = categoryRepository.save(category);
// Create test category
Category category = new Category();
category.setName("Test Category");
category.setDescription("Test Category Description");
category.setIcon("test-icon");
category = categoryRepository.save(category);
// Create test tag
Tag tag = new Tag();
tag.setName("Test Tag");
tag.setDescription("Test Tag Description");
tag.setIcon("test-tag-icon");
tag = tagRepository.save(tag);
// Create test tag
Tag tag = new Tag();
tag.setName("Test Tag");
tag.setDescription("Test Tag Description");
tag.setIcon("test-tag-icon");
tag = tagRepository.save(tag);
// Create test post
Post post = new Post();
post.setTitle("Test Post");
post.setContent("Test content");
post.setAuthor(user);
post.setCategory(category);
post.getTags().add(tag);
post.setStatus(PostStatus.PUBLISHED);
post.setCommentCount(0L);
post = postRepository.save(post);
// Create test post
Post post = new Post();
post.setTitle("Test Post");
post.setContent("Test content");
post.setAuthor(user);
post.setCategory(category);
post.getTags().add(tag);
post.setStatus(PostStatus.PUBLISHED);
post.setCommentCount(0L);
post = postRepository.save(post);
// Verify initial state
assertEquals(0L, post.getCommentCount());
assertNull(post.getLastReplyAt());
// Verify initial state
assertEquals(0L, post.getCommentCount());
assertNull(post.getLastReplyAt());
// Add a comment
commentService.addComment("testuser", post.getId(), "Test comment");
// Add a comment
commentService.addComment("testuser", post.getId(), "Test comment");
// Refresh post from database
post = postRepository.findById(post.getId()).orElseThrow();
// Refresh post from database
post = postRepository.findById(post.getId()).orElseThrow();
// Verify comment count and last reply time are updated
assertEquals(1L, post.getCommentCount());
assertNotNull(post.getLastReplyAt());
// Verify comment count and last reply time are updated
assertEquals(1L, post.getCommentCount());
assertNotNull(post.getLastReplyAt());
// Add another comment
commentService.addComment("testuser", post.getId(), "Another comment");
// Add another comment
commentService.addComment("testuser", post.getId(), "Another comment");
// Refresh post again
post = postRepository.findById(post.getId()).orElseThrow();
// Refresh post again
post = postRepository.findById(post.getId()).orElseThrow();
// Verify comment count is updated
assertEquals(2L, post.getCommentCount());
}
// Verify comment count is updated
assertEquals(2L, post.getCommentCount());
}
}

View File

@@ -1,300 +1,444 @@
package com.openisle.service;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.openisle.exception.RateLimitException;
import com.openisle.model.*;
import com.openisle.repository.*;
import com.openisle.exception.RateLimitException;
import org.junit.jupiter.api.Test;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.mockito.Mockito.*;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.TaskScheduler;
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);
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
PollPostRepository pollPostRepo = mock(PollPostRepository.class);
PollVoteRepository pollVoteRepo = mock(PollVoteRepository.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);
TaskScheduler taskScheduler = mock(TaskScheduler.class);
EmailSender emailSender = mock(EmailSender.class);
ApplicationContext context = mock(ApplicationContext.class);
PointService pointService = mock(PointService.class);
PostChangeLogService postChangeLogService = mock(PostChangeLogService.class);
PointHistoryRepository pointHistoryRepository = mock(PointHistoryRepository.class);
RedisTemplate redisTemplate = mock(RedisTemplate.class);
PostService service = new PostService(postRepo, userRepo, catRepo, tagRepo, lotteryRepo,
pollPostRepo, pollVoteRepo, notifService, subService, commentService, commentRepo,
reactionRepo, subRepo, notificationRepo, postReadService,
imageUploader, taskScheduler, emailSender, context, pointService, postChangeLogService,
pointHistoryRepository, PublishMode.DIRECT, redisTemplate);
when(context.getBean(PostService.class)).thenReturn(service);
@Test
void deletePostRemovesReads() {
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
CategoryRepository catRepo = mock(CategoryRepository.class);
TagRepository tagRepo = mock(TagRepository.class);
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
PollPostRepository pollPostRepo = mock(PollPostRepository.class);
PollVoteRepository pollVoteRepo = mock(PollVoteRepository.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);
TaskScheduler taskScheduler = mock(TaskScheduler.class);
EmailSender emailSender = mock(EmailSender.class);
ApplicationContext context = mock(ApplicationContext.class);
PointService pointService = mock(PointService.class);
PostChangeLogService postChangeLogService = mock(PostChangeLogService.class);
PointHistoryRepository pointHistoryRepository = mock(PointHistoryRepository.class);
RedisTemplate redisTemplate = mock(RedisTemplate.class);
Post post = new Post();
post.setId(1L);
User author = new User();
author.setId(1L);
author.setRole(Role.USER);
post.setAuthor(author);
PostService service = new PostService(
postRepo,
userRepo,
catRepo,
tagRepo,
lotteryRepo,
pollPostRepo,
pollVoteRepo,
notifService,
subService,
commentService,
commentRepo,
reactionRepo,
subRepo,
notificationRepo,
postReadService,
imageUploader,
taskScheduler,
emailSender,
context,
pointService,
postChangeLogService,
pointHistoryRepository,
PublishMode.DIRECT,
redisTemplate
);
when(context.getBean(PostService.class)).thenReturn(service);
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());
when(pointHistoryRepository.findByPost(post)).thenReturn(List.of());
Post post = new Post();
post.setId(1L);
User author = new User();
author.setId(1L);
author.setRole(Role.USER);
post.setAuthor(author);
service.deletePost(1L, "alice");
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());
when(pointHistoryRepository.findByPost(post)).thenReturn(List.of());
verify(postReadService).deleteByPost(post);
verify(postRepo).delete(post);
verify(postChangeLogService).deleteLogsForPost(post);
}
service.deletePost(1L, "alice");
@Test
void deletePostByAdminNotifiesAuthor() {
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
CategoryRepository catRepo = mock(CategoryRepository.class);
TagRepository tagRepo = mock(TagRepository.class);
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
PollPostRepository pollPostRepo = mock(PollPostRepository.class);
PollVoteRepository pollVoteRepo = mock(PollVoteRepository.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);
TaskScheduler taskScheduler = mock(TaskScheduler.class);
EmailSender emailSender = mock(EmailSender.class);
ApplicationContext context = mock(ApplicationContext.class);
PointService pointService = mock(PointService.class);
PostChangeLogService postChangeLogService = mock(PostChangeLogService.class);
PointHistoryRepository pointHistoryRepository = mock(PointHistoryRepository.class);
RedisTemplate redisTemplate = mock(RedisTemplate.class);
verify(postReadService).deleteByPost(post);
verify(postRepo).delete(post);
verify(postChangeLogService).deleteLogsForPost(post);
}
PostService service = new PostService(postRepo, userRepo, catRepo, tagRepo, lotteryRepo,
pollPostRepo, pollVoteRepo, notifService, subService, commentService, commentRepo,
reactionRepo, subRepo, notificationRepo, postReadService,
imageUploader, taskScheduler, emailSender, context, pointService, postChangeLogService,
pointHistoryRepository, PublishMode.DIRECT, redisTemplate);
when(context.getBean(PostService.class)).thenReturn(service);
@Test
void deletePostByAdminNotifiesAuthor() {
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
CategoryRepository catRepo = mock(CategoryRepository.class);
TagRepository tagRepo = mock(TagRepository.class);
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
PollPostRepository pollPostRepo = mock(PollPostRepository.class);
PollVoteRepository pollVoteRepo = mock(PollVoteRepository.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);
TaskScheduler taskScheduler = mock(TaskScheduler.class);
EmailSender emailSender = mock(EmailSender.class);
ApplicationContext context = mock(ApplicationContext.class);
PointService pointService = mock(PointService.class);
PostChangeLogService postChangeLogService = mock(PostChangeLogService.class);
PointHistoryRepository pointHistoryRepository = mock(PointHistoryRepository.class);
RedisTemplate redisTemplate = mock(RedisTemplate.class);
Post post = new Post();
post.setId(1L);
post.setTitle("T");
post.setContent("");
User author = new User();
author.setId(2L);
author.setRole(Role.USER);
post.setAuthor(author);
PostService service = new PostService(
postRepo,
userRepo,
catRepo,
tagRepo,
lotteryRepo,
pollPostRepo,
pollVoteRepo,
notifService,
subService,
commentService,
commentRepo,
reactionRepo,
subRepo,
notificationRepo,
postReadService,
imageUploader,
taskScheduler,
emailSender,
context,
pointService,
postChangeLogService,
pointHistoryRepository,
PublishMode.DIRECT,
redisTemplate
);
when(context.getBean(PostService.class)).thenReturn(service);
User admin = new User();
admin.setId(1L);
admin.setRole(Role.ADMIN);
Post post = new Post();
post.setId(1L);
post.setTitle("T");
post.setContent("");
User author = new User();
author.setId(2L);
author.setRole(Role.USER);
post.setAuthor(author);
when(postRepo.findById(1L)).thenReturn(Optional.of(post));
when(userRepo.findByUsername("admin")).thenReturn(Optional.of(admin));
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());
when(pointHistoryRepository.findByPost(post)).thenReturn(List.of());
User admin = new User();
admin.setId(1L);
admin.setRole(Role.ADMIN);
service.deletePost(1L, "admin");
when(postRepo.findById(1L)).thenReturn(Optional.of(post));
when(userRepo.findByUsername("admin")).thenReturn(Optional.of(admin));
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());
when(pointHistoryRepository.findByPost(post)).thenReturn(List.of());
verify(notifService).createNotification(eq(author), eq(NotificationType.POST_DELETED), isNull(),
isNull(), isNull(), eq(admin), isNull(), eq("T"));
}
service.deletePost(1L, "admin");
@Test
void createPostRespectsRateLimit() {
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
CategoryRepository catRepo = mock(CategoryRepository.class);
TagRepository tagRepo = mock(TagRepository.class);
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
PollPostRepository pollPostRepo = mock(PollPostRepository.class);
PollVoteRepository pollVoteRepo = mock(PollVoteRepository.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);
TaskScheduler taskScheduler = mock(TaskScheduler.class);
EmailSender emailSender = mock(EmailSender.class);
ApplicationContext context = mock(ApplicationContext.class);
PointService pointService = mock(PointService.class);
PostChangeLogService postChangeLogService = mock(PostChangeLogService.class);
PointHistoryRepository pointHistoryRepository = mock(PointHistoryRepository.class);
RedisTemplate redisTemplate = mock(RedisTemplate.class);
verify(notifService).createNotification(
eq(author),
eq(NotificationType.POST_DELETED),
isNull(),
isNull(),
isNull(),
eq(admin),
isNull(),
eq("T")
);
}
PostService service = new PostService(postRepo, userRepo, catRepo, tagRepo, lotteryRepo,
pollPostRepo, pollVoteRepo, notifService, subService, commentService, commentRepo,
reactionRepo, subRepo, notificationRepo, postReadService,
imageUploader, taskScheduler, emailSender, context, pointService, postChangeLogService,
pointHistoryRepository, PublishMode.DIRECT, redisTemplate);
when(context.getBean(PostService.class)).thenReturn(service);
@Test
void createPostRespectsRateLimit() {
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
CategoryRepository catRepo = mock(CategoryRepository.class);
TagRepository tagRepo = mock(TagRepository.class);
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
PollPostRepository pollPostRepo = mock(PollPostRepository.class);
PollVoteRepository pollVoteRepo = mock(PollVoteRepository.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);
TaskScheduler taskScheduler = mock(TaskScheduler.class);
EmailSender emailSender = mock(EmailSender.class);
ApplicationContext context = mock(ApplicationContext.class);
PointService pointService = mock(PointService.class);
PostChangeLogService postChangeLogService = mock(PostChangeLogService.class);
PointHistoryRepository pointHistoryRepository = mock(PointHistoryRepository.class);
RedisTemplate redisTemplate = mock(RedisTemplate.class);
when(postRepo.countByAuthorAfter(eq("alice"), any())).thenReturn(1L);
PostService service = new PostService(
postRepo,
userRepo,
catRepo,
tagRepo,
lotteryRepo,
pollPostRepo,
pollVoteRepo,
notifService,
subService,
commentService,
commentRepo,
reactionRepo,
subRepo,
notificationRepo,
postReadService,
imageUploader,
taskScheduler,
emailSender,
context,
pointService,
postChangeLogService,
pointHistoryRepository,
PublishMode.DIRECT,
redisTemplate
);
when(context.getBean(PostService.class)).thenReturn(service);
assertThrows(RateLimitException.class,
() -> service.createPost("alice", 1L, "t", "c", List.of(1L),
null, null, null, null, null, null, null, null, null));
}
when(postRepo.countByAuthorAfter(eq("alice"), any())).thenReturn(1L);
@Test
void deletePostRemovesPointHistoriesAndRecalculatesPoints() {
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
CategoryRepository catRepo = mock(CategoryRepository.class);
TagRepository tagRepo = mock(TagRepository.class);
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
PollPostRepository pollPostRepo = mock(PollPostRepository.class);
PollVoteRepository pollVoteRepo = mock(PollVoteRepository.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);
TaskScheduler taskScheduler = mock(TaskScheduler.class);
EmailSender emailSender = mock(EmailSender.class);
ApplicationContext context = mock(ApplicationContext.class);
PointService pointService = mock(PointService.class);
PostChangeLogService postChangeLogService = mock(PostChangeLogService.class);
PointHistoryRepository pointHistoryRepository = mock(PointHistoryRepository.class);
RedisTemplate redisTemplate = mock(RedisTemplate.class);
assertThrows(RateLimitException.class, () ->
service.createPost(
"alice",
1L,
"t",
"c",
List.of(1L),
null,
null,
null,
null,
null,
null,
null,
null,
null
)
);
}
PostService service = new PostService(postRepo, userRepo, catRepo, tagRepo, lotteryRepo,
pollPostRepo, pollVoteRepo, notifService, subService, commentService, commentRepo,
reactionRepo, subRepo, notificationRepo, postReadService,
imageUploader, taskScheduler, emailSender, context, pointService, postChangeLogService,
pointHistoryRepository, PublishMode.DIRECT, redisTemplate);
when(context.getBean(PostService.class)).thenReturn(service);
@Test
void deletePostRemovesPointHistoriesAndRecalculatesPoints() {
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
CategoryRepository catRepo = mock(CategoryRepository.class);
TagRepository tagRepo = mock(TagRepository.class);
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
PollPostRepository pollPostRepo = mock(PollPostRepository.class);
PollVoteRepository pollVoteRepo = mock(PollVoteRepository.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);
TaskScheduler taskScheduler = mock(TaskScheduler.class);
EmailSender emailSender = mock(EmailSender.class);
ApplicationContext context = mock(ApplicationContext.class);
PointService pointService = mock(PointService.class);
PostChangeLogService postChangeLogService = mock(PostChangeLogService.class);
PointHistoryRepository pointHistoryRepository = mock(PointHistoryRepository.class);
RedisTemplate redisTemplate = mock(RedisTemplate.class);
Post post = new Post();
post.setId(10L);
User author = new User();
author.setId(20L);
author.setRole(Role.USER);
post.setAuthor(author);
PostService service = new PostService(
postRepo,
userRepo,
catRepo,
tagRepo,
lotteryRepo,
pollPostRepo,
pollVoteRepo,
notifService,
subService,
commentService,
commentRepo,
reactionRepo,
subRepo,
notificationRepo,
postReadService,
imageUploader,
taskScheduler,
emailSender,
context,
pointService,
postChangeLogService,
pointHistoryRepository,
PublishMode.DIRECT,
redisTemplate
);
when(context.getBean(PostService.class)).thenReturn(service);
User historyUser = new User();
historyUser.setId(30L);
Post post = new Post();
post.setId(10L);
User author = new User();
author.setId(20L);
author.setRole(Role.USER);
post.setAuthor(author);
PointHistory history = new PointHistory();
history.setUser(historyUser);
history.setPost(post);
User historyUser = new User();
historyUser.setId(30L);
when(postRepo.findById(10L)).thenReturn(Optional.of(post));
when(userRepo.findByUsername("author")).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());
when(pointHistoryRepository.findByPost(post)).thenReturn(List.of(history));
when(pointService.recalculateUserPoints(historyUser)).thenReturn(0);
PointHistory history = new PointHistory();
history.setUser(historyUser);
history.setPost(post);
service.deletePost(10L, "author");
when(postRepo.findById(10L)).thenReturn(Optional.of(post));
when(userRepo.findByUsername("author")).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());
when(pointHistoryRepository.findByPost(post)).thenReturn(List.of(history));
when(pointService.recalculateUserPoints(historyUser)).thenReturn(0);
ArgumentCaptor<List<PointHistory>> captor = ArgumentCaptor.forClass(List.class);
verify(pointHistoryRepository).saveAll(captor.capture());
List<PointHistory> savedHistories = captor.getValue();
assertEquals(1, savedHistories.size());
PointHistory savedHistory = savedHistories.get(0);
assertNull(savedHistory.getPost());
assertNotNull(savedHistory.getDeletedAt());
assertTrue(savedHistory.getDeletedAt().isBefore(LocalDateTime.now().plusSeconds(1)));
service.deletePost(10L, "author");
verify(pointService).recalculateUserPoints(historyUser);
verify(userRepo).saveAll(any());
}
ArgumentCaptor<List<PointHistory>> captor = ArgumentCaptor.forClass(List.class);
verify(pointHistoryRepository).saveAll(captor.capture());
List<PointHistory> savedHistories = captor.getValue();
assertEquals(1, savedHistories.size());
PointHistory savedHistory = savedHistories.get(0);
assertNull(savedHistory.getPost());
assertNotNull(savedHistory.getDeletedAt());
assertTrue(savedHistory.getDeletedAt().isBefore(LocalDateTime.now().plusSeconds(1)));
@Test
void finalizeLotteryNotifiesAuthor() {
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
CategoryRepository catRepo = mock(CategoryRepository.class);
TagRepository tagRepo = mock(TagRepository.class);
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
PollPostRepository pollPostRepo = mock(PollPostRepository.class);
PollVoteRepository pollVoteRepo = mock(PollVoteRepository.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);
TaskScheduler taskScheduler = mock(TaskScheduler.class);
EmailSender emailSender = mock(EmailSender.class);
ApplicationContext context = mock(ApplicationContext.class);
PointService pointService = mock(PointService.class);
PostChangeLogService postChangeLogService = mock(PostChangeLogService.class);
PointHistoryRepository pointHistoryRepository = mock(PointHistoryRepository.class);
RedisTemplate redisTemplate = mock(RedisTemplate.class);
verify(pointService).recalculateUserPoints(historyUser);
verify(userRepo).saveAll(any());
}
PostService service = new PostService(postRepo, userRepo, catRepo, tagRepo, lotteryRepo,
pollPostRepo, pollVoteRepo, notifService, subService, commentService, commentRepo,
reactionRepo, subRepo, notificationRepo, postReadService,
imageUploader, taskScheduler, emailSender, context, pointService, postChangeLogService,
pointHistoryRepository, PublishMode.DIRECT, redisTemplate);
when(context.getBean(PostService.class)).thenReturn(service);
@Test
void finalizeLotteryNotifiesAuthor() {
PostRepository postRepo = mock(PostRepository.class);
UserRepository userRepo = mock(UserRepository.class);
CategoryRepository catRepo = mock(CategoryRepository.class);
TagRepository tagRepo = mock(TagRepository.class);
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
PollPostRepository pollPostRepo = mock(PollPostRepository.class);
PollVoteRepository pollVoteRepo = mock(PollVoteRepository.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);
TaskScheduler taskScheduler = mock(TaskScheduler.class);
EmailSender emailSender = mock(EmailSender.class);
ApplicationContext context = mock(ApplicationContext.class);
PointService pointService = mock(PointService.class);
PostChangeLogService postChangeLogService = mock(PostChangeLogService.class);
PointHistoryRepository pointHistoryRepository = mock(PointHistoryRepository.class);
RedisTemplate redisTemplate = mock(RedisTemplate.class);
User author = new User();
author.setId(1L);
User winner = new User();
winner.setId(2L);
PostService service = new PostService(
postRepo,
userRepo,
catRepo,
tagRepo,
lotteryRepo,
pollPostRepo,
pollVoteRepo,
notifService,
subService,
commentService,
commentRepo,
reactionRepo,
subRepo,
notificationRepo,
postReadService,
imageUploader,
taskScheduler,
emailSender,
context,
pointService,
postChangeLogService,
pointHistoryRepository,
PublishMode.DIRECT,
redisTemplate
);
when(context.getBean(PostService.class)).thenReturn(service);
LotteryPost lp = new LotteryPost();
lp.setId(1L);
lp.setAuthor(author);
lp.setTitle("L");
lp.setPrizeCount(1);
lp.getParticipants().add(winner);
User author = new User();
author.setId(1L);
User winner = new User();
winner.setId(2L);
when(lotteryRepo.findById(1L)).thenReturn(Optional.of(lp));
LotteryPost lp = new LotteryPost();
lp.setId(1L);
lp.setAuthor(author);
lp.setTitle("L");
lp.setPrizeCount(1);
lp.getParticipants().add(winner);
service.finalizeLottery(1L);
when(lotteryRepo.findById(1L)).thenReturn(Optional.of(lp));
verify(notifService).createNotification(eq(winner), eq(NotificationType.LOTTERY_WIN), eq(lp), isNull(), isNull(), eq(author), isNull(), isNull());
verify(notifService).createNotification(eq(author), eq(NotificationType.LOTTERY_DRAW), eq(lp), isNull(), isNull(), isNull(), isNull(), isNull());
}
service.finalizeLottery(1L);
verify(notifService).createNotification(
eq(winner),
eq(NotificationType.LOTTERY_WIN),
eq(lp),
isNull(),
isNull(),
eq(author),
isNull(),
isNull()
);
verify(notifService).createNotification(
eq(author),
eq(NotificationType.LOTTERY_DRAW),
eq(lp),
isNull(),
isNull(),
isNull(),
isNull(),
isNull()
);
}
}

View File

@@ -1,45 +1,59 @@
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.*;
import com.openisle.model.*;
import com.openisle.repository.*;
import java.util.Optional;
import org.junit.jupiter.api.Test;
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);
MessageRepository messageRepo = mock(MessageRepository.class);
NotificationService notif = mock(NotificationService.class);
EmailSender email = mock(EmailSender.class);
ReactionService service = new ReactionService(reactionRepo, userRepo, postRepo, commentRepo, messageRepo, 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);
@Test
void reactToPostSendsEmailEveryFive() {
ReactionRepository reactionRepo = mock(ReactionRepository.class);
UserRepository userRepo = mock(UserRepository.class);
PostRepository postRepo = mock(PostRepository.class);
CommentRepository commentRepo = mock(CommentRepository.class);
MessageRepository messageRepo = mock(MessageRepository.class);
NotificationService notif = mock(NotificationService.class);
EmailSender email = mock(EmailSender.class);
ReactionService service = new ReactionService(
reactionRepo,
userRepo,
postRepo,
commentRepo,
messageRepo,
notif,
email
);
org.springframework.test.util.ReflectionTestUtils.setField(
service,
"websiteUrl",
"https://ex.com"
);
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);
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);
service.reactToPost("bob", 3L, ReactionType.LIKE);
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);
verify(email).sendEmail("a@a.com", "你有新的互动", "https://ex.com/messages");
verify(notif).sendCustomPush(author, "你有新的互动", "https://ex.com/messages");
}
service.reactToPost("bob", 3L, ReactionType.LIKE);
verify(email).sendEmail("a@a.com", "你有新的互动", "https://ex.com/messages");
verify(notif).sendCustomPush(author, "你有新的互动", "https://ex.com/messages");
}
}

View File

@@ -1,51 +1,66 @@
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.*;
import com.openisle.model.Post;
import com.openisle.model.PostStatus;
import com.openisle.repository.CategoryRepository;
import com.openisle.repository.CommentRepository;
import com.openisle.repository.PostRepository;
import com.openisle.repository.TagRepository;
import com.openisle.repository.UserRepository;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
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);
@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");
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());
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");
List<SearchService.SearchResult> results = service.globalSearch("h");
assertEquals(2, results.size());
assertEquals(1L, results.get(0).id());
assertEquals(2L, results.get(1).id());
}
assertEquals(2, results.size());
assertEquals(1L, results.get(0).id());
assertEquals(2L, results.get(1).id());
}
}

View File

@@ -1,22 +1,22 @@
package com.openisle.service;
import static org.junit.jupiter.api.Assertions.*;
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 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"));
}
@Test
void allowsShortUsername() {
UsernameValidator validator = new UsernameValidator();
assertDoesNotThrow(() -> validator.validate("a"));
}
}