7 Commits

Author SHA1 Message Date
86e902bbfe few small fixes 2025-06-13 17:51:35 +02:00
d9a8ffe4bd Merge branch 'environment-vars' 2025-06-11 23:34:32 +02:00
c59998c113 fix nested file 2025-06-11 23:31:19 +02:00
ff5dc5c090 Warnings fixed, logs added to tests 2025-06-11 23:00:12 +02:00
4d7a191e8a Added logs to ClientServiceTest 2025-06-11 22:30:50 +02:00
a7c8f22658 isMainImage pobierane z Frontend 2025-06-11 19:05:16 +02:00
f31885c795 implementacja zmiennych środowiskowych 2025-06-11 18:21:26 +02:00
12 changed files with 183 additions and 241 deletions

View File

@@ -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()));
}
}

View File

@@ -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;
}

View File

@@ -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);
}

View File

@@ -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.sendgrid.net
spring.mail.port=587
spring.mail.username=apikey
spring.mail.password=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
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

View File

@@ -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

View File

@@ -29,6 +29,8 @@ public class ClientServiceTest {
@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");
@@ -43,17 +45,20 @@ public class ClientServiceTest {
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 przeszedł pomyślnie.");
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() {
// Przygotowanie danych
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");
@@ -63,29 +68,35 @@ public class ClientServiceTest {
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 (klient istnieje) przeszedł pomyślnie.");
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 klienta po ID (klient nie istnieje) przeszedł pomyślnie.");
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);
@@ -93,16 +104,18 @@ public class ClientServiceTest {
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 przeszedł pomyślnie.");
System.out.println("Test pobierania klienta po emailu (" + email + ") zakończony sukcesem.");
}
@Test
@DisplayName("Test dodawania klienta")
public void testAddClient() {
// Przygotowanie danych
System.out.println("Rozpoczęcie testu: testAddClient - Test dodawania nowego klienta");
ClientDTO clientDTO = new ClientDTO();
clientDTO.setEmail("newclient@example.com");
clientDTO.setRole("USER");
@@ -115,16 +128,19 @@ public class ClientServiceTest {
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 przeszedł pomyślnie.");
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");
@@ -142,41 +158,49 @@ public class ClientServiceTest {
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 przeszedł pomyślnie.");
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 klienta (klient nie istnieje) przeszedł pomyślnie.");
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 przeszedł pomyślnie.");
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");
@@ -187,8 +211,24 @@ public class ClientServiceTest {
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");
@@ -196,7 +236,6 @@ public class ClientServiceTest {
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 przeszedł pomyślnie.");
System.out.println("Test konwersji encji do DTO zakończony sukcesem. Wszystkie pola zostały poprawnie zmapowane.");
}
}

View File

@@ -1,76 +0,0 @@
package _11.asktpk.artisanconnectbackend;
import _11.asktpk.artisanconnectbackend.security.JwtUtil;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@SpringBootTest
@AutoConfigureMockMvc
class EmailControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private JwtUtil jwtUtil;
@Test
@DisplayName("Wysyłanie Maila z waznym tokenem")
void testSendEmailWithValidAuthToken() throws Exception {
System.out.println("Startowanie testSendEmailWithValidAuthToken");
String jsonPayload = """
{
"to": "test@example.com",
"subject": "Test Subject",
"body": "Test Body"
}
""";
System.out.println("Wysyłanie JSON payload: " + jsonPayload);
String jwtToken = "Bearer " + jwtUtil.generateToken("test@example.com", "USER", 1L);
MvcResult result = mockMvc.perform(post("/api/v1/email/send")
.header("Authorization", jwtToken)
.contentType(MediaType.APPLICATION_JSON)
.content(jsonPayload))
.andExpect(status().isOk())
.andExpect(content().string("Email wysłany pomyślnie"))
.andReturn();
System.out.println("Status odpowiedzi: " + result.getResponse().getStatus());
System.out.println("Treść odpowiedzi: " + result.getResponse().getContentAsString());
}
@Test
@DisplayName("Wysyłanie Maila bez tokena")
void testSendEmailWithoutAuthToken() throws Exception {
System.out.println("Startowanie testSendEmailWithoutAuthToken");
String jsonPayload = """
{
"to": "test@example.com",
"subject": "Test Subject",
"body": "Test Body"
}
""";
System.out.println("Wysyłanie JSON payload: " + jsonPayload);
MvcResult result = mockMvc.perform(post("/api/v1/email/send")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonPayload))
.andExpect(status().isForbidden())
.andReturn();
System.out.println("Status odpowiedzi: " + result.getResponse().getStatus());
System.out.println("Treść odpowiedzi: " + result.getResponse().getContentAsString());
}
}

View File

@@ -8,6 +8,7 @@ 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;
@@ -28,13 +29,13 @@ import static org.mockito.Mockito.*;
class NoticeControllerTest {
@Mock
private final NoticeService noticeService = mock(NoticeService.class);
private NoticeService noticeService;
@Mock
private final ClientService clientService = mock(ClientService.class);
private ClientService clientService;
@Mock
private final Tools tools = mock(Tools.class);
private Tools tools;
@Mock
private HttpServletRequest request;
@@ -47,7 +48,7 @@ class NoticeControllerTest {
@BeforeEach
void setUp() {
System.out.println("Inicjalizacja danych testowych przed każdym testem");
System.out.println("Inicjalizacja danych testowych...");
sampleNotice = new NoticeResponseDTO();
sampleNotice.setNoticeId(1L);
@@ -69,53 +70,43 @@ class NoticeControllerTest {
}
@Test
@DisplayName("Pobranie wszystkich ogłoszeń")
void getAllNotices_ShouldReturnListOfNotices() {
System.out.println("Test: getAllNotices_ShouldReturnListOfNotices - powinien zwrócić listę ogłoszeń");
when(noticeService.getAllNotices()).thenReturn(List.of(sampleNotice));
List<NoticeResponseDTO> result = noticeController.getAllNotices();
assertNotNull(result);
assertEquals(1, result.size());
assertEquals(sampleNotice.getNoticeId(), result.getFirst().getNoticeId());
System.out.println("Pomyślnie zwrócono listę ogłoszeń");
System.out.println("Test GET /notices zakończony sukcesem");
}
@Test
@DisplayName("Pobranie istniejącego ogłoszenia")
void getNoticeById_WhenNoticeExists_ShouldReturnNotice() {
System.out.println("Test: getNoticeById_WhenNoticeExists_ShouldReturnNotice - powinien zwrócić ogłoszenie gdy istnieje");
when(noticeService.noticeExists(1L)).thenReturn(true);
when(noticeService.getNoticeById(1L)).thenReturn(sampleNotice);
ResponseEntity<?> response = noticeController.getNoticeById(1L);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
assertEquals(sampleNotice, response.getBody());
System.out.println("Pomyślnie zwrócono istniejące ogłoszenie");
System.out.println("Test GET /notices/{id} (istniejące) zakończony sukcesem");
}
@Test
@DisplayName("Pobranie nieistniejącego ogłoszenia")
void getNoticeById_WhenNoticeNotExists_ShouldReturnNotFound() {
System.out.println("Test: getNoticeById_WhenNoticeNotExists_ShouldReturnNotFound - powinien zwrócić 404 gdy ogłoszenie nie istnieje");
when(noticeService.noticeExists(1L)).thenReturn(false);
ResponseEntity<?> response = noticeController.getNoticeById(1L);
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
System.out.println("Pomyślnie zwrócono status 404 dla nieistniejącego ogłoszenia");
System.out.println("Test GET /notices/{id} (nieistniejące) zakończony sukcesem");
}
@Test
@DisplayName("Dodanie poprawnego ogłoszenia")
void addNotice_WithValidData_ShouldCreateNotice() {
System.out.println("Test: addNotice_WithValidData_ShouldCreateNotice - powinien utworzyć nowe ogłoszenie przy poprawnych danych");
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
when(clientService.clientExists(1L)).thenReturn(true);
when(noticeService.addNotice(any(NoticeRequestDTO.class))).thenReturn(1L);
@@ -123,17 +114,12 @@ class NoticeControllerTest {
ResponseEntity<NoticeAdditionDTO> response = noticeController.addNotice(sampleNoticeRequest, request);
assertEquals(HttpStatus.CREATED, response.getStatusCode());
assertNotNull(response.getBody());
assertEquals(1L, response.getBody().getNoticeId());
assertEquals("Dodano ogłoszenie.", response.getBody().getMessage());
System.out.println("Pomyślnie utworzono nowe ogłoszenie");
System.out.println("Test POST /notices (poprawne dane) zakończony sukcesem");
}
@Test
@DisplayName("Dodanie ogłoszenia z błędną kategorią")
void addNotice_WithInvalidCategory_ShouldReturnBadRequest() {
System.out.println("Test: addNotice_WithInvalidCategory_ShouldReturnBadRequest - powinien zwrócić błąd dla nieprawidłowej kategorii");
sampleNoticeRequest.setCategory(null);
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
@@ -142,32 +128,24 @@ class NoticeControllerTest {
ResponseEntity<NoticeAdditionDTO> response = noticeController.addNotice(sampleNoticeRequest, request);
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
assertNotNull(response.getBody());
assertEquals("Nie ma takiej kategorii", response.getBody().getMessage());
System.out.println("Pomyślnie zwrócono błąd dla nieprawidłowej kategorii");
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() {
System.out.println("Test: addNotice_WhenClientNotExists_ShouldReturnBadRequest - powinien zwrócić błąd gdy klient nie istnieje");
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());
assertNotNull(response.getBody());
assertTrue(response.getBody().getMessage().contains("Nie znaleziono klienta o ID:"));
System.out.println("Pomyślnie zwrócono błąd dla nieistniejącego klienta");
System.out.println("Test POST /notices (nieistniejący klient) zakończony sukcesem");
}
@Test
@DisplayName("Aktualizacja własnego ogłoszenia")
void editNotice_WhenNoticeExistsAndOwnedByClient_ShouldUpdateNotice() {
System.out.println("Test: editNotice_WhenNoticeExistsAndOwnedByClient_ShouldUpdateNotice - powinien zaktualizować ogłoszenie gdy istnieje i należy do klienta");
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
when(noticeService.noticeExists(1L)).thenReturn(true);
when(noticeService.isNoticeOwnedByClient(1L, 1L)).thenReturn(true);
@@ -176,16 +154,12 @@ class NoticeControllerTest {
ResponseEntity<Object> response = noticeController.editNotice(1L, sampleNoticeRequest, request);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
assertEquals(sampleNotice, response.getBody());
System.out.println("Pomyślnie zaktualizowano ogłoszenie należące do klienta");
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() {
System.out.println("Test: editNotice_WhenNoticeNotOwnedByClient_ShouldReturnForbidden - powinien zwrócić błąd 403 gdy ogłoszenie nie należy do klienta");
when(tools.getClientIdFromRequest(request)).thenReturn(2L);
when(noticeService.noticeExists(1L)).thenReturn(true);
when(noticeService.isNoticeOwnedByClient(1L, 2L)).thenReturn(false);
@@ -193,16 +167,12 @@ class NoticeControllerTest {
ResponseEntity<Object> response = noticeController.editNotice(1L, sampleNoticeRequest, request);
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
assertNotNull(response.getBody());
assertTrue(((RequestResponseDTO) response.getBody()).getMessage().contains("Nie masz uprawnień"));
System.out.println("Pomyślnie zwrócono błąd 403 dla próby edycji nie swojego ogłoszenia");
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() {
System.out.println("Test: deleteNotice_WhenNoticeExistsAndOwnedByClient_ShouldDeleteNotice - powinien usunąć ogłoszenie gdy istnieje i należy do klienta");
when(tools.getClientIdFromRequest(request)).thenReturn(1L);
when(noticeService.noticeExists(1L)).thenReturn(true);
when(noticeService.isNoticeOwnedByClient(1L, 1L)).thenReturn(true);
@@ -210,12 +180,7 @@ class NoticeControllerTest {
ResponseEntity<RequestResponseDTO> response = noticeController.deleteNotice(1L, request);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
assertTrue(response.getBody().getMessage().contains("Pomyślnie usunięto"));
verify(noticeService, times(1)).deleteNotice(1L);
System.out.println("Pomyślnie usunięto ogłoszenie należące do klienta");
System.out.println("Test DELETE /notices/{id} (własne ogłoszenie) zakończony sukcesem");
}
}

View File

@@ -5,11 +5,11 @@ 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.ImageService;
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;
@@ -28,20 +28,19 @@ import static org.mockito.Mockito.*;
class NoticeServiceTest {
@Mock
private final NoticeRepository noticeRepository = mock(NoticeRepository.class);
private NoticeRepository noticeRepository;
@Mock
private final ClientRepository clientRepository = mock(ClientRepository.class);
private ClientRepository clientRepository;
@Mock
private final AttributesRepository attributesRepository = mock(AttributesRepository.class);
private AttributesRepository attributesRepository;
@Mock
private final AttributeValuesRepository attributeValuesRepository = mock(AttributeValuesRepository.class);
private AttributeValuesRepository attributeValuesRepository;
@Mock
private final AttributesNoticeRepository attributesNoticeRepository = mock(AttributesNoticeRepository.class);
private AttributesNoticeRepository attributesNoticeRepository;
@InjectMocks
private NoticeService noticeService;
@@ -52,7 +51,7 @@ class NoticeServiceTest {
@BeforeEach
void setUp() {
System.out.println("Inicjalizacja danych testowych przed każdym testem");
System.out.println("Przygotowanie danych testowych...");
sampleClient = new Client();
sampleClient.setId(1L);
@@ -78,69 +77,55 @@ class NoticeServiceTest {
}
@Test
@DisplayName("Pobranie wszystkich ogłoszeń - powinno zwrócić listę ogłoszeń")
void getAllNotices_ShouldReturnListOfNotices() {
System.out.println("Test: getAllNotices_ShouldReturnListOfNotices - powinien zwrócić listę ogłoszeń");
when(noticeRepository.findAll()).thenReturn(List.of(sampleNotice));
List<NoticeResponseDTO> result = noticeService.getAllNotices();
assertNotNull(result);
assertEquals(1, result.size());
assertEquals(sampleNotice.getIdNotice(), result.getFirst().getNoticeId());
System.out.println("Pomyślnie zwrócono listę ogłoszeń");
System.out.println("Test pobrania wszystkich ogłoszeń zakończony");
}
@Test
@DisplayName("Pobranie ogłoszenia po ID - gdy istnieje")
void getNoticeById_WhenNoticeExists_ShouldReturnNotice() {
System.out.println("Test: getNoticeById_WhenNoticeExists_ShouldReturnNotice - powinien zwrócić ogłoszenie gdy istnieje");
when(noticeRepository.findById(1L)).thenReturn(Optional.of(sampleNotice));
NoticeResponseDTO result = noticeService.getNoticeById(1L);
assertNotNull(result);
assertEquals(sampleNotice.getIdNotice(), result.getNoticeId());
System.out.println("Pomyślnie zwrócono istniejące ogłoszenie");
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() {
System.out.println("Test: getNoticeById_WhenNoticeNotExists_ShouldThrowException - powinien rzucić wyjątek gdy ogłoszenie nie istnieje");
when(noticeRepository.findById(1L)).thenReturn(Optional.empty());
assertThrows(EntityNotFoundException.class, () -> noticeService.getNoticeById(1L));
System.out.println("Pomyślnie rzucono wyjątek dla nieistniejącego ogłoszenia");
System.out.println("Test pobrania nieistniejącego ogłoszenia zakończony");
}
@Test
@DisplayName("Dodanie nowego ogłoszenia - poprawne dane")
void addNotice_WithValidData_ShouldCreateNotice() {
System.out.println("Test: addNotice_WithValidData_ShouldCreateNotice - powinien utworzyć nowe ogłoszenie przy poprawnych danych");
when(clientRepository.findById(1L)).thenReturn(Optional.of(sampleClient));
when(noticeRepository.save(any(Notice.class))).thenReturn(sampleNotice);
Long result = noticeService.addNotice(sampleNoticeRequest);
assertNotNull(result);
assertEquals(1L, result);
verify(noticeRepository, times(1)).save(any(Notice.class));
System.out.println("Pomyślnie utworzono nowe ogłoszenie");
System.out.println("Test dodania ogłoszenia zakończony");
}
@Test
@DisplayName("Dodanie ogłoszenia z atrybutami")
void addNotice_WithAttributes_ShouldSaveAttributes() {
System.out.println("Test: addNotice_WithAttributes_ShouldSaveAttributes - powinien zapisać atrybuty ogłoszenia");
AttributeDto attributeDto = new AttributeDto();
attributeDto.setName("Materiał");
attributeDto.setValue("Drewno");
attributeDto.setName("Kolor");
attributeDto.setValue("Zielony");
sampleNoticeRequest.setAttributes(List.of(attributeDto));
when(clientRepository.findById(1L)).thenReturn(Optional.of(sampleClient));
@@ -151,50 +136,39 @@ class NoticeServiceTest {
Long result = noticeService.addNotice(sampleNoticeRequest);
assertNotNull(result);
verify(attributesNoticeRepository, times(1)).save(any(AttributesNotice.class));
System.out.println("Pomyślnie zapisano atrybuty ogłoszenia");
System.out.println("Test dodania ogłoszenia z atrybutami zakończony");
}
@Test
@DisplayName("Usunięcie istniejącego ogłoszenia")
void deleteNotice_WhenNoticeExists_ShouldDeleteNotice() {
System.out.println("Test: deleteNotice_WhenNoticeExists_ShouldDeleteNotice - powinien usunąć istniejące ogłoszenie");
when(noticeRepository.existsById(1L)).thenReturn(true);
noticeService.deleteNotice(1L);
verify(noticeRepository, times(1)).deleteById(1L);
System.out.println("Pomyślnie usunięto istniejące ogłoszenie");
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() {
System.out.println("Test: isNoticeOwnedByClient_WhenOwned_ShouldReturnTrue - powinien zwrócić true gdy ogłoszenie należy do klienta");
when(noticeRepository.existsByIdNoticeAndClientId(1L, 1L)).thenReturn(true);
boolean result = noticeService.isNoticeOwnedByClient(1L, 1L);
assertTrue(result);
System.out.println("Pomyślnie zwrócono true dla ogłoszenia należącego do klienta");
System.out.println("Test sprawdzenia właściciela (true) zakończony");
}
@Test
@DisplayName("Boostowanie ogłoszenia - aktualizacja daty publikacji")
void boostNotice_ShouldUpdatePublishDate() {
System.out.println("Test: boostNotice_ShouldUpdatePublishDate - powinien zaktualizować datę publikacji");
when(noticeRepository.findById(1L)).thenReturn(Optional.of(sampleNotice));
when(noticeRepository.save(any(Notice.class))).thenReturn(sampleNotice);
noticeService.boostNotice(1L);
assertNotNull(sampleNotice.getPublishDate());
verify(noticeRepository, times(1)).save(sampleNotice);
System.out.println("Pomyślnie zaktualizowano datę publikacji ogłoszenia");
System.out.println("Test boostowania ogłoszenia zakończony");
}
}

View File

@@ -4,6 +4,7 @@ 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;
@@ -25,7 +26,10 @@ class ToolsTest {
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;
@@ -35,6 +39,7 @@ class ToolsTest {
Long result = tools.getClientIdFromRequest(request);
assertEquals(expectedClientId, result);
}
System.out.println("Test zakończony powodzeniem: Poprawnie pobrano ID klienta z tokenu");
}
}

View File

@@ -11,6 +11,7 @@ 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;
@@ -50,11 +51,15 @@ class WishlistControllerTest {
@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);
@@ -65,24 +70,34 @@ class WishlistControllerTest {
ResponseEntity<RequestResponseDTO> response = wishlistController.toggleWishlist(testNoticeId, request);
assertEquals(200, response.getStatusCodeValue());
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.getStatusCodeValue());
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);
@@ -93,15 +108,22 @@ class WishlistControllerTest {
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ę");
}
}

View File

@@ -8,6 +8,7 @@ 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;
@@ -40,6 +41,8 @@ class WishlistServiceTest {
@BeforeEach
void setUp() {
System.out.println("Przygotowanie danych testowych...");
testClient = new Client();
testClient.setId(1L);
testClient.setEmail("test@example.com");
@@ -52,10 +55,15 @@ class WishlistServiceTest {
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);
@@ -63,20 +71,30 @@ class WishlistServiceTest {
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);
@@ -87,15 +105,22 @@ class WishlistServiceTest {
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ę");
}
}