Compare commits
31 Commits
fix-paymen
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 86e902bbfe | |||
| d9a8ffe4bd | |||
| c59998c113 | |||
| ff5dc5c090 | |||
| 4d7a191e8a | |||
| 7c7e82b0e6 | |||
| 7d070075d6 | |||
| b24d263f22 | |||
| f7023f9c4a | |||
| cad54d7b96 | |||
| b124a4b0e8 | |||
| 6e318a07c6 | |||
| b476f2e8c9 | |||
| a7c8f22658 | |||
| 5d7ab8d45d | |||
| 5addf38127 | |||
| f31885c795 | |||
| a5bc401e89 | |||
| edeb36cb8c | |||
| bacfd529aa | |||
| 8656ececf1 | |||
| 1d104493b5 | |||
| 3355914c70 | |||
| dfa747f548 | |||
| d51161221c | |||
| 0f14c72fdd | |||
| 2589c6010e | |||
| f9f2bff77e | |||
| 3d064e0496 | |||
| 3b9b0769d1 | |||
| 3e5baa34d1 |
@@ -1,70 +1,70 @@
|
||||
package _11.asktpk.artisanconnectbackend.controller;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.customExceptions.ClientAlreadyExistsException;
|
||||
import _11.asktpk.artisanconnectbackend.customExceptions.WrongLoginPasswordException;
|
||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import _11.asktpk.artisanconnectbackend.service.AuthService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
public class AuthController {
|
||||
|
||||
private final ClientService clientService;
|
||||
private final AuthService authService;
|
||||
private final JwtUtil jwtUtil;
|
||||
|
||||
public AuthController(ClientService clientService, JwtUtil jwtUtil) {
|
||||
this.clientService = clientService;
|
||||
public AuthController(AuthService authService, JwtUtil jwtUtil) {
|
||||
this.authService = authService;
|
||||
this.jwtUtil = jwtUtil;
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<AuthResponseDTO> login(@RequestBody AuthRequestDTO authRequestDTO) {
|
||||
if (clientService.checkClientCredentials(authRequestDTO)) {
|
||||
Client client = clientService.getClientByEmail(authRequestDTO.getEmail());
|
||||
Long userId = client.getId();
|
||||
String userRole = client.getRole().getRole();
|
||||
public ResponseEntity<?> login(@RequestBody AuthRequestDTO authRequestDTO) {
|
||||
if (authRequestDTO.getEmail() == null || authRequestDTO.getPassword() == null
|
||||
|| authRequestDTO.getEmail().isEmpty() || authRequestDTO.getPassword().isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Przekazano puste login lub hasło"));
|
||||
}
|
||||
|
||||
String token = jwtUtil.generateToken(client.getEmail(), userRole, userId);
|
||||
authRequestDTO.setEmail(authRequestDTO.getEmail().toLowerCase());
|
||||
|
||||
try {
|
||||
AuthResponseDTO responseDTO = authService.login(authRequestDTO.getEmail(), authRequestDTO.getPassword());
|
||||
|
||||
log.info("User logged in with {}", client.getEmail());
|
||||
return ResponseEntity.status(HttpStatus.OK)
|
||||
.body(new AuthResponseDTO(userId, userRole, token));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
|
||||
.body(responseDTO);
|
||||
|
||||
} catch (WrongLoginPasswordException e) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new RequestResponseDTO(e.getMessage()));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO(e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public ResponseEntity<AuthResponseDTO> register(@RequestBody ClientRegistrationDTO clientDTO) {
|
||||
if (clientService.getClientByEmail(clientDTO.getEmail()) != null) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT).build();
|
||||
public ResponseEntity<?> register(@RequestBody ClientRegistrationDTO clientRegistrationDTO) {
|
||||
if (clientRegistrationDTO.getEmail() == null || clientRegistrationDTO.getPassword() == null
|
||||
|| clientRegistrationDTO.getEmail().isEmpty() || clientRegistrationDTO.getPassword().isEmpty()) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Przekazano puste login lub hasło"));
|
||||
}
|
||||
|
||||
ClientDTO savedClient = clientService.registerClient(clientDTO);
|
||||
clientRegistrationDTO.setEmail(clientRegistrationDTO.getEmail().toLowerCase());
|
||||
|
||||
String token = jwtUtil.generateToken(
|
||||
savedClient.getEmail(),
|
||||
savedClient.getRole(),
|
||||
savedClient.getId()
|
||||
);
|
||||
try {
|
||||
AuthResponseDTO registrationData = authService.register(clientRegistrationDTO.getEmail(), clientRegistrationDTO.getPassword(), clientRegistrationDTO.getFirstName(), clientRegistrationDTO.getLastName());
|
||||
|
||||
log.info("New user registered with {}", savedClient.getEmail());
|
||||
|
||||
return ResponseEntity.status(HttpStatus.CREATED)
|
||||
.body(new AuthResponseDTO(
|
||||
savedClient.getId(),
|
||||
savedClient.getRole(),
|
||||
token
|
||||
));
|
||||
return ResponseEntity.status(HttpStatus.CREATED)
|
||||
.body(registrationData);
|
||||
} catch (ClientAlreadyExistsException clientAlreadyExistsException) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(new RequestResponseDTO(clientAlreadyExistsException.getMessage()));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO(e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
@@ -73,7 +73,7 @@ public class AuthController {
|
||||
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
jwtUtil.blacklistToken(token);
|
||||
authService.logout(token);
|
||||
return ResponseEntity.ok(new RequestResponseDTO("Successfully logged out"));
|
||||
}
|
||||
|
||||
@@ -82,45 +82,28 @@ public class AuthController {
|
||||
|
||||
@PostMapping("/google")
|
||||
public ResponseEntity<?> authenticateWithGoogle(@RequestBody GoogleAuthRequestDTO dto) {
|
||||
if(dto.getGoogleToken() == null){
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Invalid or empty token"));
|
||||
}
|
||||
|
||||
try {
|
||||
String accessToken = dto.getGoogleToken();
|
||||
String googleUserInfoUrl = "https://www.googleapis.com/oauth2/v3/userinfo";
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setBearerAuth(accessToken);
|
||||
HttpEntity<String> entity = new HttpEntity<>(headers);
|
||||
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
ResponseEntity<Map> response = restTemplate.exchange(
|
||||
googleUserInfoUrl, HttpMethod.GET, entity, Map.class);
|
||||
|
||||
Map<String, Object> userInfo = response.getBody();
|
||||
|
||||
// String googleId = (String) userInfo.get("sub"); Potencjalnie możemy używać googlowskiego ID, ale to ma konflikt z naszym generowanym
|
||||
assert userInfo != null;
|
||||
String email = (String) userInfo.get("email");
|
||||
String name = (String) userInfo.get("name");
|
||||
|
||||
Client client = clientService.getClientByEmail(email);
|
||||
if (client == null) {
|
||||
client = new Client();
|
||||
client.setEmail(email);
|
||||
client.setFirstName(name);
|
||||
client.setRole(clientService.getUserRole()); // to pobiera po prostu role "USER" z tabeli w bazie
|
||||
clientService.saveClientToDB(client);
|
||||
}
|
||||
|
||||
String jwt = jwtUtil.generateToken(client.getEmail(), client.getRole().getRole(), client.getId());
|
||||
|
||||
log.info("User authenticated with google: {}", email);
|
||||
return ResponseEntity.ok(new AuthResponseDTO(client.getId(), client.getRole().getRole(), jwt));
|
||||
AuthResponseDTO response = authService.googleLogin(dto.getGoogleToken());
|
||||
return ResponseEntity.status(HttpStatus.OK).body(response);
|
||||
} catch (HttpClientErrorException httpClientErrorException) {
|
||||
log.error("Token is invalid or expired");
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new RequestResponseDTO("Invalid access token"));
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Google access token is invalid or expired"));
|
||||
} catch (Exception e) {
|
||||
log.error("Error while checking Google access token", e);
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.body(new RequestResponseDTO("Authentication Error (Google): " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public ResponseEntity<?> getMe(HttpServletRequest request) {
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
return ResponseEntity.status(HttpStatus.OK).body(new AuthResponseDTO(jwtUtil.extractUserId(token), jwtUtil.extractRole(token), token));
|
||||
}
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new RequestResponseDTO("Invalid or empty token"));
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -29,7 +30,7 @@ public class ImageController {
|
||||
private String uploadDir;
|
||||
|
||||
@PostMapping("/upload/{id}")
|
||||
public ResponseEntity<RequestResponseDTO> uploadImage(@RequestParam("file") MultipartFile file, @PathVariable("id") Long noticeId) {
|
||||
public ResponseEntity<RequestResponseDTO> uploadImage(@RequestParam("file") MultipartFile file, @PathVariable("id") Long noticeId, @Param("isMainImage") Boolean isMainImage) {
|
||||
try {
|
||||
if(file.isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(new RequestResponseDTO("File is empty"));
|
||||
@@ -44,10 +45,11 @@ public class ImageController {
|
||||
}
|
||||
|
||||
String newImageName = imageService.saveImageToStorage(uploadDir, file);
|
||||
imageService.addImageNameToDB(newImageName, noticeId);
|
||||
imageService.addImageNameToDB(newImageName, noticeId, isMainImage);
|
||||
|
||||
return ResponseEntity.ok(new RequestResponseDTO("Image uploaded successfully with new name: " + newImageName));
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).body(new RequestResponseDTO(e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ public class OrderController {
|
||||
}
|
||||
|
||||
@PostMapping("/token")
|
||||
public ResponseEntity<?> fetchToken(HttpServletRequest request,@RequestParam Long orderId) {
|
||||
public ResponseEntity<?> fetchToken(@RequestParam Long orderId) {
|
||||
Order order = orderService.getOrderById(orderId);
|
||||
Client client = order.getClient();
|
||||
OAuthPaymentResponseDTO authPaymentDTO = paymentService.getOAuthToken();
|
||||
@@ -51,8 +51,15 @@ public class OrderController {
|
||||
|
||||
String paymentDescription = order.getOrderType() == Enums.OrderType.ACTIVATION ? "Aktywacja ogłoszenia" : "Podbicie ogłoszenia";
|
||||
paymentDescription += order.getNotice().getTitle();
|
||||
|
||||
TransactionPaymentRequestDTO.Callbacks callbacks = new TransactionPaymentRequestDTO.Callbacks();
|
||||
TransactionPaymentRequestDTO.PayerUrls payerUrls = new TransactionPaymentRequestDTO.PayerUrls();
|
||||
payerUrls.setSuccess("com.hamx.artisanconnect://dashboard/userNotices");
|
||||
payerUrls.setError("com.hamx.artisanconnect://dashboard/userNotices");
|
||||
callbacks.setPayerUrls(payerUrls);
|
||||
|
||||
TransactionPaymentRequestDTO paymentRequest = new TransactionPaymentRequestDTO(
|
||||
order.getAmount(), paymentDescription, payer);
|
||||
order.getAmount(), paymentDescription, payer, callbacks);
|
||||
|
||||
String response = paymentService.createTransaction(order, authPaymentDTO.getAccess_token(), paymentRequest);
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package _11.asktpk.artisanconnectbackend.customExceptions;
|
||||
|
||||
public class ClientAlreadyExistsException extends Exception {
|
||||
public ClientAlreadyExistsException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package _11.asktpk.artisanconnectbackend.customExceptions;
|
||||
|
||||
public class WrongLoginPasswordException extends Exception {
|
||||
public WrongLoginPasswordException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,16 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
|
||||
@Getter @Setter
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class ClientDTO {
|
||||
private Long id;
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
public class ImageRequestDTO {
|
||||
public Resource image;
|
||||
public Long noticeId;
|
||||
public boolean isMainImage;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package _11.asktpk.artisanconnectbackend.dto;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import java.util.List;
|
||||
|
||||
@Getter @Setter
|
||||
public class NoticeRequestDTO {
|
||||
@@ -18,6 +19,8 @@ public class NoticeRequestDTO {
|
||||
|
||||
private Enums.Status status;
|
||||
|
||||
private List<AttributeDto> attributes;
|
||||
|
||||
public NoticeRequestDTO() {
|
||||
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
package _11.asktpk.artisanconnectbackend.dto;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Getter @Setter
|
||||
public class OrderWithPaymentsDTO {
|
||||
private Long orderId;
|
||||
private String orderType;
|
||||
@@ -10,53 +14,4 @@ public class OrderWithPaymentsDTO {
|
||||
private Double amount;
|
||||
private LocalDateTime createdAt;
|
||||
private List<PaymentDTO> payments;
|
||||
|
||||
// Gettery i settery
|
||||
public Long getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(Long orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public String getOrderType() {
|
||||
return orderType;
|
||||
}
|
||||
|
||||
public void setOrderType(String orderType) {
|
||||
this.orderType = orderType;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Double getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(Double amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(LocalDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public List<PaymentDTO> getPayments() {
|
||||
return payments;
|
||||
}
|
||||
|
||||
public void setPayments(List<PaymentDTO> payments) {
|
||||
this.payments = payments;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ public class TransactionPaymentRequestDTO {
|
||||
private double amount;
|
||||
private String description;
|
||||
private Payer payer;
|
||||
private Callbacks callbacks;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -20,4 +21,21 @@ public class TransactionPaymentRequestDTO {
|
||||
private String email;
|
||||
private String name;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class Callbacks {
|
||||
private PayerUrls payerUrls;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class PayerUrls {
|
||||
private String success;
|
||||
private String error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package _11.asktpk.artisanconnectbackend.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
@@ -11,7 +12,15 @@ import java.util.List;
|
||||
@Entity
|
||||
@Table(name = "clients")
|
||||
@Getter @Setter
|
||||
@NoArgsConstructor
|
||||
public class Client {
|
||||
public Client(String email, String password, String firstName, String lastName) {
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.AttributeValues;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Attributes;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface AttributeValuesRepository extends JpaRepository<AttributeValues, Long> {
|
||||
|
||||
Optional<AttributeValues> findByAttributeAndValue(Attributes attribute, String value);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.AttributesNotice;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface AttributesNoticeRepository extends JpaRepository<AttributesNotice, Long> {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package _11.asktpk.artisanconnectbackend.repository;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.entities.Attributes;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface AttributesRepository extends JpaRepository<Attributes, Long> {
|
||||
Optional<Attributes> findByName(String name);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package _11.asktpk.artisanconnectbackend.service;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.customExceptions.ClientAlreadyExistsException;
|
||||
import _11.asktpk.artisanconnectbackend.customExceptions.WrongLoginPasswordException;
|
||||
import _11.asktpk.artisanconnectbackend.dto.AuthResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class AuthService {
|
||||
|
||||
private final ClientService clientService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtUtil jwtUtil;
|
||||
|
||||
public AuthService(ClientService clientService, JwtUtil jwtUtil, PasswordEncoder passwordEncoder) {
|
||||
this.clientService = clientService;
|
||||
this.jwtUtil = jwtUtil;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
public AuthResponseDTO login(String email, String password) throws Exception {
|
||||
Client client = clientService.getClientByEmail(email);
|
||||
if (client == null) {
|
||||
throw new Exception("Klient o podanym adresie nie istnieje!");
|
||||
}
|
||||
|
||||
if (passwordEncoder.matches(password, client.getPassword())) {
|
||||
String token = jwtUtil.generateToken(client.getEmail(), client.getRole().getRole(), client.getId());
|
||||
log.info("User logged in with {}", client.getEmail());
|
||||
return new AuthResponseDTO(client.getId(), client.getRole().getRole(), token);
|
||||
}
|
||||
throw new WrongLoginPasswordException("Login lub hasło jest niepoprawny!");
|
||||
}
|
||||
|
||||
public AuthResponseDTO register(String email, String password, String firstName, String lastName) throws Exception {
|
||||
if (clientService.getClientByEmail(email) != null) {
|
||||
throw new ClientAlreadyExistsException("Klient o podanym adresie email już istnieje!");
|
||||
}
|
||||
|
||||
Client newClient = new Client();
|
||||
newClient.setEmail(email);
|
||||
newClient.setPassword(passwordEncoder.encode(password));
|
||||
newClient.setFirstName(firstName);
|
||||
newClient.setLastName(lastName);
|
||||
|
||||
ClientDTO savedClient = clientService.registerClient(newClient);
|
||||
if (savedClient != null) {
|
||||
log.info("New user registered with {}", savedClient.getEmail());
|
||||
String token = jwtUtil.generateToken(
|
||||
savedClient.getEmail(),
|
||||
savedClient.getRole(),
|
||||
savedClient.getId()
|
||||
);
|
||||
|
||||
return new AuthResponseDTO(savedClient.getId(), savedClient.getRole(), token);
|
||||
} else {
|
||||
throw new Exception("Rejestracja nie powiodła się!");
|
||||
}
|
||||
}
|
||||
|
||||
public void logout(String token) {
|
||||
jwtUtil.blacklistToken(token);
|
||||
}
|
||||
|
||||
public AuthResponseDTO googleLogin(String googleAccessToken) throws Exception {
|
||||
String googleUserInfoUrl = "https://www.googleapis.com/oauth2/v3/userinfo";
|
||||
|
||||
ResponseEntity<Map> response;
|
||||
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setBearerAuth(googleAccessToken);
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
response = restTemplate.exchange(
|
||||
googleUserInfoUrl, HttpMethod.GET, new HttpEntity<>(headers), Map.class);
|
||||
|
||||
|
||||
Map<String, Object> userInfo = response.getBody();
|
||||
|
||||
// String googleId = (String) userInfo.get("sub"); Potencjalnie możemy używać googlowskiego ID, ale to ma konflikt z naszym generowanym
|
||||
if (userInfo == null) {
|
||||
throw new Exception("Pobrany użytkownik jest pusty! Może to być spowodowane niepoprawnym tokenem lub brakiem dostępu do Google API.");
|
||||
}
|
||||
String email = (String) userInfo.get("email");
|
||||
String name = (String) userInfo.get("name");
|
||||
|
||||
Client client = clientService.getClientByEmail(email);
|
||||
if (client == null) {
|
||||
client = new Client();
|
||||
client.setEmail(email);
|
||||
client.setFirstName(name);
|
||||
client.setRole(clientService.getUserRole()); // to pobiera po prostu role "USER" z tabeli w bazie
|
||||
clientService.saveClientToDB(client);
|
||||
}
|
||||
|
||||
String jwt = jwtUtil.generateToken(client.getEmail(), client.getRole().getRole(), client.getId());
|
||||
log.info("User authenticated with google: {}", client.getEmail());
|
||||
return new AuthResponseDTO(
|
||||
client.getId(),
|
||||
client.getRole().getRole(),
|
||||
jwt
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package _11.asktpk.artisanconnectbackend.service;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.AuthRequestDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientRegistrationDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
@@ -8,7 +7,6 @@ import _11.asktpk.artisanconnectbackend.entities.Role;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.RolesRepository;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
@@ -16,16 +14,14 @@ import java.util.List;
|
||||
@Service
|
||||
public class ClientService {
|
||||
private final ClientRepository clientRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final RolesRepository rolesRepository;
|
||||
|
||||
public ClientService(ClientRepository clientRepository, PasswordEncoder passwordEncoder, RolesRepository rolesRepository) {
|
||||
public ClientService(ClientRepository clientRepository, RolesRepository rolesRepository) {
|
||||
this.clientRepository = clientRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.rolesRepository = rolesRepository;
|
||||
}
|
||||
|
||||
private ClientDTO toDto(Client client) {
|
||||
public ClientDTO toDto(Client client) {
|
||||
if(client == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -42,7 +38,7 @@ public class ClientService {
|
||||
return dto;
|
||||
}
|
||||
|
||||
private Client fromDto(ClientDTO dto) {
|
||||
public Client fromDto(ClientDTO dto) {
|
||||
Client client = new Client();
|
||||
Role rola;
|
||||
|
||||
@@ -86,6 +82,14 @@ public class ClientService {
|
||||
return toDto(clientRepository.findById(id).orElse(null));
|
||||
}
|
||||
|
||||
public Client getClientByEmail(String email) {
|
||||
return clientRepository.findByEmail(email);
|
||||
}
|
||||
|
||||
public Role getUserRole() {
|
||||
return rolesRepository.findRoleByRole("USER");
|
||||
}
|
||||
|
||||
public boolean clientExists(Long id) {
|
||||
return clientRepository.existsById(id);
|
||||
}
|
||||
@@ -117,29 +121,8 @@ public class ClientService {
|
||||
clientRepository.deleteById(id);
|
||||
}
|
||||
|
||||
// И замените метод checkClientCredentials на:
|
||||
public boolean checkClientCredentials(AuthRequestDTO dto) {
|
||||
Client cl = clientRepository.findByEmail(dto.getEmail());
|
||||
if (cl == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return passwordEncoder.matches(dto.getPassword(), cl.getPassword());
|
||||
}
|
||||
|
||||
// При создании нового пользователя не забудьте шифровать пароль:
|
||||
public ClientDTO registerClient(ClientRegistrationDTO clientDTO) {
|
||||
Client client = fromDto(clientDTO);
|
||||
client.setRole(rolesRepository.findRoleById(1L));
|
||||
client.setPassword(passwordEncoder.encode(client.getPassword()));
|
||||
public ClientDTO registerClient(Client client) {
|
||||
client.setRole(getUserRole()); // ID 1 - USER role
|
||||
return toDto(clientRepository.save(client));
|
||||
}
|
||||
|
||||
public Client getClientByEmail(String email) {
|
||||
return clientRepository.findByEmail(email);
|
||||
}
|
||||
|
||||
public Role getUserRole() {
|
||||
return rolesRepository.findRoleByRole("USER");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,10 +15,10 @@ public class EmailService {
|
||||
|
||||
public void sendEmail(EmailDTO email) {
|
||||
SimpleMailMessage message = new SimpleMailMessage();
|
||||
message.setFrom("noreply@zikor.pl");
|
||||
message.setTo(email.getTo());
|
||||
message.setSubject(email.getSubject());
|
||||
message.setText(email.getBody());
|
||||
message.setFrom("patryk.kania001@gmail.com");
|
||||
mailSender.send(message);
|
||||
}
|
||||
}
|
||||
@@ -40,10 +40,11 @@ public class ImageService {
|
||||
return uniqueFileName;
|
||||
}
|
||||
|
||||
public void addImageNameToDB(String filename, Long noticeId) {
|
||||
public void addImageNameToDB(String filename, Long noticeId, boolean isMainImage) {
|
||||
Image image = new Image();
|
||||
image.setImageName(filename);
|
||||
image.setNoticeId(noticeId);
|
||||
image.setMainImage(isMainImage);
|
||||
imageRepository.save(image);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,11 +2,8 @@ package _11.asktpk.artisanconnectbackend.service;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.AttributeDto;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeRequestDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.AttributesNotice;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.NoticeRepository;
|
||||
import _11.asktpk.artisanconnectbackend.entities.*;
|
||||
import _11.asktpk.artisanconnectbackend.repository.*;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeResponseDTO;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
@@ -28,11 +25,22 @@ public class NoticeService {
|
||||
private final NoticeRepository noticeRepository;
|
||||
private final ClientRepository clientRepository;
|
||||
private final ImageService imageService;
|
||||
private final AttributesRepository attributesRepository;
|
||||
private final AttributeValuesRepository attributeValuesRepository;
|
||||
private final AttributesNoticeRepository attributesNoticeRepository;
|
||||
|
||||
public NoticeService(NoticeRepository noticeRepository, ClientRepository clientRepository, ImageService imageService) {
|
||||
public NoticeService(NoticeRepository noticeRepository,
|
||||
ClientRepository clientRepository,
|
||||
ImageService imageService,
|
||||
AttributesRepository attributesRepository,
|
||||
AttributeValuesRepository attributeValuesRepository,
|
||||
AttributesNoticeRepository attributesNoticeRepository) {
|
||||
this.noticeRepository = noticeRepository;
|
||||
this.clientRepository = clientRepository;
|
||||
this.imageService = imageService;
|
||||
this.attributesRepository = attributesRepository;
|
||||
this.attributeValuesRepository = attributeValuesRepository;
|
||||
this.attributesNoticeRepository = attributesNoticeRepository;
|
||||
}
|
||||
|
||||
public Notice fromDTO(NoticeRequestDTO dto) {
|
||||
@@ -97,7 +105,38 @@ public class NoticeService {
|
||||
public Long addNotice(NoticeRequestDTO dto) {
|
||||
Notice notice = fromDTO(dto);
|
||||
notice.setPublishDate(LocalDateTime.now());
|
||||
return noticeRepository.save(notice).getIdNotice();
|
||||
Notice savedNotice = noticeRepository.save(notice);
|
||||
|
||||
if (dto.getAttributes() != null && !dto.getAttributes().isEmpty()) {
|
||||
saveAttributes(savedNotice.getIdNotice(), dto.getAttributes());
|
||||
}
|
||||
|
||||
return savedNotice.getIdNotice();
|
||||
}
|
||||
|
||||
private void saveAttributes(Long noticeId, List<AttributeDto> attributeDtos) {
|
||||
for (AttributeDto attributeDto : attributeDtos) {
|
||||
Attributes attribute = attributesRepository.findByName(attributeDto.getName())
|
||||
.orElseGet(() -> {
|
||||
Attributes newAttribute = new Attributes();
|
||||
newAttribute.setName(attributeDto.getName());
|
||||
return attributesRepository.save(newAttribute);
|
||||
});
|
||||
|
||||
AttributeValues attributeValue = attributeValuesRepository
|
||||
.findByAttributeAndValue(attribute, attributeDto.getValue())
|
||||
.orElseGet(() -> {
|
||||
AttributeValues newValue = new AttributeValues();
|
||||
newValue.setAttribute(attribute);
|
||||
newValue.setValue(attributeDto.getValue());
|
||||
return attributeValuesRepository.save(newValue);
|
||||
});
|
||||
|
||||
AttributesNotice attributesNotice = new AttributesNotice();
|
||||
attributesNotice.setNotice_id(noticeId);
|
||||
attributesNotice.setAttributeValue(attributeValue);
|
||||
attributesNoticeRepository.save(attributesNotice);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean noticeExists(Long id) {
|
||||
|
||||
@@ -1,39 +1,33 @@
|
||||
spring.application.name=ArtisanConnectBackend
|
||||
|
||||
## PostgreSQL
|
||||
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
|
||||
spring.datasource.url=${DB_URL:jdbc:postgresql://db:5432/postgres}
|
||||
spring.datasource.username=${DB_USER:postgres}
|
||||
spring.datasource.password=${DB_PASS:postgres}
|
||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
spring.datasource.username=postgres
|
||||
spring.datasource.password=postgres
|
||||
|
||||
#initial data for db injection
|
||||
spring.sql.init.data-locations=classpath:sql/data.sql
|
||||
spring.sql.init.mode=always
|
||||
spring.jpa.defer-datasource-initialization=true
|
||||
|
||||
# create and drop table, good for testing, production set to none or comment it
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
|
||||
file.upload-dir=/Users/andsol/Desktop/uploads
|
||||
spring.servlet.multipart.max-file-size=10MB
|
||||
spring.servlet.multipart.max-request-size=10MB
|
||||
file.upload-dir=${IMAGES_UPLOAD_DIR:/app/images}
|
||||
spring.servlet.multipart.max-file-size=${MAX_FILE_SIZE:10MB}
|
||||
spring.servlet.multipart.max-request-size=${MAX_REQUEST_SIZE:10MB}
|
||||
|
||||
spring.mail.host=smtp.gmail.com
|
||||
spring.mail.port=587
|
||||
spring.mail.username=patryk.kania001@gmail.com
|
||||
spring.mail.password=pmyd ylwg mbsn hcpp
|
||||
spring.mail.properties.mail.smtp.auth=true
|
||||
spring.mail.properties.mail.smtp.starttls.enable=true
|
||||
spring.mail.host=${MAIL_HOST}
|
||||
spring.mail.port=${MAIL_PORT}
|
||||
spring.mail.username=${MAIL_USER}
|
||||
spring.mail.password=${MAIL_PASSWORD}
|
||||
|
||||
tpay.clientId = 01JQKC048X62ST9V59HNRSXD92-01JQKC2CQHPYXQFSFX8BKC24BX
|
||||
tpay.clientSecret = 44898642be53381cdcc47f3e44bf5a15e592f5d270fc3a6cf6fb81a8b8ebffb9
|
||||
tpay.authUrl = https://openapi.sandbox.tpay.com/oauth/auth
|
||||
tpay.transactionUrl = https://openapi.sandbox.tpay.com/transactions
|
||||
tpay.securityCode = )IY7E)YSM!A)Q6O-GN#U7U_33s9qObk8
|
||||
tpay.clientId=${TPAY_CLIENT_ID}
|
||||
tpay.clientSecret=${TPAY_SECRET}
|
||||
tpay.authUrl=${TPAY_AUTH_URL}
|
||||
tpay.transactionUrl=${TPAY_TRANSACTION_URL}
|
||||
tpay.securityCode = ${TPAY_SECURITY_CODE}
|
||||
|
||||
#jwt settings
|
||||
jwt.secret=DIXLsOs3FKmCAQwISd0SKsHMXJrPl3IKIRkVlkOvYW7kEcdUTbxh8zFe1B3eZWkY
|
||||
jwt.expiration=300000
|
||||
jwt.secret=${JWT_SECRET}
|
||||
jwt.expiration=1200000
|
||||
|
||||
logging.file.name=logs/payment-notifications.log
|
||||
logging.level.TpayLogger=INFO
|
||||
@@ -5,11 +5,11 @@ VALUES
|
||||
|
||||
INSERT INTO clients (email, first_name, last_name, password, role_id)
|
||||
VALUES
|
||||
('dignissim.tempor.arcu@aol.ca', 'Diana', 'Harrison', 'password', 1),
|
||||
('john.doe@example.com', 'John', 'Doe', 'password123', 2),
|
||||
('jane.smith@example.com', 'Jane', 'Smith', 'securepass', 1),
|
||||
('michael.brown@example.com', 'Michael', 'Brown', 'mypassword', 1),
|
||||
('emily.jones@example.com', 'Emily', 'Jones', 'passw0rd', 1);
|
||||
('dignissim.tempor.arcu@aol.ca', 'Diana', 'Harrison', '', 1),
|
||||
('john.doe@example.com', 'John', 'Doe', '', 2),
|
||||
('jane.smith@example.com', 'Jane', 'Smith', '', 1),
|
||||
('michael.brown@example.com', 'Michael', 'Brown', '', 1),
|
||||
('emily.jones@example.com', 'Emily', 'Jones', '', 1);
|
||||
|
||||
|
||||
INSERT INTO notice (title, description, client_id, price, category, status, publish_date) VALUES
|
||||
|
||||
@@ -1,33 +1,441 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.NoticeRepository;
|
||||
import _11.asktpk.artisanconnectbackend.service.*;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.http.*;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Image;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ImageRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@SpringBootTest
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.Comparator;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Testy dla funkcjonalności klienta w backendzie.
|
||||
*/
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
class ArtisanConnectBackendApplicationTests {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(ArtisanConnectBackendApplicationTests.class);
|
||||
|
||||
// @Test
|
||||
// void testPostgresDatabase() {
|
||||
// postgresDatabase.add(new Notice("Test Notice", "Username", "Test Description"));
|
||||
// Boolean isRecordAvailable = postgresDatabase.get().size() > 0;
|
||||
// if(isRecordAvailable) {
|
||||
// logger.info("The record is available in the database");
|
||||
// } else {
|
||||
// logger.error("The record is not available in the database");
|
||||
// }
|
||||
// assert isRecordAvailable;
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// void getAllNotices() throws IOException {
|
||||
// OkHttpClient client = new OkHttpClient().newBuilder()
|
||||
// .build();
|
||||
// MediaType mediaType = MediaType.parse("text/plain");
|
||||
// Request request = new Request.Builder()
|
||||
// .url("http://localhost:8080/api/v1/notices/all")
|
||||
// .build();
|
||||
// Response response = client.newCall(request).execute();
|
||||
// }
|
||||
}
|
||||
@Nested
|
||||
@DisplayName("Testy integracyjne ImageService")
|
||||
class ImageServiceTest {
|
||||
|
||||
private final Logger logger = LogManager.getLogger(ImageServiceTest.class);
|
||||
private final ImageService imageService;
|
||||
private final ImageRepository imageRepository;
|
||||
private final Path testDirectory;
|
||||
|
||||
ImageServiceTest() throws Exception {
|
||||
logger.info("Inicjalizacja testów ImageService");
|
||||
this.imageRepository = mock(ImageRepository.class);
|
||||
this.testDirectory = Files.createTempDirectory("test-images");
|
||||
logger.info("Utworzono katalog testowy: {}", testDirectory);
|
||||
|
||||
Constructor<ImageService> constructor = ImageService.class.getDeclaredConstructor(ImageRepository.class);
|
||||
constructor.setAccessible(true);
|
||||
this.imageService = constructor.newInstance(imageRepository);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() throws IOException {
|
||||
logger.info("Sprzątanie po teście - usuwanie katalogu testowego: {}", testDirectory);
|
||||
try (var paths = Files.walk(testDirectory)) {
|
||||
paths.sorted(Comparator.reverseOrder())
|
||||
.forEach(path -> {
|
||||
try {
|
||||
Files.delete(path);
|
||||
logger.debug("Usunięto plik: {}", path);
|
||||
} catch (IOException e) {
|
||||
logger.warn("Nie można usunąć pliku: {}", path, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie zapisać obraz w magazynie plików")
|
||||
void shouldSaveImageToStorage() throws IOException {
|
||||
logger.info("Test zapisu obrazu - rozpoczęcie");
|
||||
|
||||
final String testFileName = "test.jpg";
|
||||
final Path testFilePath = testDirectory.resolve(testFileName);
|
||||
Files.createFile(testFilePath);
|
||||
Files.write(testFilePath, "test content".getBytes());
|
||||
logger.debug("Utworzono testowy plik: {}", testFilePath);
|
||||
|
||||
final MultipartFile file = mock(MultipartFile.class);
|
||||
when(file.getOriginalFilename()).thenReturn(testFileName);
|
||||
when(file.getInputStream()).thenReturn(Files.newInputStream(testFilePath));
|
||||
|
||||
final String savedFileName = imageService.saveImageToStorage(testDirectory.toString(), file);
|
||||
logger.info("Zapisano plik pod nazwą: {}", savedFileName);
|
||||
|
||||
assertTrue(savedFileName.endsWith(".jpg"));
|
||||
assertTrue(Files.exists(testDirectory.resolve(savedFileName)));
|
||||
logger.info("Test zapisu obrazu - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie pobrać obraz")
|
||||
void shouldGetImage() throws IOException {
|
||||
logger.info("Test pobierania obrazu - rozpoczęcie");
|
||||
|
||||
final String testFileName = "test.jpg";
|
||||
Files.createFile(testDirectory.resolve(testFileName));
|
||||
logger.debug("Utworzono testowy plik: {}", testFileName);
|
||||
|
||||
final Resource resource = imageService.getImage(testDirectory.toString(), testFileName);
|
||||
logger.info("Pobrano zasób: {}", resource.getFilename());
|
||||
|
||||
assertNotNull(resource);
|
||||
assertTrue(resource.exists());
|
||||
assertInstanceOf(UrlResource.class, resource);
|
||||
logger.info("Test pobierania obrazu - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zgłosić błąd, gdy obraz nie zostanie znaleziony")
|
||||
void shouldThrowExceptionWhenImageNotFound() {
|
||||
logger.info("Test obsługi błędu - rozpoczęcie");
|
||||
|
||||
final Exception exception = assertThrows(IOException.class, () ->
|
||||
imageService.getImage(testDirectory.toString(), "missing.jpg")
|
||||
);
|
||||
logger.info("Złapano wyjątek: {}", exception.getMessage());
|
||||
|
||||
assertThat(exception).hasMessageContaining("File not found");
|
||||
logger.info("Test obsługi błędu - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie usuwać obraz z magazynu plików")
|
||||
void shouldDeleteImage() throws IOException {
|
||||
logger.info("Test usuwania obrazu - rozpoczęcie");
|
||||
|
||||
final String testFileName = "test-delete.jpg";
|
||||
final Path testFilePath = testDirectory.resolve(testFileName);
|
||||
Files.createFile(testFilePath);
|
||||
logger.debug("Utworzono testowy plik: {}", testFilePath);
|
||||
|
||||
when(imageRepository.existsImageByImageNameEqualsIgnoreCase(testFileName)).thenReturn(true);
|
||||
|
||||
imageService.deleteImage(testDirectory.toString(), testFileName);
|
||||
logger.info("Usunięto plik: {}", testFileName);
|
||||
|
||||
assertFalse(Files.exists(testFilePath));
|
||||
verify(imageRepository).deleteByImageNameEquals(testFileName);
|
||||
logger.info("Test usuwania obrazu - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie zwrócić listę nazw obrazów")
|
||||
void shouldGetImagesListForNotice() throws Exception {
|
||||
logger.info("Test pobierania listy obrazów - rozpoczęcie");
|
||||
|
||||
final Long noticeId = 1L;
|
||||
final List<String> expectedNames = List.of("image1.jpg", "image2.jpg");
|
||||
final List<Image> mockImages = expectedNames.stream()
|
||||
.map(name -> {
|
||||
Image img = new Image();
|
||||
img.setImageName(name);
|
||||
return img;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
when(imageRepository.findByNoticeId(noticeId)).thenReturn(mockImages);
|
||||
logger.debug("Skonfigurowano mock repository dla noticeId: {}", noticeId);
|
||||
|
||||
final List<String> imageNames = imageService.getImagesList(noticeId);
|
||||
logger.info("Pobrano listę {} obrazów", imageNames.size());
|
||||
|
||||
assertThat(imageNames).containsExactlyElementsOf(expectedNames);
|
||||
logger.info("Test pobierania listy obrazów - zakończony pomyślnie");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Nested
|
||||
@DisplayName("Testy dla VariablesController")
|
||||
@Transactional
|
||||
class VariablesControllerTest {
|
||||
|
||||
private final int port;
|
||||
private final TestRestTemplate restTemplate;
|
||||
|
||||
@Autowired
|
||||
public VariablesControllerTest(@LocalServerPort int port, TestRestTemplate restTemplate) {
|
||||
this.port = port;
|
||||
this.restTemplate = restTemplate;
|
||||
logger.info("Inicjalizacja testów VariablesController");
|
||||
}
|
||||
|
||||
private String registerAndGetJwtToken(String emailPrefix) {
|
||||
logger.info("Rozpoczęcie procesu rejestracji dla prefiksu email: {}", emailPrefix);
|
||||
String email = emailPrefix + "_" + UUID.randomUUID().toString().substring(0, 8) + "@example.com";
|
||||
logger.debug("Wygenerowany email: {}", email);
|
||||
|
||||
ClientRegistrationDTO registrationDTO = new ClientRegistrationDTO();
|
||||
registrationDTO.setEmail(email);
|
||||
registrationDTO.setFirstName("Test");
|
||||
registrationDTO.setLastName("User");
|
||||
registrationDTO.setPassword("password123");
|
||||
|
||||
ResponseEntity<AuthResponseDTO> response = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/register"),
|
||||
registrationDTO,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
|
||||
if (response.getStatusCode() == HttpStatus.CONFLICT) {
|
||||
logger.warn("Użytkownik już istnieje, próba logowania");
|
||||
AuthRequestDTO loginRequest = new AuthRequestDTO();
|
||||
loginRequest.setEmail(email);
|
||||
loginRequest.setPassword("password123");
|
||||
|
||||
response = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/login"),
|
||||
loginRequest,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
} else {
|
||||
logger.info("Pomyślnie zarejestrowano nowego użytkownika");
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
assertThat(response.getBody()).isNotNull();
|
||||
logger.debug("Otrzymano token JWT");
|
||||
return response.getBody().getToken();
|
||||
}
|
||||
|
||||
private HttpEntity<Void> createRequestWithToken(String token) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set("Authorization", "Bearer " + token);
|
||||
return new HttpEntity<>(headers);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić kategorie")
|
||||
void shouldGetCategories() {
|
||||
logger.info("Test pobierania kategorii - rozpoczęcie");
|
||||
String token = registerAndGetJwtToken(
|
||||
"categories"
|
||||
);
|
||||
logger.debug("Otrzymano token autoryzacyjny");
|
||||
|
||||
String url = createURLWithPort("/api/v1/vars/categories");
|
||||
logger.debug("Utworzono URL endpointu: {}", url);
|
||||
|
||||
HttpEntity<Void> request = createRequestWithToken(token);
|
||||
ResponseEntity<CategoriesDTO[]> response = restTemplate.exchange(
|
||||
url,
|
||||
HttpMethod.GET,
|
||||
request,
|
||||
CategoriesDTO[].class
|
||||
);
|
||||
logger.info("Wykonano zapytanie o kategorie");
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull().isNotEmpty();
|
||||
logger.info("Test pobierania kategorii - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić statusy")
|
||||
void shouldGetStatuses() {
|
||||
String token = registerAndGetJwtToken(
|
||||
"statuses"
|
||||
);
|
||||
|
||||
String url = createURLWithPort("/api/v1/vars/statuses");
|
||||
|
||||
HttpEntity<Void> request = createRequestWithToken(token);
|
||||
ResponseEntity<Enums.Status[]> response = restTemplate.exchange(
|
||||
url,
|
||||
HttpMethod.GET,
|
||||
request,
|
||||
Enums.Status[].class
|
||||
);
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull().isNotEmpty();
|
||||
}
|
||||
|
||||
|
||||
private String createURLWithPort(String uri) {
|
||||
return "http://localhost:" + port + uri;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Nested
|
||||
@DisplayName("Testy integracyjne AuthController")
|
||||
@Transactional
|
||||
class AuthControllerTest {
|
||||
|
||||
private final int port;
|
||||
private final TestRestTemplate restTemplate;
|
||||
private final ClientRepository clientRepository;
|
||||
private final NoticeRepository noticeRepository;
|
||||
private final Logger logger = LogManager.getLogger(AuthControllerTest.class);
|
||||
|
||||
@Autowired
|
||||
public AuthControllerTest(
|
||||
@LocalServerPort int port,
|
||||
TestRestTemplate restTemplate,
|
||||
ClientRepository clientRepository,
|
||||
NoticeRepository noticeRepository) {
|
||||
this.port = port;
|
||||
this.restTemplate = restTemplate;
|
||||
this.clientRepository = clientRepository;
|
||||
this.noticeRepository = noticeRepository;
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void cleanDatabase() {
|
||||
noticeRepository.deleteAll();
|
||||
clientRepository.deleteAll();
|
||||
}
|
||||
|
||||
private String createURLWithPort(String uri) {
|
||||
return "http://localhost:" + port + uri;
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić błąd przy rejestracji z istniejącym emailem")
|
||||
void shouldFailRegisterWithExistingEmail() {
|
||||
String email = "user_" + UUID.randomUUID().toString().substring(0, 8) + "@example.com";
|
||||
ClientRegistrationDTO registrationDTO = new ClientRegistrationDTO();
|
||||
registrationDTO.setEmail(email);
|
||||
registrationDTO.setFirstName("Jan");
|
||||
registrationDTO.setLastName("Kowalski");
|
||||
registrationDTO.setPassword("password123");
|
||||
|
||||
ResponseEntity<AuthResponseDTO> firstResponse = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/register"),
|
||||
registrationDTO,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
assertThat(firstResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED);
|
||||
|
||||
ResponseEntity<AuthResponseDTO> secondResponse = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/register"),
|
||||
registrationDTO,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
logger.info("Wysłano żądanie rejestracji");
|
||||
|
||||
assertThat(secondResponse.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien poprawnie zalogować istniejącego użytkownika")
|
||||
void shouldLoginExistingUser() {
|
||||
logger.info("Test logowania użytkownika - rozpoczęcie");
|
||||
String email = "user_" + UUID.randomUUID().toString().substring(0, 8) + "@example.com";
|
||||
String password = "password123";
|
||||
|
||||
ClientRegistrationDTO registrationDTO = new ClientRegistrationDTO();
|
||||
registrationDTO.setEmail(email);
|
||||
registrationDTO.setFirstName("Jan");
|
||||
registrationDTO.setLastName("Kowalski");
|
||||
registrationDTO.setPassword(password);
|
||||
restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/register"),
|
||||
registrationDTO,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
logger.debug("Zarejestrowano testowego użytkownika: {}", email);
|
||||
|
||||
AuthRequestDTO loginRequest = new AuthRequestDTO();
|
||||
loginRequest.setEmail(email);
|
||||
loginRequest.setPassword(password);
|
||||
|
||||
ResponseEntity<AuthResponseDTO> response = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/login"),
|
||||
loginRequest,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
logger.info("Wykonano próbę logowania");
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull();
|
||||
assertThat(response.getBody().getToken()).isNotBlank();
|
||||
logger.info("Test logowania - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić błąd przy logowaniu z nieprawidłowym hasłem")
|
||||
void shouldFailLoginWithIncorrectPassword() {
|
||||
logger.info("Test obsługi błędnych danych logowania - rozpoczęcie");
|
||||
String email = "user_" + UUID.randomUUID().toString().substring(0, 8) + "@example.com";
|
||||
String password = "password123";
|
||||
|
||||
ClientRegistrationDTO registrationDTO = new ClientRegistrationDTO();
|
||||
registrationDTO.setEmail(email);
|
||||
registrationDTO.setFirstName("Jan");
|
||||
registrationDTO.setLastName("Kowalski");
|
||||
registrationDTO.setPassword(password);
|
||||
restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/register"),
|
||||
registrationDTO,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
|
||||
AuthRequestDTO loginRequest = new AuthRequestDTO();
|
||||
loginRequest.setEmail(email);
|
||||
loginRequest.setPassword("wrongPassword");
|
||||
logger.debug("Przygotowano nieprawidłowe dane logowania");
|
||||
|
||||
ResponseEntity<AuthResponseDTO> response = restTemplate.postForEntity(
|
||||
createURLWithPort("/api/v1/auth/login"),
|
||||
loginRequest,
|
||||
AuthResponseDTO.class
|
||||
);
|
||||
logger.info("Wykonano próbę logowania z błędnymi danymi");
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
logger.info("Test obsługi błędnych danych - zakończony pomyślnie");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.customExceptions.ClientAlreadyExistsException;
|
||||
import _11.asktpk.artisanconnectbackend.customExceptions.WrongLoginPasswordException;
|
||||
import _11.asktpk.artisanconnectbackend.dto.AuthResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Role;
|
||||
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
||||
import _11.asktpk.artisanconnectbackend.service.AuthService;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class AuthServiceTest {
|
||||
|
||||
private final ClientService clientService = Mockito.mock(ClientService.class);
|
||||
private final PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
|
||||
private final JwtUtil jwtUtil = Mockito.mock(JwtUtil.class);
|
||||
private final AuthService authService = new AuthService(clientService, jwtUtil, passwordEncoder);
|
||||
|
||||
|
||||
@Test
|
||||
@DisplayName("Test logowania - poprawne dane")
|
||||
public void testLoginSuccess() throws Exception {
|
||||
String email = "test@example.com";
|
||||
String password = "password";
|
||||
Client client = new Client();
|
||||
client.setEmail(email);
|
||||
client.setPassword("encodedPassword");
|
||||
client.setRole(new Role());
|
||||
|
||||
when(clientService.getClientByEmail(email)).thenReturn(client);
|
||||
when(passwordEncoder.matches(password, client.getPassword())).thenReturn(true);
|
||||
when(jwtUtil.generateToken(email, client.getRole().getRole(), client.getId())).thenReturn("token");
|
||||
|
||||
AuthResponseDTO response = authService.login(email, password);
|
||||
|
||||
assertNotNull(response, "Odpowiedź nie powinna być null");
|
||||
assertEquals("token", response.getToken(), "Token w odpowiedzi powinien być poprawny");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test logowania - niepoprawne hasło")
|
||||
public void testLoginWrongPassword() {
|
||||
String email = "test@example.com";
|
||||
String password = "wrongPassword";
|
||||
Client client = new Client();
|
||||
client.setEmail(email);
|
||||
client.setPassword("encodedPassword");
|
||||
|
||||
when(clientService.getClientByEmail(email)).thenReturn(client);
|
||||
when(passwordEncoder.matches(password, client.getPassword())).thenReturn(false);
|
||||
|
||||
assertThrows(WrongLoginPasswordException.class, () -> authService.login(email, password),
|
||||
"Powinien zostać rzucony WrongLoginPasswordException");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test rejestracji - nowy użytkownik")
|
||||
public void testRegisterNewUser() throws Exception {
|
||||
String email = "new@example.com";
|
||||
String password = "password";
|
||||
String firstName = "Jan";
|
||||
String lastName = "Kowalski";
|
||||
|
||||
when(clientService.getClientByEmail(email)).thenReturn(null);
|
||||
when(passwordEncoder.encode(password)).thenReturn("encodedPassword");
|
||||
when(clientService.registerClient(any(Client.class))).thenReturn(new ClientDTO());
|
||||
|
||||
AuthResponseDTO response = authService.register(email, password, firstName, lastName);
|
||||
|
||||
assertNotNull(response, "Odpowiedź nie powinna być null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test rejestracji - użytkownik już istnieje")
|
||||
public void testRegisterExistingUser() {
|
||||
String email = "existing@example.com";
|
||||
String password = "password";
|
||||
String firstName = "Jan";
|
||||
String lastName = "Kowalski";
|
||||
|
||||
when(clientService.getClientByEmail(email)).thenReturn(new Client());
|
||||
|
||||
assertThrows(ClientAlreadyExistsException.class, () -> authService.register(email, password, firstName, lastName),
|
||||
"Powinien zostać rzucony ClientAlreadyExistsException");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test wylogowania z poprawnym tokenem")
|
||||
public void testLogoutWithValidToken() {
|
||||
String token = "valid.token.here";
|
||||
|
||||
when(jwtUtil.isBlacklisted(token)).thenReturn(false);
|
||||
|
||||
authService.logout(token);
|
||||
|
||||
verify(jwtUtil, times(1)).blacklistToken(token);
|
||||
|
||||
when(jwtUtil.isBlacklisted(token)).thenReturn(true);
|
||||
assertTrue(jwtUtil.isBlacklisted(token), "Token powinien być na czarnej liście po wylogowaniu");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test wylogowania bez tokena")
|
||||
public void testLogoutWithoutToken() {
|
||||
authService.logout(null);
|
||||
|
||||
verify(jwtUtil, never()).blacklistToken(anyString());
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.controller.ClientController;
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
class ClientControllerTest {
|
||||
|
||||
private MockMvc mockMvc;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Mock
|
||||
private ClientService clientService;
|
||||
|
||||
@InjectMocks
|
||||
private ClientController clientController;
|
||||
|
||||
private ClientDTO sampleClientDTO;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Inicjalizacja konfiguracji testu...");
|
||||
MockitoAnnotations.openMocks(this);
|
||||
mockMvc = MockMvcBuilders.standaloneSetup(clientController).build();
|
||||
|
||||
sampleClientDTO = new ClientDTO();
|
||||
sampleClientDTO.setId(1L);
|
||||
sampleClientDTO.setEmail("test@example.com");
|
||||
sampleClientDTO.setFirstName("John");
|
||||
sampleClientDTO.setLastName("Doe");
|
||||
sampleClientDTO.setRole("USER");
|
||||
System.out.println("Konfiguracja testu zakończona z przykładowym klientem: " + sampleClientDTO);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić listę klientów")
|
||||
void getAllClients_ShouldReturnListOfClients() throws Exception {
|
||||
System.out.println("Uruchamianie testu: getAllClients_ShouldReturnListOfClients");
|
||||
|
||||
List<ClientDTO> clients = Collections.singletonList(sampleClientDTO);
|
||||
when(clientService.getAllClients()).thenReturn(clients);
|
||||
System.out.println("Konfiguracja mocka: clientService.getAllClients() zwróci " + clients);
|
||||
|
||||
mockMvc.perform(get("/api/v1/clients/get/all"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].id").value(1L))
|
||||
.andExpect(jsonPath("$[0].email").value("test@example.com"));
|
||||
|
||||
verify(clientService, times(1)).getAllClients();
|
||||
System.out.println("Test zaliczony: Pomyślnie pobrano listę klientów");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien utworzyć nowego klienta")
|
||||
void addClient_WhenClientNotExists_ShouldCreateClient() throws Exception {
|
||||
System.out.println("Uruchamianie testu: addClient_WhenClientNotExists_ShouldCreateClient");
|
||||
|
||||
when(clientService.clientExists(anyLong())).thenReturn(false);
|
||||
when(clientService.addClient(any(ClientDTO.class))).thenReturn(sampleClientDTO);
|
||||
System.out.println("Konfiguracja mocka: clientService.addClient() zwróci " + sampleClientDTO);
|
||||
|
||||
mockMvc.perform(post("/api/v1/clients/add")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(sampleClientDTO)))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(jsonPath("$.id").value(1L));
|
||||
|
||||
verify(clientService, times(1)).addClient(any(ClientDTO.class));
|
||||
System.out.println("Test zaliczony: Pomyślnie utworzono nowego klienta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić 409 gdy klient istnieje")
|
||||
void addClient_WhenClientExists_ShouldReturnConflict() throws Exception {
|
||||
System.out.println("Uruchamianie testu: addClient_WhenClientExists_ShouldReturnConflict");
|
||||
|
||||
when(clientService.clientExists(anyLong())).thenReturn(true);
|
||||
System.out.println("Konfiguracja mocka: clientService.clientExists() zwróci true");
|
||||
|
||||
mockMvc.perform(post("/api/v1/clients/add")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(sampleClientDTO)))
|
||||
.andExpect(status().isConflict());
|
||||
|
||||
verify(clientService, times(0)).addClient(any(ClientDTO.class));
|
||||
System.out.println("Test zaliczony: Poprawnie zwrócono 409 dla istniejącego klienta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zaktualizować istniejącego klienta")
|
||||
void updateClient_WhenClientExists_ShouldUpdateClient() throws Exception {
|
||||
System.out.println("Uruchamianie testu: updateClient_WhenClientExists_ShouldUpdateClient");
|
||||
|
||||
when(clientService.clientExists(1L)).thenReturn(true);
|
||||
when(clientService.updateClient(anyLong(), any(ClientDTO.class))).thenReturn(sampleClientDTO);
|
||||
System.out.println("Konfiguracja mocka: clientService.updateClient() zwróci " + sampleClientDTO);
|
||||
|
||||
mockMvc.perform(put("/api/v1/clients/edit/1")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(sampleClientDTO)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(1L));
|
||||
|
||||
verify(clientService, times(1)).updateClient(anyLong(), any(ClientDTO.class));
|
||||
System.out.println("Test zaliczony: Pomyślnie zaktualizowano klienta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić 404 gdy klient nie istnieje")
|
||||
void updateClient_WhenClientNotExists_ShouldReturnNotFound() throws Exception {
|
||||
System.out.println("Uruchamianie testu: updateClient_WhenClientNotExists_ShouldReturnNotFound");
|
||||
|
||||
when(clientService.clientExists(1L)).thenReturn(false);
|
||||
System.out.println("Konfiguracja mocka: clientService.clientExists(1L) zwróci false");
|
||||
|
||||
mockMvc.perform(put("/api/v1/clients/edit/1")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(sampleClientDTO)))
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
verify(clientService, times(0)).updateClient(anyLong(), any(ClientDTO.class));
|
||||
System.out.println("Test zaliczony: Poprawnie zwrócono 404 dla nieistniejącego klienta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien usunąć istniejącego klienta")
|
||||
void deleteClient_WhenClientExists_ShouldDeleteClient() throws Exception {
|
||||
System.out.println("Uruchamianie testu: deleteClient_WhenClientExists_ShouldDeleteClient");
|
||||
|
||||
when(clientService.clientExists(1L)).thenReturn(true);
|
||||
doNothing().when(clientService).deleteClient(1L);
|
||||
System.out.println("Konfiguracja mocka: clientService.deleteClient(1L) nie zrobi nic");
|
||||
|
||||
mockMvc.perform(delete("/api/v1/clients/delete/1"))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
verify(clientService, times(1)).deleteClient(1L);
|
||||
System.out.println("Test zaliczony: Pomyślnie usunięto klienta");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Powinien zwrócić 404 gdy klient nie istnieje")
|
||||
void deleteClient_WhenClientNotExists_ShouldReturnNotFound() throws Exception {
|
||||
System.out.println("Uruchamianie testu: deleteClient_WhenClientNotExists_ShouldReturnNotFound");
|
||||
|
||||
when(clientService.clientExists(1L)).thenReturn(false);
|
||||
System.out.println("Konfiguracja mocka: clientService.clientExists(1L) zwróci false");
|
||||
|
||||
mockMvc.perform(delete("/api/v1/clients/delete/1"))
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
verify(clientService, times(0)).deleteClient(anyLong());
|
||||
System.out.println("Test zaliczony: Poprawnie zwrócono 404 dla nieistniejącego klienta");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.ClientDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Role;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.RolesRepository;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class ClientServiceTest {
|
||||
|
||||
private final ClientRepository clientRepository = Mockito.mock(ClientRepository.class);
|
||||
private final RolesRepository rolesRepository = Mockito.mock(RolesRepository.class);
|
||||
|
||||
private final ClientService clientService = new ClientService(clientRepository, rolesRepository);
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania wszystkich klientów")
|
||||
public void testGetAllClients() {
|
||||
System.out.println("Rozpoczęcie testu: testGetAllClients - Test pobierania wszystkich klientów");
|
||||
|
||||
Client client1 = new Client();
|
||||
client1.setId(1L);
|
||||
client1.setEmail("client1@example.com");
|
||||
client1.setRole(new Role());
|
||||
|
||||
Client client2 = new Client();
|
||||
client2.setId(2L);
|
||||
client2.setEmail("client2@example.com");
|
||||
client2.setRole(new Role());
|
||||
|
||||
when(clientRepository.findAll()).thenReturn(List.of(client1, client2));
|
||||
|
||||
List<ClientDTO> clients = clientService.getAllClients();
|
||||
|
||||
System.out.println("Pobrano listę klientów, liczba elementów: " + clients.size());
|
||||
assertEquals(2, clients.size(), "Lista klientów powinna zawierać 2 elementy");
|
||||
System.out.println("Pierwszy klient na liście: " + clients.getFirst().getEmail());
|
||||
assertEquals("client1@example.com", clients.getFirst().getEmail(), "Email pierwszego klienta powinien być poprawny");
|
||||
|
||||
System.out.println("Test pobierania wszystkich klientów zakończony sukcesem. Zwrócono " + clients.size() + " klientów.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania klienta po ID - klient istnieje")
|
||||
public void testGetClientByIdExists() {
|
||||
Long clientId = 1L;
|
||||
System.out.println("Rozpoczęcie testu: testGetClientByIdExists - Test pobierania klienta po ID (ID: " + clientId + ")");
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(clientId);
|
||||
client.setEmail("client@example.com");
|
||||
client.setRole(new Role());
|
||||
|
||||
when(clientRepository.findById(clientId)).thenReturn(Optional.of(client));
|
||||
|
||||
Client retrievedClient = clientService.getClientById(clientId);
|
||||
|
||||
System.out.println("Pobrano klienta o ID: " + (retrievedClient != null ? retrievedClient.getId() : "null"));
|
||||
assertNotNull(retrievedClient, "Pobrany klient nie powinien być null");
|
||||
assertEquals(clientId, retrievedClient.getId(), "ID klienta powinno być zgodne");
|
||||
|
||||
System.out.println("Test pobierania klienta po ID (ID: " + clientId + ") zakończony sukcesem. Znaleziono klienta: " + retrievedClient.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania klienta po ID - klient nie istnieje")
|
||||
public void testGetClientByIdNotExists() {
|
||||
Long clientId = 1L;
|
||||
System.out.println("Rozpoczęcie testu: testGetClientByIdNotExists - Test pobierania nieistniejącego klienta (ID: " + clientId + ")");
|
||||
|
||||
when(clientRepository.findById(clientId)).thenReturn(Optional.empty());
|
||||
|
||||
Client retrievedClient = clientService.getClientById(clientId);
|
||||
|
||||
System.out.println("Próba pobrania nieistniejącego klienta zwróciła: " + retrievedClient);
|
||||
assertNull(retrievedClient, "Pobrany klient powinien być null, gdy nie istnieje");
|
||||
|
||||
System.out.println("Test pobierania nieistniejącego klienta (ID: " + clientId + ") zakończony sukcesem. Zwrócono null zgodnie z oczekiwaniami.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania klienta po emailu")
|
||||
public void testGetClientByEmail() {
|
||||
String email = "client@example.com";
|
||||
System.out.println("Rozpoczęcie testu: testGetClientByEmail - Test pobierania klienta po emailu (" + email + ")");
|
||||
|
||||
Client client = new Client();
|
||||
client.setEmail(email);
|
||||
|
||||
when(clientRepository.findByEmail(email)).thenReturn(client);
|
||||
|
||||
Client retrievedClient = clientService.getClientByEmail(email);
|
||||
|
||||
System.out.println("Pobrano klienta o emailu: " + (retrievedClient != null ? retrievedClient.getEmail() : "null"));
|
||||
assertNotNull(retrievedClient, "Pobrany klient nie powinien być null");
|
||||
assertEquals(email, retrievedClient.getEmail(), "Email klienta powinien być zgodny");
|
||||
|
||||
System.out.println("Test pobierania klienta po emailu (" + email + ") zakończony sukcesem.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test dodawania klienta")
|
||||
public void testAddClient() {
|
||||
System.out.println("Rozpoczęcie testu: testAddClient - Test dodawania nowego klienta");
|
||||
|
||||
ClientDTO clientDTO = new ClientDTO();
|
||||
clientDTO.setEmail("newclient@example.com");
|
||||
clientDTO.setRole("USER");
|
||||
|
||||
Client client = new Client();
|
||||
client.setEmail("newclient@example.com");
|
||||
client.setRole(new Role());
|
||||
|
||||
when(clientRepository.save(any(Client.class))).thenReturn(client);
|
||||
|
||||
ClientDTO addedClient = clientService.addClient(clientDTO);
|
||||
|
||||
System.out.println("Dodano nowego klienta: " + (addedClient != null ? addedClient.getEmail() : "null"));
|
||||
assertNotNull(addedClient, "Dodany klient nie powinien być null");
|
||||
assertEquals("newclient@example.com", addedClient.getEmail(), "Email dodanego klienta powinien być poprawny");
|
||||
|
||||
System.out.println("Test dodawania klienta zakończony sukcesem. Dodano klienta: " + addedClient.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test aktualizacji klienta")
|
||||
public void testUpdateClient() {
|
||||
Long clientId = 1L;
|
||||
System.out.println("Rozpoczęcie testu: testUpdateClient - Test aktualizacji klienta (ID: " + clientId + ")");
|
||||
|
||||
Client existingClient = new Client();
|
||||
existingClient.setId(clientId);
|
||||
existingClient.setEmail("old@example.com");
|
||||
|
||||
ClientDTO updatedDTO = new ClientDTO();
|
||||
updatedDTO.setEmail("updated@example.com");
|
||||
updatedDTO.setRole("USER");
|
||||
|
||||
Role role = new Role();
|
||||
role.setRole("USER");
|
||||
|
||||
when(clientRepository.findById(clientId)).thenReturn(Optional.of(existingClient));
|
||||
when(rolesRepository.findRoleByRole("USER")).thenReturn(role);
|
||||
when(clientRepository.save(any(Client.class))).thenReturn(existingClient);
|
||||
|
||||
ClientDTO updatedClient = clientService.updateClient(clientId, updatedDTO);
|
||||
|
||||
System.out.println("Zaktualizowano klienta. Nowy email: " + updatedClient.getEmail());
|
||||
assertEquals("updated@example.com", updatedClient.getEmail(), "Email klienta powinien być zaktualizowany");
|
||||
|
||||
System.out.println("Test aktualizacji klienta (ID: " + clientId + ") zakończony sukcesem. Nowy email: " + updatedClient.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test aktualizacji klienta - klient nie istnieje")
|
||||
public void testUpdateClientNotExists() {
|
||||
long clientId = 1L;
|
||||
System.out.println("Rozpoczęcie testu: testUpdateClientNotExists - Test aktualizacji nieistniejącego klienta (ID: " + clientId + ")");
|
||||
|
||||
ClientDTO updatedDTO = new ClientDTO();
|
||||
updatedDTO.setEmail("updated@example.com");
|
||||
|
||||
when(clientRepository.findById(clientId)).thenReturn(Optional.empty());
|
||||
|
||||
System.out.println("Oczekiwanie na EntityNotFoundException...");
|
||||
assertThrows(EntityNotFoundException.class, () -> clientService.updateClient(clientId, updatedDTO),
|
||||
"Powinien zostać rzucony EntityNotFoundException");
|
||||
|
||||
System.out.println("Test aktualizacji nieistniejącego klienta (ID: " + clientId + ") zakończony sukcesem. Rzucono wyjątek EntityNotFoundException zgodnie z oczekiwaniami.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test usuwania klienta")
|
||||
public void testDeleteClient() {
|
||||
Long clientId = 1L;
|
||||
System.out.println("Rozpoczęcie testu: testDeleteClient - Test usuwania klienta (ID: " + clientId + ")");
|
||||
|
||||
clientService.deleteClient(clientId);
|
||||
|
||||
verify(clientRepository, times(1)).deleteById(clientId);
|
||||
System.out.println("Weryfikacja: metoda deleteById została wywołana 1 raz z ID: " + clientId);
|
||||
|
||||
System.out.println("Test usuwania klienta (ID: " + clientId + ") zakończony sukcesem.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test konwersji encji do DTO")
|
||||
public void testToDto() {
|
||||
System.out.println("Rozpoczęcie testu: testToDto - Test konwersji encji Client do ClientDTO");
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(1L);
|
||||
client.setEmail("client@example.com");
|
||||
client.setFirstName("Jan");
|
||||
client.setLastName("Kowalski");
|
||||
client.setImage("image.jpg");
|
||||
Role role = new Role();
|
||||
role.setRole("USER");
|
||||
client.setRole(role);
|
||||
|
||||
System.out.println("Przygotowano encję Client do konwersji:");
|
||||
System.out.println("ID: " + client.getId());
|
||||
System.out.println("Email: " + client.getEmail());
|
||||
System.out.println("Imię: " + client.getFirstName());
|
||||
System.out.println("Nazwisko: " + client.getLastName());
|
||||
System.out.println("Obraz: " + client.getImage());
|
||||
System.out.println("Rola: " + client.getRole().getRole());
|
||||
|
||||
ClientDTO dto = clientService.toDto(client);
|
||||
|
||||
System.out.println("Wynik konwersji do DTO:");
|
||||
System.out.println("ID: " + dto.getId());
|
||||
System.out.println("Email: " + dto.getEmail());
|
||||
System.out.println("Imię: " + dto.getFirstName());
|
||||
System.out.println("Nazwisko: " + dto.getLastName());
|
||||
System.out.println("Obraz: " + dto.getImage());
|
||||
System.out.println("Rola: " + dto.getRole());
|
||||
|
||||
assertEquals(1L, dto.getId(), "ID w DTO powinno być zgodne");
|
||||
assertEquals("client@example.com", dto.getEmail(), "Email w DTO powinien być zgodny");
|
||||
assertEquals("Jan", dto.getFirstName(), "Imię w DTO powinno być zgodne");
|
||||
assertEquals("Kowalski", dto.getLastName(), "Nazwisko w DTO powinno być zgodne");
|
||||
assertEquals("image.jpg", dto.getImage(), "Obraz w DTO powinien być zgodny");
|
||||
assertEquals("USER", dto.getRole(), "Rola w DTO powinna być zgodna");
|
||||
|
||||
System.out.println("Test konwersji encji do DTO zakończony sukcesem. Wszystkie pola zostały poprawnie zmapowane.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.controller.NoticeController;
|
||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Tools;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class NoticeControllerTest {
|
||||
|
||||
@Mock
|
||||
private NoticeService noticeService;
|
||||
|
||||
@Mock
|
||||
private ClientService clientService;
|
||||
|
||||
@Mock
|
||||
private Tools tools;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@InjectMocks
|
||||
private NoticeController noticeController;
|
||||
|
||||
private NoticeResponseDTO sampleNotice;
|
||||
private NoticeRequestDTO sampleNoticeRequest;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Inicjalizacja danych testowych...");
|
||||
|
||||
sampleNotice = new NoticeResponseDTO();
|
||||
sampleNotice.setNoticeId(1L);
|
||||
sampleNotice.setTitle("Testowe ogłoszenie");
|
||||
sampleNotice.setClientId(1L);
|
||||
sampleNotice.setDescription("Opis testowego ogłoszenia");
|
||||
sampleNotice.setPrice(100.0);
|
||||
sampleNotice.setCategory(Enums.Category.Woodworking);
|
||||
sampleNotice.setStatus(Enums.Status.ACTIVE);
|
||||
sampleNotice.setPublishDate(LocalDateTime.now());
|
||||
|
||||
sampleNoticeRequest = new NoticeRequestDTO();
|
||||
sampleNoticeRequest.setTitle("Testowe ogłoszenie");
|
||||
sampleNoticeRequest.setClientId(1L);
|
||||
sampleNoticeRequest.setDescription("Opis testowego ogłoszenia");
|
||||
sampleNoticeRequest.setPrice(100.0);
|
||||
sampleNoticeRequest.setCategory(Enums.Category.Woodworking);
|
||||
sampleNoticeRequest.setStatus(Enums.Status.ACTIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie wszystkich ogłoszeń")
|
||||
void getAllNotices_ShouldReturnListOfNotices() {
|
||||
when(noticeService.getAllNotices()).thenReturn(List.of(sampleNotice));
|
||||
|
||||
List<NoticeResponseDTO> result = noticeController.getAllNotices();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
System.out.println("Test GET /notices zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie istniejącego ogłoszenia")
|
||||
void getNoticeById_WhenNoticeExists_ShouldReturnNotice() {
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.getNoticeById(1L)).thenReturn(sampleNotice);
|
||||
|
||||
ResponseEntity<?> response = noticeController.getNoticeById(1L);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
System.out.println("Test GET /notices/{id} (istniejące) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie nieistniejącego ogłoszenia")
|
||||
void getNoticeById_WhenNoticeNotExists_ShouldReturnNotFound() {
|
||||
when(noticeService.noticeExists(1L)).thenReturn(false);
|
||||
|
||||
ResponseEntity<?> response = noticeController.getNoticeById(1L);
|
||||
|
||||
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
|
||||
System.out.println("Test GET /notices/{id} (nieistniejące) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie poprawnego ogłoszenia")
|
||||
void addNotice_WithValidData_ShouldCreateNotice() {
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(clientService.clientExists(1L)).thenReturn(true);
|
||||
when(noticeService.addNotice(any(NoticeRequestDTO.class))).thenReturn(1L);
|
||||
|
||||
ResponseEntity<NoticeAdditionDTO> response = noticeController.addNotice(sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.CREATED, response.getStatusCode());
|
||||
System.out.println("Test POST /notices (poprawne dane) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie ogłoszenia z błędną kategorią")
|
||||
void addNotice_WithInvalidCategory_ShouldReturnBadRequest() {
|
||||
sampleNoticeRequest.setCategory(null);
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(clientService.clientExists(1L)).thenReturn(true);
|
||||
|
||||
ResponseEntity<NoticeAdditionDTO> response = noticeController.addNotice(sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
|
||||
System.out.println("Test POST /notices (błędna kategoria) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie ogłoszenia przez nieistniejącego klienta")
|
||||
void addNotice_WhenClientNotExists_ShouldReturnBadRequest() {
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(clientService.clientExists(1L)).thenReturn(false);
|
||||
|
||||
ResponseEntity<NoticeAdditionDTO> response = noticeController.addNotice(sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
|
||||
System.out.println("Test POST /notices (nieistniejący klient) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Aktualizacja własnego ogłoszenia")
|
||||
void editNotice_WhenNoticeExistsAndOwnedByClient_ShouldUpdateNotice() {
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.isNoticeOwnedByClient(1L, 1L)).thenReturn(true);
|
||||
when(noticeService.updateNotice(anyLong(), any(NoticeRequestDTO.class))).thenReturn(sampleNotice);
|
||||
|
||||
ResponseEntity<Object> response = noticeController.editNotice(1L, sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
System.out.println("Test PUT /notices/{id} (własne ogłoszenie) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Próba aktualizacji cudzego ogłoszenia")
|
||||
void editNotice_WhenNoticeNotOwnedByClient_ShouldReturnForbidden() {
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(2L);
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.isNoticeOwnedByClient(1L, 2L)).thenReturn(false);
|
||||
|
||||
ResponseEntity<Object> response = noticeController.editNotice(1L, sampleNoticeRequest, request);
|
||||
|
||||
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
|
||||
System.out.println("Test PUT /notices/{id} (cudze ogłoszenie) zakończony sukcesem");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Usunięcie własnego ogłoszenia")
|
||||
void deleteNotice_WhenNoticeExistsAndOwnedByClient_ShouldDeleteNotice() {
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(noticeService.noticeExists(1L)).thenReturn(true);
|
||||
when(noticeService.isNoticeOwnedByClient(1L, 1L)).thenReturn(true);
|
||||
|
||||
ResponseEntity<RequestResponseDTO> response = noticeController.deleteNotice(1L, request);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
verify(noticeService, times(1)).deleteNotice(1L);
|
||||
System.out.println("Test DELETE /notices/{id} (własne ogłoszenie) zakończony sukcesem");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.AttributeDto;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeRequestDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.*;
|
||||
import _11.asktpk.artisanconnectbackend.repository.*;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class NoticeServiceTest {
|
||||
|
||||
@Mock
|
||||
private NoticeRepository noticeRepository;
|
||||
|
||||
@Mock
|
||||
private ClientRepository clientRepository;
|
||||
|
||||
@Mock
|
||||
private AttributesRepository attributesRepository;
|
||||
|
||||
@Mock
|
||||
private AttributeValuesRepository attributeValuesRepository;
|
||||
|
||||
@Mock
|
||||
private AttributesNoticeRepository attributesNoticeRepository;
|
||||
|
||||
@InjectMocks
|
||||
private NoticeService noticeService;
|
||||
|
||||
private Notice sampleNotice;
|
||||
private NoticeRequestDTO sampleNoticeRequest;
|
||||
private Client sampleClient;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Przygotowanie danych testowych...");
|
||||
|
||||
sampleClient = new Client();
|
||||
sampleClient.setId(1L);
|
||||
sampleClient.setEmail("test@example.com");
|
||||
|
||||
sampleNotice = new Notice();
|
||||
sampleNotice.setIdNotice(1L);
|
||||
sampleNotice.setTitle("Testowe ogłoszenie");
|
||||
sampleNotice.setClient(sampleClient);
|
||||
sampleNotice.setDescription("Opis testowego ogłoszenia");
|
||||
sampleNotice.setPrice(100.0);
|
||||
sampleNotice.setCategory(Enums.Category.Woodworking);
|
||||
sampleNotice.setStatus(Enums.Status.ACTIVE);
|
||||
sampleNotice.setPublishDate(LocalDateTime.now());
|
||||
|
||||
sampleNoticeRequest = new NoticeRequestDTO();
|
||||
sampleNoticeRequest.setTitle("Testowe ogłoszenie");
|
||||
sampleNoticeRequest.setClientId(1L);
|
||||
sampleNoticeRequest.setDescription("Opis testowego ogłoszenia");
|
||||
sampleNoticeRequest.setPrice(100.0);
|
||||
sampleNoticeRequest.setCategory(Enums.Category.Woodworking);
|
||||
sampleNoticeRequest.setStatus(Enums.Status.ACTIVE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie wszystkich ogłoszeń - powinno zwrócić listę ogłoszeń")
|
||||
void getAllNotices_ShouldReturnListOfNotices() {
|
||||
when(noticeRepository.findAll()).thenReturn(List.of(sampleNotice));
|
||||
|
||||
List<NoticeResponseDTO> result = noticeService.getAllNotices();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
System.out.println("Test pobrania wszystkich ogłoszeń zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie ogłoszenia po ID - gdy istnieje")
|
||||
void getNoticeById_WhenNoticeExists_ShouldReturnNotice() {
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.of(sampleNotice));
|
||||
|
||||
NoticeResponseDTO result = noticeService.getNoticeById(1L);
|
||||
|
||||
assertNotNull(result);
|
||||
System.out.println("Test pobrania istniejącego ogłoszenia zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobranie ogłoszenia po ID - gdy nie istnieje")
|
||||
void getNoticeById_WhenNoticeNotExists_ShouldThrowException() {
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(EntityNotFoundException.class, () -> noticeService.getNoticeById(1L));
|
||||
System.out.println("Test pobrania nieistniejącego ogłoszenia zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie nowego ogłoszenia - poprawne dane")
|
||||
void addNotice_WithValidData_ShouldCreateNotice() {
|
||||
when(clientRepository.findById(1L)).thenReturn(Optional.of(sampleClient));
|
||||
when(noticeRepository.save(any(Notice.class))).thenReturn(sampleNotice);
|
||||
|
||||
Long result = noticeService.addNotice(sampleNoticeRequest);
|
||||
|
||||
assertNotNull(result);
|
||||
System.out.println("Test dodania ogłoszenia zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie ogłoszenia z atrybutami")
|
||||
void addNotice_WithAttributes_ShouldSaveAttributes() {
|
||||
AttributeDto attributeDto = new AttributeDto();
|
||||
attributeDto.setName("Kolor");
|
||||
attributeDto.setValue("Zielony");
|
||||
sampleNoticeRequest.setAttributes(List.of(attributeDto));
|
||||
|
||||
when(clientRepository.findById(1L)).thenReturn(Optional.of(sampleClient));
|
||||
when(noticeRepository.save(any(Notice.class))).thenReturn(sampleNotice);
|
||||
when(attributesRepository.findByName(anyString())).thenReturn(Optional.empty());
|
||||
when(attributeValuesRepository.findByAttributeAndValue(any(), anyString())).thenReturn(Optional.empty());
|
||||
|
||||
Long result = noticeService.addNotice(sampleNoticeRequest);
|
||||
|
||||
assertNotNull(result);
|
||||
System.out.println("Test dodania ogłoszenia z atrybutami zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Usunięcie istniejącego ogłoszenia")
|
||||
void deleteNotice_WhenNoticeExists_ShouldDeleteNotice() {
|
||||
when(noticeRepository.existsById(1L)).thenReturn(true);
|
||||
|
||||
noticeService.deleteNotice(1L);
|
||||
|
||||
System.out.println("Test usunięcia ogłoszenia zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Sprawdzenie właściciela ogłoszenia - gdy należy do klienta")
|
||||
void isNoticeOwnedByClient_WhenOwned_ShouldReturnTrue() {
|
||||
when(noticeRepository.existsByIdNoticeAndClientId(1L, 1L)).thenReturn(true);
|
||||
|
||||
boolean result = noticeService.isNoticeOwnedByClient(1L, 1L);
|
||||
|
||||
assertTrue(result);
|
||||
System.out.println("Test sprawdzenia właściciela (true) zakończony");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Boostowanie ogłoszenia - aktualizacja daty publikacji")
|
||||
void boostNotice_ShouldUpdatePublishDate() {
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.of(sampleNotice));
|
||||
when(noticeRepository.save(any(Notice.class))).thenReturn(sampleNotice);
|
||||
|
||||
noticeService.boostNotice(1L);
|
||||
|
||||
assertNotNull(sampleNotice.getPublishDate());
|
||||
System.out.println("Test boostowania ogłoszenia zakończony");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.controller.OrderController;
|
||||
import _11.asktpk.artisanconnectbackend.dto.*;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Order;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Payment;
|
||||
import _11.asktpk.artisanconnectbackend.service.OrderService;
|
||||
import _11.asktpk.artisanconnectbackend.service.PaymentService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Tools;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class OrderControllerTest {
|
||||
|
||||
private final OrderService orderService = Mockito.mock(OrderService.class);
|
||||
private final PaymentService paymentService = Mockito.mock(PaymentService.class);
|
||||
private final Tools tools = Mockito.mock(Tools.class);
|
||||
private final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
|
||||
|
||||
private OrderController orderController;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
orderController = new OrderController(orderService, paymentService, tools);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test dodawania zamówienia")
|
||||
public void testAddOrder() {
|
||||
OrderDTO orderDTO = new OrderDTO();
|
||||
orderDTO.setClientId(1L);
|
||||
orderDTO.setNoticeId(1L);
|
||||
orderDTO.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
|
||||
when(orderService.addOrder(orderDTO)).thenReturn(1L);
|
||||
|
||||
ResponseEntity<?> response = orderController.addClient(orderDTO, request);
|
||||
|
||||
assertEquals(HttpStatus.CREATED, response.getStatusCode(), "Status odpowiedzi powinien być 201 CREATED");
|
||||
assertEquals(1L, response.getBody(), "Ciało odpowiedzi powinno zawierać ID zamówienia");
|
||||
|
||||
System.out.println("Test dodawania zamówienia przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test zmiany statusu zamówienia")
|
||||
public void testChangeStatus() {
|
||||
OrderStatusDTO orderStatusDTO = new OrderStatusDTO();
|
||||
orderStatusDTO.setId(1L);
|
||||
orderStatusDTO.setStatus(Enums.OrderStatus.COMPLETED);
|
||||
|
||||
when(orderService.changeOrderStatus(1L, Enums.OrderStatus.COMPLETED)).thenReturn(1L);
|
||||
|
||||
ResponseEntity<?> response = orderController.changeStatus(orderStatusDTO);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status odpowiedzi powinien być 200 OK");
|
||||
assertEquals(1L, response.getBody(), "Ciało odpowiedzi powinno zawierać ID zamówienia");
|
||||
|
||||
System.out.println("Test zmiany statusu zamówienia przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania tokena płatności")
|
||||
public void testFetchToken() {
|
||||
Long orderId = 1L;
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
order.setAmount(10.00);
|
||||
order.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(1L);
|
||||
client.setEmail("test@example.com");
|
||||
client.setFirstName("Jan");
|
||||
client.setLastName("Kowalski");
|
||||
|
||||
Notice notice = new Notice();
|
||||
notice.setTitle("Test Notice");
|
||||
|
||||
order.setClient(client);
|
||||
order.setNotice(notice);
|
||||
|
||||
OAuthPaymentResponseDTO oAuthResponse = new OAuthPaymentResponseDTO();
|
||||
oAuthResponse.setAccess_token("testAccessToken");
|
||||
|
||||
when(orderService.getOrderById(orderId)).thenReturn(order);
|
||||
when(paymentService.getOAuthToken()).thenReturn(oAuthResponse);
|
||||
when(paymentService.createTransaction(eq(order), eq("testAccessToken"), any(TransactionPaymentRequestDTO.class)))
|
||||
.thenReturn("http://payment.url");
|
||||
|
||||
ResponseEntity<?> response = orderController.fetchToken(orderId);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status odpowiedzi powinien być 200 OK");
|
||||
assertEquals("http://payment.url", response.getBody(), "Ciało odpowiedzi powinno zawierać URL płatności");
|
||||
|
||||
System.out.println("Test pobierania tokena płatności przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania wszystkich zamówień")
|
||||
public void testGetAllOrders() {
|
||||
Long clientId = 1L;
|
||||
Order order1 = new Order();
|
||||
order1.setId(1L);
|
||||
order1.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
order1.setStatus(Enums.OrderStatus.PENDING);
|
||||
order1.setAmount(10.00);
|
||||
order1.setCreatedAt(LocalDateTime.now());
|
||||
|
||||
Order order2 = new Order();
|
||||
order2.setId(2L);
|
||||
order2.setOrderType(Enums.OrderType.BOOST);
|
||||
order2.setStatus(Enums.OrderStatus.COMPLETED);
|
||||
order2.setAmount(8.00);
|
||||
order2.setCreatedAt(LocalDateTime.now());
|
||||
|
||||
List<Order> orders = List.of(order1, order2);
|
||||
|
||||
Payment payment1 = new Payment();
|
||||
payment1.setIdPayment(1L);
|
||||
payment1.setAmount(10.00);
|
||||
payment1.setStatus(Enums.PaymentStatus.PENDING);
|
||||
payment1.setTransactionPaymentUrl("http://payment.url/1");
|
||||
payment1.setTransactionId("trans1");
|
||||
|
||||
Payment payment2 = new Payment();
|
||||
payment2.setIdPayment(2L);
|
||||
payment2.setAmount(8.00);
|
||||
payment2.setStatus(Enums.PaymentStatus.CORRECT);
|
||||
payment2.setTransactionPaymentUrl("http://payment.url/2");
|
||||
payment2.setTransactionId("trans2");
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(clientId);
|
||||
when(orderService.getOrdersByClientId(clientId)).thenReturn(orders);
|
||||
when(paymentService.getPaymentsByOrderId(1L)).thenReturn(List.of(payment1));
|
||||
when(paymentService.getPaymentsByOrderId(2L)).thenReturn(List.of(payment2));
|
||||
|
||||
ResponseEntity<List<OrderWithPaymentsDTO>> response = orderController.getOrders(request);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status odpowiedzi powinien być 200 OK");
|
||||
List<OrderWithPaymentsDTO> dtoList = response.getBody();
|
||||
assertNotNull(dtoList, "Lista DTO nie powinna być null");
|
||||
assertEquals(2, dtoList.size(), "Lista DTO powinna zawierać 2 elementy");
|
||||
|
||||
OrderWithPaymentsDTO dto1 = dtoList.getFirst();
|
||||
assertEquals(1L, dto1.getOrderId(), "ID zamówienia w DTO powinno być 1");
|
||||
assertEquals("ACTIVATION", dto1.getOrderType(), "Typ zamówienia w DTO powinien być ACTIVATION");
|
||||
assertEquals("PENDING", dto1.getStatus(), "Status zamówienia w DTO powinien być PENDING");
|
||||
assertEquals(10.00, dto1.getAmount(), "Kwota zamówienia w DTO powinna być 10.00");
|
||||
assertEquals(1, dto1.getPayments().size(), "Liczba płatności w DTO powinna być 1");
|
||||
|
||||
System.out.println("Test pobierania wszystkich zamówień przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania zamówienia po ID")
|
||||
public void testGetOrderById() {
|
||||
Long clientId = 1L;
|
||||
Long orderId = 1L;
|
||||
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
order.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
order.setStatus(Enums.OrderStatus.PENDING);
|
||||
order.setAmount(10.00);
|
||||
order.setCreatedAt(LocalDateTime.now());
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(clientId);
|
||||
order.setClient(client);
|
||||
|
||||
Payment payment = new Payment();
|
||||
payment.setIdPayment(1L);
|
||||
payment.setAmount(10.00);
|
||||
payment.setStatus(Enums.PaymentStatus.PENDING);
|
||||
payment.setTransactionPaymentUrl("http://payment.url/1");
|
||||
payment.setTransactionId("trans1");
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(clientId);
|
||||
when(orderService.getOrderById(orderId)).thenReturn(order);
|
||||
when(paymentService.getPaymentsByOrderId(orderId)).thenReturn(List.of(payment));
|
||||
|
||||
ResponseEntity<OrderWithPaymentsDTO> response = orderController.getOrderById(request, orderId);
|
||||
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode(), "Status odpowiedzi powinien być 200 OK");
|
||||
OrderWithPaymentsDTO dto = response.getBody();
|
||||
assertNotNull(dto, "DTO nie powinno być null");
|
||||
assertEquals(orderId, dto.getOrderId(), "ID zamówienia w DTO powinno być równe podanemu");
|
||||
|
||||
System.out.println("Test pobierania zamówienia po ID przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania zamówienia po ID - brak uprawnień")
|
||||
public void testGetOrderByIdForbidden() {
|
||||
Long clientId = 1L;
|
||||
Long orderId = 1L;
|
||||
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
order.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
order.setStatus(Enums.OrderStatus.PENDING);
|
||||
order.setAmount(10.00);
|
||||
order.setCreatedAt(LocalDateTime.now());
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(2L);
|
||||
order.setClient(client);
|
||||
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(clientId);
|
||||
when(orderService.getOrderById(orderId)).thenReturn(order);
|
||||
|
||||
ResponseEntity<OrderWithPaymentsDTO> response = orderController.getOrderById(request, orderId);
|
||||
|
||||
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode(), "Status odpowiedzi powinien być 403 FORBIDDEN");
|
||||
|
||||
System.out.println("Test pobierania zamówienia po ID - brak uprawnień przeszedł pomyślnie.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.OrderDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Order;
|
||||
import _11.asktpk.artisanconnectbackend.repository.ClientRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.NoticeRepository;
|
||||
import _11.asktpk.artisanconnectbackend.repository.OrderRepository;
|
||||
import _11.asktpk.artisanconnectbackend.service.OrderService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Enums;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class OrderServiceTest {
|
||||
|
||||
private final OrderRepository orderRepository = Mockito.mock(OrderRepository.class);
|
||||
private final ClientRepository clientRepository = Mockito.mock(ClientRepository.class);
|
||||
private final NoticeRepository noticeRepository = Mockito.mock(NoticeRepository.class);
|
||||
private final OrderService orderService = new OrderService(orderRepository, clientRepository, noticeRepository);
|
||||
|
||||
@Test
|
||||
@DisplayName("Test dodawania zamówienia")
|
||||
public void testAddOrder() {
|
||||
OrderDTO orderDTO = new OrderDTO();
|
||||
orderDTO.setClientId(1L);
|
||||
orderDTO.setNoticeId(1L);
|
||||
orderDTO.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
|
||||
Client client = new Client();
|
||||
client.setId(1L);
|
||||
|
||||
Notice notice = new Notice();
|
||||
notice.setIdNotice(1L);
|
||||
|
||||
Order savedOrder = new Order();
|
||||
savedOrder.setId(1L);
|
||||
savedOrder.setClient(client);
|
||||
savedOrder.setNotice(notice);
|
||||
savedOrder.setOrderType(Enums.OrderType.ACTIVATION);
|
||||
savedOrder.setStatus(Enums.OrderStatus.PENDING);
|
||||
savedOrder.setAmount(10.00);
|
||||
savedOrder.setCreatedAt(LocalDateTime.now());
|
||||
savedOrder.setUpdatedAt(LocalDateTime.now());
|
||||
|
||||
when(clientRepository.findById(1L)).thenReturn(Optional.of(client));
|
||||
when(noticeRepository.findById(1L)).thenReturn(Optional.of(notice));
|
||||
when(orderRepository.save(any(Order.class))).thenReturn(savedOrder);
|
||||
|
||||
Long orderId = orderService.addOrder(orderDTO);
|
||||
|
||||
assertNotNull(orderId, "ID zamówienia nie powinno być null");
|
||||
assertEquals(1L, orderId, "ID zamówienia powinno być równe 1");
|
||||
verify(orderRepository, times(1)).save(any(Order.class));
|
||||
|
||||
System.out.println("Test dodawania zamówienia przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test zmiany statusu zamówienia")
|
||||
public void testChangeOrderStatus() {
|
||||
Long orderId = 1L;
|
||||
Enums.OrderStatus newStatus = Enums.OrderStatus.COMPLETED;
|
||||
|
||||
Order existingOrder = new Order();
|
||||
existingOrder.setId(orderId);
|
||||
existingOrder.setStatus(Enums.OrderStatus.PENDING);
|
||||
|
||||
when(orderRepository.findById(orderId)).thenReturn(Optional.of(existingOrder));
|
||||
when(orderRepository.save(any(Order.class))).thenReturn(existingOrder);
|
||||
|
||||
Long updatedOrderId = orderService.changeOrderStatus(orderId, newStatus);
|
||||
|
||||
assertNotNull(updatedOrderId, "ID zaktualizowanego zamówienia nie powinno być null");
|
||||
assertEquals(orderId, updatedOrderId, "ID zaktualizowanego zamówienia powinno być równe podanemu");
|
||||
assertEquals(newStatus, existingOrder.getStatus(), "Status zamówienia powinien zostać zaktualizowany");
|
||||
verify(orderRepository, times(1)).save(existingOrder);
|
||||
|
||||
System.out.println("Test zmiany statusu zamówienia przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania zamówienia po ID")
|
||||
public void testGetOrderById() {
|
||||
Long orderId = 1L;
|
||||
Order order = new Order();
|
||||
order.setId(orderId);
|
||||
|
||||
when(orderRepository.findById(orderId)).thenReturn(Optional.of(order));
|
||||
|
||||
Order retrievedOrder = orderService.getOrderById(orderId);
|
||||
|
||||
assertNotNull(retrievedOrder, "Pobrane zamówienie nie powinno być null");
|
||||
assertEquals(orderId, retrievedOrder.getId(), "ID pobranego zamówienia powinno być równe podanemu");
|
||||
|
||||
System.out.println("Test pobierania zamówienia po ID przeszedł pomyślnie.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Test pobierania zamówień po ID klienta")
|
||||
public void testGetOrdersByClientId() {
|
||||
Long clientId = 1L;
|
||||
List<Order> orders = List.of(new Order(), new Order());
|
||||
|
||||
when(orderRepository.findByClientId(clientId)).thenReturn(orders);
|
||||
|
||||
List<Order> retrievedOrders = orderService.getOrdersByClientId(clientId);
|
||||
|
||||
assertNotNull(retrievedOrders, "Lista zamówień nie powinna być null");
|
||||
assertEquals(2, retrievedOrders.size(), "Lista zamówień powinna zawierać 2 elementy");
|
||||
|
||||
System.out.println("Test pobierania zamówień po ID klienta przeszedł pomyślnie.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Tools;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ToolsTest {
|
||||
|
||||
@Mock
|
||||
private JwtUtil jwtUtil;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@InjectMocks
|
||||
private Tools tools;
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobieranie ID klienta z requestu - powinno zwrócić ID gdy token jest poprawny")
|
||||
void getClientIdFromRequest_shouldReturnClientIdWhenTokenValid() {
|
||||
System.out.println("Rozpoczęcie testu getClientIdFromRequest_shouldReturnClientIdWhenTokenValid");
|
||||
|
||||
String token = "valid.token.here";
|
||||
Long expectedClientId = 1L;
|
||||
|
||||
when(request.getHeader("Authorization")).thenReturn("Bearer " + token);
|
||||
when(jwtUtil.extractUserId(token)).thenReturn(expectedClientId);
|
||||
|
||||
Long result = tools.getClientIdFromRequest(request);
|
||||
|
||||
assertEquals(expectedClientId, result);
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie pobrano ID klienta z tokenu");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.controller.WishlistController;
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.dto.RequestResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.service.ClientService;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.service.WishlistService;
|
||||
import _11.asktpk.artisanconnectbackend.utils.Tools;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WishlistControllerTest {
|
||||
|
||||
@Mock
|
||||
private WishlistService wishlistService;
|
||||
|
||||
@Mock
|
||||
private ClientService clientService;
|
||||
|
||||
@Mock
|
||||
private NoticeService noticeService;
|
||||
|
||||
@Mock
|
||||
private Tools tools;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@InjectMocks
|
||||
private WishlistController wishlistController;
|
||||
|
||||
private final Long testClientId = 1L;
|
||||
private final Long testNoticeId = 1L;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("[Konfiguracja] Przygotowanie środowiska testowego...");
|
||||
when(tools.getClientIdFromRequest(request)).thenReturn(testClientId);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie/Usunięcie z wishlisty - powinno zwrócić sukces gdy ogłoszenie istnieje")
|
||||
void toggleWishlist_shouldReturnSuccessWhenNoticeExists() {
|
||||
System.out.println("Rozpoczęcie testu toggleWishlist_shouldReturnSuccessWhenNoticeExists");
|
||||
|
||||
NoticeResponseDTO noticeResponse = new NoticeResponseDTO();
|
||||
noticeResponse.setNoticeId(testNoticeId);
|
||||
|
||||
when(noticeService.getNoticeById(testNoticeId)).thenReturn(noticeResponse);
|
||||
when(clientService.getClientById(testClientId)).thenReturn(new Client());
|
||||
when(noticeService.getNoticeByIdEntity(testNoticeId)).thenReturn(new Notice());
|
||||
when(wishlistService.toggleWishlist(any(), any())).thenReturn(true);
|
||||
|
||||
ResponseEntity<RequestResponseDTO> response = wishlistController.toggleWishlist(testNoticeId, request);
|
||||
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
assertNotNull(response.getBody());
|
||||
assertEquals("Wishlist entry added", response.getBody().getMessage());
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie obsłużono dodanie/usunięcie z wishlisty");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Dodanie/Usunięcie z wishlisty - powinno zwrócić błąd gdy ogłoszenie nie istnieje")
|
||||
void toggleWishlist_shouldReturnBadRequestWhenNoticeNotFound() {
|
||||
System.out.println("Rozpoczęcie testu toggleWishlist_shouldReturnBadRequestWhenNoticeNotFound");
|
||||
|
||||
when(noticeService.getNoticeById(testNoticeId)).thenReturn(null);
|
||||
|
||||
ResponseEntity<RequestResponseDTO> response = wishlistController.toggleWishlist(testNoticeId, request);
|
||||
|
||||
assertEquals(400, response.getStatusCode().value());
|
||||
assertNotNull(response.getBody());
|
||||
assertEquals("Notice not found", response.getBody().getMessage());
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie obsłużono brak ogłoszenia");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobieranie wishlisty - powinno zwrócić listę ogłoszeń")
|
||||
void getWishlistForClient_shouldReturnNoticeList() {
|
||||
System.out.println("Rozpoczęcie testu getWishlistForClient_shouldReturnNoticeList");
|
||||
|
||||
NoticeResponseDTO noticeResponse = new NoticeResponseDTO();
|
||||
noticeResponse.setNoticeId(testNoticeId);
|
||||
|
||||
when(wishlistService.getNoticesInWishlist(testClientId)).thenReturn(Collections.singletonList(noticeResponse));
|
||||
|
||||
List<NoticeResponseDTO> result = wishlistController.getWishlistForClient(request);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(testNoticeId, result.getFirst().getNoticeId());
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie pobrano listę ogłoszeń");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobieranie wishlisty - powinno zwrócić pustą listę gdy brak wpisów")
|
||||
void getWishlistForClient_shouldReturnEmptyListWhenNoEntries() {
|
||||
System.out.println("Rozpoczęcie testu getWishlistForClient_shouldReturnEmptyListWhenNoEntries");
|
||||
|
||||
when(wishlistService.getNoticesInWishlist(testClientId)).thenReturn(Collections.emptyList());
|
||||
|
||||
List<NoticeResponseDTO> result = wishlistController.getWishlistForClient(request);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie zwrócono pustą wishlistę");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package _11.asktpk.artisanconnectbackend;
|
||||
|
||||
import _11.asktpk.artisanconnectbackend.dto.NoticeResponseDTO;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Client;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Notice;
|
||||
import _11.asktpk.artisanconnectbackend.entities.Wishlist;
|
||||
import _11.asktpk.artisanconnectbackend.repository.WishlistRepository;
|
||||
import _11.asktpk.artisanconnectbackend.service.NoticeService;
|
||||
import _11.asktpk.artisanconnectbackend.service.WishlistService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WishlistServiceTest {
|
||||
|
||||
@Mock
|
||||
private WishlistRepository wishlistRepository;
|
||||
|
||||
@Mock
|
||||
private NoticeService noticeService;
|
||||
|
||||
@InjectMocks
|
||||
private WishlistService wishlistService;
|
||||
|
||||
private Client testClient;
|
||||
private Notice testNotice;
|
||||
private Wishlist testWishlist;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
System.out.println("Przygotowanie danych testowych...");
|
||||
|
||||
testClient = new Client();
|
||||
testClient.setId(1L);
|
||||
testClient.setEmail("test@example.com");
|
||||
|
||||
testNotice = new Notice();
|
||||
testNotice.setIdNotice(1L);
|
||||
testNotice.setTitle("Test Notice");
|
||||
|
||||
testWishlist = new Wishlist();
|
||||
testWishlist.setId(1L);
|
||||
testWishlist.setClient(testClient);
|
||||
testWishlist.setNotice(testNotice);
|
||||
|
||||
System.out.println("[Konfiguracja] Dane testowe gotowe");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Przełączanie wishlisty - powinno dodać gdy wpis nie istnieje")
|
||||
void toggleWishlist_shouldAddWhenNotExists() {
|
||||
System.out.println("Rozpoczęcie testu toggleWishlist_shouldAddWhenNotExists");
|
||||
|
||||
when(wishlistRepository.findByClientAndNotice(testClient, testNotice)).thenReturn(Optional.empty());
|
||||
when(wishlistRepository.save(any(Wishlist.class))).thenReturn(testWishlist);
|
||||
|
||||
boolean result = wishlistService.toggleWishlist(testClient, testNotice);
|
||||
|
||||
assertTrue(result);
|
||||
verify(wishlistRepository, times(1)).save(any(Wishlist.class));
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie dodano do wishlisty");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Przełączanie wishlisty - powinno usunąć gdy wpis istnieje")
|
||||
void toggleWishlist_shouldRemoveWhenExists() {
|
||||
System.out.println("Rozpoczęcie testu toggleWishlist_shouldRemoveWhenExists");
|
||||
|
||||
when(wishlistRepository.findByClientAndNotice(testClient, testNotice)).thenReturn(Optional.of(testWishlist));
|
||||
|
||||
boolean result = wishlistService.toggleWishlist(testClient, testNotice);
|
||||
|
||||
assertFalse(result);
|
||||
verify(wishlistRepository, times(1)).delete(testWishlist);
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie usunięto z wishlisty");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobieranie ogłoszeń z wishlisty - powinno zwrócić listę ogłoszeń")
|
||||
void getNoticesInWishlist_shouldReturnNoticeList() {
|
||||
System.out.println("Rozpoczęcie testu getNoticesInWishlist_shouldReturnNoticeList");
|
||||
|
||||
List<Wishlist> wishlistEntries = new ArrayList<>();
|
||||
wishlistEntries.add(testWishlist);
|
||||
|
||||
when(wishlistRepository.findAllByClientId(1L)).thenReturn(wishlistEntries);
|
||||
when(noticeService.getNoticeById(1L)).thenReturn(new NoticeResponseDTO());
|
||||
|
||||
List<NoticeResponseDTO> result = wishlistService.getNoticesInWishlist(1L);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
|
||||
System.out.println(" Test zakończony powodzeniem: Poprawnie zwrócono listę ogłoszeń");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Pobieranie ogłoszeń z wishlisty - powinno zwrócić pustą listę gdy brak wpisów")
|
||||
void getNoticesInWishlist_shouldReturnEmptyListWhenNoEntries() {
|
||||
System.out.println("Rozpoczęcie testu getNoticesInWishlist_shouldReturnEmptyListWhenNoEntries");
|
||||
|
||||
when(wishlistRepository.findAllByClientId(1L)).thenReturn(new ArrayList<>());
|
||||
|
||||
List<NoticeResponseDTO> result = wishlistService.getNoticesInWishlist(1L);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
|
||||
System.out.println("Test zakończony powodzeniem: Poprawnie zwrócono pustą listę");
|
||||
}
|
||||
}
|
||||
BIN
src/test/resources/test.jpeg
Normal file
BIN
src/test/resources/test.jpeg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
BIN
src/test/resources/test.jpg
Normal file
BIN
src/test/resources/test.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
BIN
src/test/resources/test.png
Normal file
BIN
src/test/resources/test.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 435 KiB |
Reference in New Issue
Block a user