Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/main/java/com/SleepUp/SU/security/jwt/JwtService.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public JwtService(AppProperties appProperties) {
AppProperties.JwtProperties jwt = appProperties.getJwt();
this.secretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwt.getSecret()));
this.jwtExpirationMs = jwt.getExpirationMs();
this.jwtRefreshExpirationMs = jwt.getRefreshExpirationMs() != null ? jwt.getRefreshExpirationMs() : DEFAULT_REFRESH_EXPIRATION_MS;
this.jwtRefreshExpirationMs = jwt.getRefreshExpirationMs();
}

public String generateRefreshToken(UserDetails userDetails) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public User updateUserDataAdmin(UserRequestAdmin userRequestAdmin, User user){

User updatedUser = updateUser(userData, user);

Role role = userRequestAdmin.role() != null && !userRequestAdmin.role().getRoleName().isEmpty()
Role role = userRequestAdmin.role() != null
? userRequestAdmin.role() :
updatedUser.getRole();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
package com.SleepUp.SU.reservation.accommodationOwner;


import com.SleepUp.SU.reservation.dto.ReservationAuthRequest;
import com.SleepUp.SU.reservation.dto.ReservationResponseDetail;
import com.SleepUp.SU.reservation.dto.ReservationResponseSummary;
import com.SleepUp.SU.reservation.reservationGuest.ReservationGuestServiceImpl;
import com.SleepUp.SU.reservation.entity.Reservation;
import com.SleepUp.SU.reservation.repository.ReservationRepository;
import com.SleepUp.SU.reservation.status.BookingStatus;
import com.SleepUp.SU.user.entity.CustomUserDetails;
import com.SleepUp.SU.user.entity.User;
import com.SleepUp.SU.user.repository.UserRepository;
import com.SleepUp.SU.user.role.Role;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
Expand All @@ -18,91 +16,157 @@
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.anonymous;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class ReservationOwnerControllerTest {
@Transactional
class ReservationOwnerControllerTest {

private static final String RESERVATIONS_ACCOMMODATION_PATH = "/reservations/accommodation/{id}";
private static final String RESERVATION_STATUS_PATH = "/reservations/{id}/status";
private static final String RESERVATION_BY_ID_PATH = "/reservations/{id}";

@Autowired
private MockMvc mockMvc;

@MockitoBean
private ReservationOwnerService reservationOwnerServiceImpl;
@Autowired
private ReservationRepository reservationRepository;

@Autowired
private ObjectMapper objectMapper;

@Autowired
private UserRepository userRepository;

private CustomUserDetails principal;
private Long accommodationId = 123L;
private CustomUserDetails customUserDetailsGuest;
private CustomUserDetails customUserDetailsOwner;
private Reservation reservation;

@BeforeEach
void setUp() {
User testUser = userRepository.findByUsername("TestUser").orElseGet(() -> {
User u = new User();
u.setUsername("TestUser");
u.setEmail("testuser@example.com");
u.setName("Test User");
u.setRole(Role.USER);
return userRepository.save(u);
});
principal = new CustomUserDetails(testUser);
public void setUp() {
User savedUser = userRepository.findByUsername("User2")
.orElseThrow(() -> new RuntimeException("User2 not found"));

customUserDetailsGuest = new CustomUserDetails(savedUser);

reservation = reservationRepository.findByUser_Id(savedUser.getId()).getFirst();

User owner = reservation.getAccommodation().getManagedBy();

customUserDetailsOwner = new CustomUserDetails(owner);

}


// @Nested
// class UpdateReservationStatusTest {
// @Test
// void updateReservationStatus_authorized_shouldReturnOk() throws Exception {
// Long id = 42L;
// ReservationAuthRequest authRequest = new ReservationAuthRequest(BookingStatus.CANCELLED);
//
// ReservationResponseDetail detailDto = new ReservationResponseDetail(
// 42L,
// "alice",
// 2,
// "Beach House",
// LocalDate.of(2025, 9, 25),
// LocalDate.of(2025, 9, 30),
// BookingStatus.CANCELLED,
// true,
// LocalDateTime.of(2025, 9, 1, 10, 30)
// );
//
// when(reservationOwnerServiceImpl.updateStatus(id, authRequest))
// .thenReturn(detailDto);
//
// mockMvc.perform(patch(RESERVATION_STATUS_PATH, id)
// .with(user(principal))
// .contentType(MediaType.APPLICATION_JSON)
// .content(objectMapper.writeValueAsString(authRequest)))
// .andExpect(status().isOk())
// .andExpect(content().json(objectMapper.writeValueAsString(detailDto)));
// }
//
// }
@Nested
class GetAllReservationsForMyAccommodationTest {

@Test
void getAllReservations_authorized_shouldReturnList() throws Exception {
Long accommodationId = reservation.getAccommodation().getId();

mockMvc.perform(get("/accommodations/{id}/reservations", accommodationId)
.with(user(customUserDetailsOwner)))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$[0].id").value(1))
.andExpect(jsonPath("$[0].userName").value("Name4"))
.andExpect(jsonPath("$[0].guestNumber").isEmpty())
.andExpect(jsonPath("$[0].accommodationName").value("Hotel ABC"))
.andExpect(jsonPath("$[0].checkInDate").value("2025-09-21"))
.andExpect(jsonPath("$[0].checkOutDate").value("2025-09-24"))
.andExpect(jsonPath("$[0].bookingStatus").value("CONFIRMED"))
.andExpect(jsonPath("$[0].totalPrice").value(450.00));
}

@Test
void getAllReservations_whenNotOwner_shouldReturnForbidden() throws Exception {
Long accommodationId = reservation.getAccommodation().getId();

mockMvc.perform(get("/accommodations/{id}/reservations", accommodationId)
.with(user(customUserDetailsGuest)))
.andDo(print())
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.message").value(containsString("Access denied")));
}
}

}

@Nested
class UpdateReservationStatusTest {
@Test
void updateReservationStatus_authorized_shouldReturnOk() throws Exception {
Long id = reservation.getId();
ReservationAuthRequest authRequest = new ReservationAuthRequest(BookingStatus.CANCELLED);

ReservationResponseDetail detailDto = new ReservationResponseDetail(
id,
"alice",
2,
"Beach House",
LocalDate.of(2025, 9, 25),
LocalDate.of(2025, 9, 30),
BookingStatus.CANCELLED,
true,
LocalDateTime.of(2025, 9, 1, 10, 30), null
);

mockMvc.perform(patch(RESERVATION_STATUS_PATH, id)
.with(user(customUserDetailsOwner))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(authRequest)))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(2))
.andExpect(jsonPath("$.userName").value("Name2"))
.andExpect(jsonPath("$.guestNumber").isEmpty())
.andExpect(jsonPath("$.accommodationName").value("Hotel ABC"))
.andExpect(jsonPath("$.checkInDate").value("2025-10-02"))
.andExpect(jsonPath("$.checkOutDate").value("2025-10-06"))
.andExpect(jsonPath("$.bookingStatus").value("CANCELLED"))
.andExpect(jsonPath("$.emailSent").value(false))
.andExpect(jsonPath("$.totalPrice").value(600.00));

}

@Test
void updateReservationStatus_whenNotAccommodationOwner_shouldThrowForbidden() throws Exception {
Long id = reservation.getId();
ReservationAuthRequest authRequest = new ReservationAuthRequest(BookingStatus.CANCELLED);

ReservationResponseDetail detailDto = new ReservationResponseDetail(
id,
"alice",
2,
"Beach House",
LocalDate.of(2025, 9, 25),
LocalDate.of(2025, 9, 30),
BookingStatus.CANCELLED,
true,
LocalDateTime.of(2025, 9, 1, 10, 30), null
);

mockMvc.perform(patch(RESERVATION_STATUS_PATH, id)
.with(user(customUserDetailsGuest))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(authRequest)))
.andDo(print())
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.message").value(containsString("This reservation does not belong to any of your accommodations.")));

}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,36 @@ void setUp() {
.build();
}

@Nested
class GetUserByIdTest {
@Test
void getUserById_whenAdminRole_shouldReturnUserResponse() throws Exception {
mockMvc.perform(get(USER_PATH_ID, 1L)
.with(user(adminCustomUserDetails))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("User1"))
.andExpect(jsonPath("$.name").value("Name1"))
.andExpect(jsonPath("$.email").value("user1@example.com"))
.andExpect(jsonPath("$.role").value("USER"));
}

@Test
void getUserById_whenNotAdminRole_shouldReturnForbidden() throws Exception {
mockMvc.perform(get(USER_PATH_ID, 1L)
.with(user(userCustomUserDetails))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isForbidden());
}

@Test
void getUserById_whenNoAuthentication_shouldReturnUnauthorized() throws Exception {
mockMvc.perform(get(USER_PATH_ID, 1L)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized());
}
}

@Nested
class CreateUserTest {

Expand Down
Loading
Loading