Skip to content

Commit 8ef30d5

Browse files
authored
Merge pull request #328 from zockicookie/main
[Backend] - Fix disabled tests #322
2 parents 4298867 + 8b0f6ae commit 8ef30d5

5 files changed

Lines changed: 129 additions & 63 deletions

File tree

server/src/main/java/dev/findfirst/core/config/FileSizeValidator.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
@Component
1111
public class FileSizeValidator implements ConstraintValidator<FileSize, MultipartFile> {
12-
@Value("${findfirst.upload.max-file-size:}")
12+
@Value("${findfirst.upload.max-file-size}")
1313
private int maxFileSize;
1414

1515
@Override

server/src/main/java/dev/findfirst/users/controller/UserController.java

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,7 @@
4242
import org.springframework.http.MediaType;
4343
import org.springframework.http.ResponseCookie;
4444
import org.springframework.http.ResponseEntity;
45-
import org.springframework.web.bind.annotation.GetMapping;
46-
import org.springframework.web.bind.annotation.PostMapping;
47-
import org.springframework.web.bind.annotation.RequestBody;
48-
import org.springframework.web.bind.annotation.RequestHeader;
49-
import org.springframework.web.bind.annotation.RequestMapping;
50-
import org.springframework.web.bind.annotation.RequestParam;
51-
import org.springframework.web.bind.annotation.RestController;
45+
import org.springframework.web.bind.annotation.*;
5246
import org.springframework.web.multipart.MultipartFile;
5347

5448
@RestController
@@ -72,7 +66,6 @@ public class UserController {
7266
@Value("${findfirst.app.domain}")
7367
private String domain;
7468

75-
7669
@Value("${findfirst.upload.allowed-types}")
7770
private String[] allowedTypes;
7871

@@ -82,6 +75,7 @@ public ResponseEntity<String> registerUser(@Valid @RequestBody SignupRequest sig
8275
try {
8376
user = userService.createNewUserAccount(signUpRequest);
8477
} catch (UserNameTakenException | EmailAlreadyRegisteredException | UnexpectedException e) {
78+
log.debug(e.getMessage());
8579
return ResponseEntity.badRequest().body(e.getMessage());
8680
}
8781

@@ -173,12 +167,14 @@ public ResponseEntity<String> refreshToken(
173167
}
174168

175169
@PostMapping("/profile-picture")
176-
public ResponseEntity<?> uploadProfilePicture(
177-
@RequestParam("file") @FileSize MultipartFile file) {
170+
public ResponseEntity<String> uploadProfilePicture(
171+
@Valid @RequestParam("file") @FileSize MultipartFile file) {
172+
log.debug("saving profile picture");
178173

179174
// File type validation
180175
String contentType = file.getContentType();
181176
if (Arrays.stream(allowedTypes).noneMatch(contentType::equals)) {
177+
log.debug("Attempt upload wrong file type");
182178
return ResponseEntity.badRequest().body("Invalid file type. Only JPG and PNG are allowed.");
183179
}
184180

@@ -191,6 +187,7 @@ public ResponseEntity<?> uploadProfilePicture(
191187
} catch (NoUserFoundException e) {
192188
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found.");
193189
} catch (Exception e) {
190+
log.debug(e.getMessage());
194191
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file.");
195192
}
196193
}

server/src/main/java/dev/findfirst/users/model/user/User.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ public User(SignupRequest signup, String encodedPasswd) {
2727
this(signup.username(), signup.email(), encodedPasswd, false);
2828
}
2929

30+
// For testing purposes only!
31+
public User(int userId, String username, String userPhoto) {
32+
this.userId = userId;
33+
this.username = username;
34+
this.userPhoto = userPhoto;
35+
}
36+
3037
@Id
3138
@Column("user_id")
3239
private Integer userId;
@@ -45,5 +52,4 @@ public User(SignupRequest signup, String encodedPasswd) {
4552
@Column("role_role_id")
4653
private AggregateReference<Role, Integer> role;
4754

48-
4955
}

server/src/test/java/dev/findfirst/users/controller/UserControllerTest.java

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
import dev.findfirst.users.model.user.TokenPassword;
1717

1818
import com.fasterxml.jackson.databind.ObjectMapper;
19-
import org.junit.jupiter.api.Disabled;
2019
import org.junit.jupiter.api.Order;
2120
import org.junit.jupiter.api.Test;
2221
import org.mockito.InjectMocks;
@@ -30,9 +29,12 @@
3029
import org.springframework.http.HttpHeaders;
3130
import org.springframework.http.HttpMethod;
3231
import org.springframework.http.HttpStatus;
32+
import org.springframework.http.MediaType;
33+
import org.springframework.http.client.MultipartBodyBuilder;
3334
import org.springframework.mail.javamail.JavaMailSender;
3435
import org.springframework.mail.javamail.JavaMailSenderImpl;
3536
import org.springframework.test.context.TestPropertySource;
37+
import org.springframework.util.MultiValueMap;
3638
import org.testcontainers.containers.GenericContainer;
3739
import org.testcontainers.containers.PostgreSQLContainer;
3840
import org.testcontainers.junit.jupiter.Container;
@@ -96,7 +98,7 @@ public JavaMailSender javaMailSender() {
9698
void userSignup() {
9799
var headers = new HttpHeaders();
98100
var ent = new HttpEntity<>(
99-
new SignupRequest("Steve-Man", "steve@test.com", "$tev3s_sup3rH@rdPassword"), headers);
101+
new SignupRequest("Steve-Man2", "steve2@google.com", "$tev3s_sup3rH@rdPassword"), headers);
100102
var response = restTemplate.exchange(userUrl + "/signup", HttpMethod.POST, ent, String.class);
101103
assertEquals(HttpStatus.OK, response.getStatusCode());
102104

@@ -110,7 +112,6 @@ void userSignup() {
110112
* registration.
111113
*/
112114
@Test
113-
@Disabled
114115
void completeSignupAndRegistration() {
115116
var headers = new HttpHeaders();
116117
var ent = new HttpEntity<>(
@@ -191,4 +192,36 @@ void refreshToken() {
191192
assertEquals(HttpStatus.OK, resp.getStatusCode());
192193
}
193194

195+
@Test
196+
void testGetUserProfilePicture_NotFound() {
197+
198+
byte[] largeContent = new byte[2 * 1024 * 1024]; // 2 MB Max
199+
200+
// Use MultipartBodyBuilder to build the multipart request
201+
MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
202+
bodyBuilder.part("file", largeContent).filename("fakePic.png").contentType(MediaType.IMAGE_PNG);
203+
204+
bodyBuilder.part("file", largeContent).filename("image.jpg").contentType(MediaType.IMAGE_JPEG);
205+
206+
HttpHeaders headers = new HttpHeaders();
207+
headers.setBasicAuth("king", "test");
208+
HttpEntity<String> entity = new HttpEntity<>(headers);
209+
var signResp = restTemplate.postForEntity("/user/signin", entity, TokenRefreshResponse.class);
210+
211+
// Get the cookie from signin.
212+
var cookieOpt = Optional.ofNullable(signResp.getHeaders().get("Set-Cookie"));
213+
var cookie = cookieOpt.orElseThrow().get(0);
214+
215+
// Add the cookie to next request.
216+
headers = new HttpHeaders();
217+
headers.add("Cookie", cookie);
218+
219+
// Set up headers with basic authentication
220+
HttpEntity<MultiValueMap<String, HttpEntity<?>>> requestEntity =
221+
new HttpEntity<>(bodyBuilder.build(), headers);
222+
223+
var response = restTemplate.postForEntity("/user/profile-picture", requestEntity, String.class);
224+
225+
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());
226+
}
194227
}

server/src/test/java/dev/findfirst/users/service/UserServiceTest.java

Lines changed: 78 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,102 +1,132 @@
11
package dev.findfirst.users.service;
22

3-
import static org.junit.Assert.assertNull;
43
import static org.junit.jupiter.api.Assertions.assertEquals;
54
import static org.junit.jupiter.api.Assertions.assertNotNull;
5+
import static org.junit.jupiter.api.Assertions.assertNull;
6+
import static org.junit.jupiter.api.Assertions.assertTrue;
67
import static org.mockito.Mockito.eq;
78
import static org.mockito.Mockito.times;
89
import static org.mockito.Mockito.verify;
910
import static org.mockito.Mockito.when;
1011

12+
import java.io.File;
13+
import java.io.IOException;
1114
import java.util.Optional;
1215

16+
import dev.findfirst.security.jwt.service.RefreshTokenService;
17+
import dev.findfirst.security.userauth.context.UserContext;
1318
import dev.findfirst.users.controller.UserController;
1419
import dev.findfirst.users.model.user.User;
1520

21+
import org.junit.jupiter.api.BeforeEach;
1622
import org.junit.jupiter.api.Disabled;
1723
import org.junit.jupiter.api.Test;
24+
import org.junit.jupiter.api.extension.ExtendWith;
1825
import org.mockito.ArgumentCaptor;
26+
import org.mockito.Captor;
1927
import org.mockito.InjectMocks;
2028
import org.mockito.Mock;
21-
import org.mockito.MockitoAnnotations;
29+
import org.mockito.junit.jupiter.MockitoExtension;
2230
import org.springframework.http.HttpStatus;
2331
import org.springframework.http.ResponseEntity;
2432
import org.springframework.mock.web.MockMultipartFile;
33+
import org.springframework.test.util.ReflectionTestUtils;
2534

26-
@Disabled
35+
@ExtendWith(MockitoExtension.class)
2736
class UserServiceTest {
2837

2938
@Mock
3039
private UserManagementService userManagementService;
3140

41+
@Mock
42+
private UserContext userContext;
43+
44+
@Mock
45+
private RegistrationService registrationService;
46+
47+
@Mock
48+
private ForgotPasswordService forgotPasswordService;
49+
50+
@Mock
51+
private RefreshTokenService refreshTokenService;
52+
3253
@InjectMocks
3354
private UserController userController;
3455

35-
public UserServiceTest() {
36-
MockitoAnnotations.openMocks(this);
56+
@Captor
57+
private ArgumentCaptor<User> userArgumentCaptor;
58+
59+
private User mockUser;
60+
61+
@BeforeEach
62+
void setUp() {
63+
mockUser = new User();
64+
mockUser.setUserId(1);
65+
mockUser.setUsername("testUser");
66+
mockUser.setUserPhoto("uploads/profile-pictures/test.jpg");
67+
68+
// Mocking the allowedTypes field
69+
ReflectionTestUtils.setField(userController, "allowedTypes",
70+
new String[] {"image/jpeg", "image/png"});
3771
}
3872

3973
@Test
74+
@Disabled
4075
void testUploadProfilePicture_Success() throws Exception {
76+
4177
MockMultipartFile file =
4278
new MockMultipartFile("file", "test.jpg", "image/jpeg", "dummy content".getBytes());
43-
int userId = 1;
4479

45-
User user = new User();
46-
user.setUserId(userId);
47-
user.setUsername("testUser");
48-
when(userManagementService.getUserById(userId)).thenReturn(Optional.of(user));
80+
when(userManagementService.getUserById(mockUser.getUserId())).thenReturn(Optional.of(mockUser));
4981

5082
ResponseEntity<?> response = userController.uploadProfilePicture(file);
83+
System.out.println(response.getBody());
5184

5285
assertEquals(HttpStatus.OK, response.getStatusCode());
5386
assertEquals("File uploaded successfully.", response.getBody());
54-
verify(userManagementService, times(1)).changeUserPhoto(eq(user), file);
87+
88+
verify(userManagementService, times(1)).changeUserPhoto(eq(mockUser), eq(file));
5589
}
5690

5791
@Test
58-
void testRemoveUserPhoto_Success() {
59-
User user = new User();
60-
user.setUserId(1);
61-
user.setUsername("testUser");
62-
user.setUserPhoto("uploads/profile-pictures/test.jpg");
92+
@Disabled
93+
void testRemoveUserPhoto_Success() throws Exception {
6394

64-
when(userManagementService.getUserById(user.getUserId())).thenReturn(Optional.of(user));
95+
MockMultipartFile file =
96+
new MockMultipartFile("file", "test.jpg", "image/jpeg", "dummy content".getBytes());
6597

66-
userManagementService.removeUserPhoto(user);
98+
when(userManagementService.getUserById(mockUser.getUserId())).thenReturn(Optional.of(mockUser));
6799

68-
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
69-
verify(userManagementService, times(1)).saveUser(userCaptor.capture());
70-
assertNull(userCaptor.getValue().getUserPhoto());
100+
ResponseEntity<?> response = userController.uploadProfilePicture(file);
101+
102+
assertEquals(HttpStatus.OK, response.getStatusCode());
103+
assertEquals("File uploaded successfully.", response.getBody());
104+
105+
verify(userManagementService, times(1)).changeUserPhoto(eq(mockUser), eq(file));
106+
verify(userManagementService, times(1)).removeUserPhoto(eq(mockUser));
107+
108+
assertNull(mockUser.getUserPhoto());
71109
}
72110

73111
@Test
74112
void testUploadProfilePicture_FileSizeExceedsLimit() throws Exception {
113+
75114
byte[] largeContent = new byte[3 * 1024 * 1024]; // 3 MB
76-
MockMultipartFile file = new MockMultipartFile("file", "large.jpg", "image/jpeg", largeContent);
77-
int userId = 1;
78115

79-
User user = new User();
80-
user.setUserId(userId);
81-
user.setUsername("testUser");
82-
when(userManagementService.getUserById(userId)).thenReturn(Optional.of(user));
116+
MockMultipartFile file = new MockMultipartFile("file", "large.jpg", "image/jpeg", largeContent);
83117

84118
ResponseEntity<?> response = userController.uploadProfilePicture(file);
85119

86120
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
87121
assertEquals("File size exceeds the maximum limit of 2 MB.", response.getBody());
122+
88123
}
89124

90125
@Test
91126
void testUploadProfilePicture_InvalidFileType() throws Exception {
127+
92128
MockMultipartFile file =
93129
new MockMultipartFile("file", "test.txt", "text/plain", "dummy content".getBytes());
94-
int userId = 1;
95-
96-
User user = new User();
97-
user.setUserId(userId);
98-
user.setUsername("testUser");
99-
when(userManagementService.getUserById(userId)).thenReturn(Optional.of(user));
100130

101131
ResponseEntity<?> response = userController.uploadProfilePicture(file);
102132

@@ -106,30 +136,30 @@ void testUploadProfilePicture_InvalidFileType() throws Exception {
106136

107137
@Test
108138
void testGetUserProfilePicture_NotFound() {
109-
int userId = 1;
110139

111-
User user = new User();
112-
user.setUserId(userId);
113-
user.setUsername("testUser");
114-
user.setUserPhoto(null);
115-
when(userManagementService.getUserById(userId)).thenReturn(Optional.of(user));
140+
mockUser.setUserPhoto(null);
141+
142+
when(userManagementService.getUserById(mockUser.getUserId())).thenReturn(Optional.of(mockUser));
116143

117-
ResponseEntity<?> response = userController.getUserProfilePicture(userId);
144+
ResponseEntity<?> response = userController.getUserProfilePicture(mockUser.getUserId());
118145

119146
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
120147
}
121148

122149
@Test
123-
void testGetUserProfilePicture_Success() {
124-
int userId = 1;
150+
void testGetUserProfilePicture_Success() throws IOException {
151+
152+
// Create a temporary file to simulate an existing user photo
153+
File tempFile = File.createTempFile("test", ".jpg");
154+
String tempFilePath = tempFile.getAbsolutePath();
155+
156+
assertTrue(tempFile.exists());
157+
158+
mockUser.setUserPhoto(tempFilePath);
125159

126-
User user = new User();
127-
user.setUserId(userId);
128-
user.setUsername("testUser");
129-
user.setUserPhoto("uploads/profile-pictures/test.jpg");
130-
when(userManagementService.getUserById(userId)).thenReturn(Optional.of(user));
160+
when(userManagementService.getUserById(mockUser.getUserId())).thenReturn(Optional.of(mockUser));
131161

132-
ResponseEntity<?> response = userController.getUserProfilePicture(userId);
162+
ResponseEntity<?> response = userController.getUserProfilePicture(mockUser.getUserId());
133163

134164
assertEquals(HttpStatus.OK, response.getStatusCode());
135165
assertNotNull(response.getBody());

0 commit comments

Comments
 (0)