From 7e176d1ab1827129bf6021625fb3f72da74e93ce Mon Sep 17 00:00:00 2001 From: jaimeeg5 Date: Sun, 15 Nov 2026 11:40:42 +0100 Subject: [PATCH 1/2] fix: return 400 instead of 500 for bad requests --- .../pcmod/service/ComponentsService.java | 4 +-- .../pcmod/service/ImageService.java | 6 ++-- .../pcmod/service/ReviewsService.java | 6 ++-- .../pcmod/service/UsersService.java | 4 +-- .../pcmod/e2e/api/ComponentsSystemTests.java | 28 ++++++++-------- .../pcmod/e2e/api/ReviewsSystemTests.java | 18 +++++------ .../pcmod/e2e/api/UsersSystemTests.java | 32 +++++++++---------- .../ComponentsIntegrationTests.java | 18 +++++------ .../integration/ReviewsIntegrationTests.java | 18 +++++------ .../integration/UsersIntegrationTests.java | 18 +++++------ .../pcmod/unit/ComponentsUnitTests.java | 18 +++++------ .../pcmod/unit/ImagesUnitTests.java | 14 ++++---- .../pcmod/unit/ReviewsUnitTests.java | 17 +++++----- .../pcmod/unit/UsersUnitTests.java | 21 ++++++------ 14 files changed, 111 insertions(+), 111 deletions(-) diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java index 107301b..fe6daaa 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java @@ -67,7 +67,7 @@ public Component save(Component component) { List errors = validateComponent(component, null); if (!errors.isEmpty()) { - throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors)); + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors)); } return componentRepository.save(component); @@ -112,7 +112,7 @@ public Component updateComponent(Component newComponentData, long id) { List errors = validateComponent(newComponentData, id); if (!errors.isEmpty()) { - throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors)); + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors)); } Component component = componentRepository.findById(id).orElseThrow(); diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ImageService.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ImageService.java index 80059f0..82ca97d 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ImageService.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ImageService.java @@ -6,8 +6,10 @@ import javax.sql.rowset.serial.SerialBlob; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.server.ResponseStatusException; import es.codeurjcstudents.pcmod.model.Image; import es.codeurjcstudents.pcmod.repository.ImageRepository; @@ -69,12 +71,12 @@ public Image deleteImage(long id) { public void validate(MultipartFile imageField) { if (imageField.getSize() > MAX_SIZE) { - throw new IllegalArgumentException("El tamaño de la imagen no puede superar los 10MB."); + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "El tamaño de la imagen no puede superar los 10MB."); } String contentType = imageField.getContentType(); if (contentType == null || !ALLOWED_TYPES.contains(contentType)) { - throw new IllegalArgumentException( + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "El tipo de archivo no es válido. Solo se permiten imágenes JPEG, PNG y WebP."); } diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java index b9f5d3c..48d106e 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java @@ -64,13 +64,13 @@ public Page findAllByComponent(long id, Pageable pageable) { public Review save(Review review, long userId, long componentId) { if (reviewRepository.existsByComponentIdAndUserId(componentId, userId)) { - throw new IllegalArgumentException("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario."); + throw new ResponseStatusException(HttpStatus.CONFLICT, "Validación fallida:\n• Ya existe una reseña de este producto para tu usuario."); } List errors = validateReview(review); if (!errors.isEmpty()) { - throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors)); + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors)); } User user = userRepository.findById(userId) @@ -115,7 +115,7 @@ public Review updateReview(Review newReviewData, long componentId, long reviewId List errors = validateReview(newReviewData); if (!errors.isEmpty()) { - throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors)); + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors)); } Review review = reviewRepository.findById(reviewId).orElseThrow(); diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/UsersService.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/UsersService.java index a9c8b1f..62daf40 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/UsersService.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/UsersService.java @@ -67,7 +67,7 @@ public User register(User user, String rawPassword) { List errors = validateUser(user, rawPassword, null); if (!errors.isEmpty()) { - throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors)); + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors)); } User userToSave = new User(user.getName(), user.getSurname(), user.getUsername(), user.getAddress(), @@ -114,7 +114,7 @@ public User updateUser(User newUserData, String rawPassword, long id) { List errors = validateUser(newUserData, rawPassword, id); if (!errors.isEmpty()) { - throw new IllegalArgumentException("Validación fallida:\n• " + String.join("\n• ", errors)); + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Validación fallida:\n• " + String.join("\n• ", errors)); } User user = userRepository.findById(id).orElseThrow(); diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java index 7bdbf97..e4d76f9 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java @@ -231,7 +231,7 @@ public void postVoidComponentData() { } """) .when().post("/components/") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(400).contentType(ContentType.JSON) .body("message", equalTo( "Validación fallida:\n• El nombre del componente es obligatorio.\n• La descripción es obligatoria.\n• La marca es obligatoria.")); } @@ -264,7 +264,7 @@ public void postNullComponentData() { } """) .when().post("/components/") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(400).contentType(ContentType.JSON) .body("message", equalTo( "Validación fallida:\n• El nombre del componente es obligatorio.\n• La descripción es obligatoria.\n• La marca es obligatoria.")); } @@ -297,8 +297,8 @@ public void postExistingComponentData() { } """) .when().post("/components/") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo("Validación fallida:\n• Ya existe un componente con ese nombre.")); } @@ -330,8 +330,8 @@ public void postBadNumComponentData() { } """) .when().post("/components/") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo( "Validación fallida:\n• El precio del producto ha de ser mayor de 0.00 €.\n• El stock del producto ha de ser 0 o mayor.")); } @@ -457,8 +457,8 @@ public void postComponentImageWithInvalidFile() { .cookie("AuthToken", authToken) .multiPart("imageFile", "test.txt", invalidTypeImage, "text/plain") .when().post("components/2/image") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo("El tipo de archivo no es válido. Solo se permiten imágenes JPEG, PNG y WebP.")); } @@ -634,7 +634,7 @@ public void putVoidComponent() { } """) .when().put("components/5") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(400).contentType(ContentType.JSON) .body("message", equalTo( "Validación fallida:\n• El nombre del componente es obligatorio.\n• La descripción es obligatoria.\n• La marca es obligatoria.\n• El precio es obligatorio.\n• El stock es obligatorio.")); } @@ -667,7 +667,7 @@ public void putNullComponent() { } """) .when().put("components/5") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(400).contentType(ContentType.JSON) .body("message", equalTo( "Validación fallida:\n• El nombre del componente es obligatorio.\n• La descripción es obligatoria.\n• La marca es obligatoria.\n• El precio es obligatorio.\n• El stock es obligatorio.")); } @@ -700,8 +700,8 @@ public void putExistingComponent() { } """) .when().put("components/5") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo("Validación fallida:\n• Ya existe un componente con ese nombre.")); } @@ -733,8 +733,8 @@ public void putBadFormatComponent() { } """) .when().put("components/5") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo( "Validación fallida:\n• El precio del producto ha de ser mayor de 0.00 €.\n• El stock del producto ha de ser 0 o mayor.")); } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java index d676807..d38f307 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java @@ -163,7 +163,7 @@ public void postReviewForAnExistingOwnReviewComponent() { } """) .when().post("/components/4/reviews/") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(409).contentType(ContentType.JSON) .body("message", equalTo("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.")); } @@ -192,7 +192,7 @@ public void postVoidReviewData() { } """) .when().post("/components/5/reviews/") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(400).contentType(ContentType.JSON) .body("message", equalTo( "Validación fallida:\n• El título es obligatorio.\n• El mensaje es obligatorio.\n• La valoración es obligatoria.")); } @@ -222,7 +222,7 @@ public void postNullComponentData() { } """) .when().post("/components/5/reviews/") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(400).contentType(ContentType.JSON) .body("message", equalTo( "Validación fallida:\n• El título es obligatorio.\n• El mensaje es obligatorio.\n• La valoración es obligatoria.")); } @@ -252,8 +252,8 @@ public void postBadNumReviewData() { } """) .when().post("/components/5/reviews/") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo( "Validación fallida:\n• La valoración del producto ha de estar entre 1 y 5.")); } @@ -587,7 +587,7 @@ public void putVoidReviewData() { } """) .when().put("/components/2/reviews/1") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(400).contentType(ContentType.JSON) .body("message", equalTo( "Validación fallida:\n• El título es obligatorio.\n• El mensaje es obligatorio.\n• La valoración es obligatoria.")); } @@ -617,7 +617,7 @@ public void putNullComponentData() { } """) .when().put("/components/2/reviews/1") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(400).contentType(ContentType.JSON) .body("message", equalTo( "Validación fallida:\n• El título es obligatorio.\n• El mensaje es obligatorio.\n• La valoración es obligatoria.")); } @@ -647,8 +647,8 @@ public void putBadNumReviewData() { } """) .when().put("/components/2/reviews/1") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo( "Validación fallida:\n• La valoración del producto ha de estar entre 1 y 5.")); } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/UsersSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/UsersSystemTests.java index b20eec2..91553d4 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/UsersSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/UsersSystemTests.java @@ -260,8 +260,8 @@ public void registerVoidCredentials() { } """) .when().post("auth/register") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo( "Validación fallida:\n• El nombre es obligatorio.\n• El apellido es obligatorio.\n• La dirección es obligatoria.\n• El nombre de usuario es obligatorio.\n• El email es obligatorio.\n• La contraseña es obligatoria.")); } @@ -281,8 +281,8 @@ public void registerNullCredentials() { } """) .when().post("auth/register") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo( "Validación fallida:\n• El nombre es obligatorio.\n• El apellido es obligatorio.\n• La dirección es obligatoria.\n• El nombre de usuario es obligatorio.\n• El email es obligatorio.\n• La contraseña es obligatoria.")); } @@ -302,8 +302,8 @@ public void registerExistingCredentials() { } """) .when().post("auth/register") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo("Validación fallida:\n• El nombre de usuario ya existe.\n• El email ya existe.")); } @@ -322,8 +322,8 @@ public void registerBadFormatCredentials() { } """) .when().post("auth/register") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo( "Validación fallida:\n• El formato del email no es válido. Debe seguir el formato: ejemplo@dominio.com.\n• La contraseña debe tener al menos 8 caracteres, incluir una mayúscula, una minúscula, un número y un carácter especial (@$!%*?&-_).")); } @@ -448,8 +448,8 @@ public void postImageWithInvalidFile() { .cookie("AuthToken", authToken) .multiPart("imageFile", "test.txt", invalidTypeImage, "text/plain") .when().post("users/1/image") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo("El tipo de archivo no es válido. Solo se permiten imágenes JPEG, PNG y WebP.")); } @@ -849,7 +849,7 @@ public void putVoidCredentials() { } """) .when().put("users/1") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(400).contentType(ContentType.JSON) .body("message", equalTo( "Validación fallida:\n• El nombre es obligatorio.\n• El apellido es obligatorio.\n• La dirección es obligatoria.\n• El nombre de usuario es obligatorio.\n• El email es obligatorio.")); } @@ -882,7 +882,7 @@ public void putNullCredentials() { } """) .when().put("users/1") - .then().statusCode(500).contentType(ContentType.JSON) + .then().statusCode(400).contentType(ContentType.JSON) .body("message", equalTo( "Validación fallida:\n• El nombre es obligatorio.\n• El apellido es obligatorio.\n• La dirección es obligatoria.\n• El nombre de usuario es obligatorio.\n• El email es obligatorio.")); } @@ -915,8 +915,8 @@ public void putExistingCredentials() { } """) .when().put("users/1") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo("Validación fallida:\n• El nombre de usuario ya existe.\n• El email ya existe.")); } @@ -948,8 +948,8 @@ public void putBadFormatCredentials() { } """) .when().put("users/1") - .then().statusCode(500).contentType(ContentType.JSON) - .body("status", equalTo(500)) + .then().statusCode(400).contentType(ContentType.JSON) + .body("status", equalTo(400)) .body("message", equalTo( "Validación fallida:\n• El formato del email no es válido. Debe seguir el formato: ejemplo@dominio.com.\n• La contraseña debe tener al menos 8 caracteres, incluir una mayúscula, una minúscula, un número y un carácter especial (@$!%*?&-_).")); } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java index 5156dd3..c441ac1 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java @@ -207,7 +207,7 @@ void postVoidComponent() { Component newComponent = new Component("", "", ComponentType.CPU, "", BigDecimal.valueOf(100.00), 5); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> componentsService.save(newComponent)); } @@ -223,7 +223,7 @@ void postNullComponent() { Component newComponent = new Component(null, null, ComponentType.CPU, null, BigDecimal.valueOf(100.00), 5); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> componentsService.save(newComponent)); } @@ -240,7 +240,7 @@ void postExistingComponent() { Component newComponent = new Component("NVIDIA GeForce RTX 5060 WINDFORCE MAX OC", "sampleDescription", ComponentType.CPU, "sampleBrand", BigDecimal.valueOf(100.00), 5); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> componentsService.save(newComponent)); } @@ -257,7 +257,7 @@ void postBadFormatComponent() { Component newComponent = new Component("sampleName", "sampleDescription", ComponentType.CPU, "sampleBrand", BigDecimal.valueOf(-100.00), -5); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> componentsService.save(newComponent)); } @@ -419,7 +419,7 @@ void postImageWithInvalidFile() { "image", "image.txt", "text/plain", new byte[1024]); Component component = componentsRepository.findAll().get(0); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> componentsService.addComponentImage(component.getId(), invalidTypeImage)); } @@ -617,7 +617,7 @@ void updateVoidComponent() { Component updatedComponent = new Component("", "", ComponentType.CPU, "", BigDecimal.valueOf(100.00), 5); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> componentsService.updateComponent(updatedComponent, component.getId())); } @@ -634,7 +634,7 @@ void updateNullComponent() { Component updatedComponent = new Component(null, null, ComponentType.CPU, null, BigDecimal.valueOf(100.00), 5); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> componentsService.updateComponent(updatedComponent, component.getId())); } @@ -652,7 +652,7 @@ void updateExistingComponent() { Component updatedComponent = new Component("NVIDIA GeForce RTX 5060 WINDFORCE MAX OC", "sampleDescription", ComponentType.CPU, "sampleBrand", BigDecimal.valueOf(100.00), 5); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> componentsService.updateComponent(updatedComponent, component.getId())); } @@ -670,7 +670,7 @@ void updateBadFormatComponent() { Component updatedComponent = new Component("sampleName", "sampleDescription", ComponentType.CPU, "sampleBrand", BigDecimal.valueOf(-100.00), -5); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> componentsService.updateComponent(updatedComponent, component.getId())); } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java index f958844..085c65e 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java @@ -209,7 +209,7 @@ void postReviewInAComponentWithOwnReview() { null, java.util.List.of(new SimpleGrantedAuthority("ROLE_REGISTERED_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")))); Review review = new Review("sample_title", "sample_message", 5); - assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, admin.getId(), componentsRepository.findAll().getFirst().getId())); + assertThrows(ResponseStatusException.class, () -> reviewsService.save(review, admin.getId(), componentsRepository.findAll().getFirst().getId())); assertEquals(2, reviewsRepository.count()); } @@ -248,7 +248,7 @@ void saveVoidReview() { Review review = new Review("","", null); Component component = componentsRepository.findAll().getLast(); - assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); + assertThrows(ResponseStatusException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); assertEquals(2, reviewsRepository.count()); } @@ -264,7 +264,7 @@ void saveNullReview() { Review review = new Review(null,null, null); Component component = componentsRepository.findAll().getLast(); - assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); + assertThrows(ResponseStatusException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); assertEquals(2, reviewsRepository.count()); } @@ -280,7 +280,7 @@ void saveBadFormatReview() { Review review = new Review("sample_title", "sample_message", -5); Component component = componentsRepository.findAll().getLast(); - assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); + assertThrows(ResponseStatusException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); assertEquals(2, reviewsRepository.count()); } @@ -313,8 +313,8 @@ void validateReviewInAComponentWithOwnReview() { Review review = new Review("sample_title","sample_message", 5); Component component = componentsRepository.findAll().getFirst(); - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); - assertEquals("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.", exception.getMessage()); + ResponseStatusException exception = assertThrows(ResponseStatusException.class, () -> reviewsService.save(review, admin.getId(), component.getId())); + assertTrue(exception.getMessage().contains("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.")); assertEquals(2, reviewsRepository.count()); } @@ -585,7 +585,7 @@ void updateVoidReview() { Review updatedReview = new Review("", "", null); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> reviewsService.updateReview(updatedReview, component.getId(), review.getId())); } @@ -603,7 +603,7 @@ void updateNullReview() { Review updatedReview = new Review(null, null, null); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> reviewsService.updateReview(updatedReview, component.getId(), review.getId())); } @@ -621,7 +621,7 @@ void updateBadFormatReview() { Review updatedReview = new Review("sample_title", "sample_message", Integer.valueOf(-5)); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> reviewsService.updateReview(updatedReview, component.getId(), review.getId())); } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/UsersIntegrationTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/UsersIntegrationTests.java index 841aa0a..22229da 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/UsersIntegrationTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/UsersIntegrationTests.java @@ -236,7 +236,7 @@ void register() { void registerVoidCredentials() { User newUser = new User("", "", "", "", "", "", ""); - assertThrows(IllegalArgumentException.class, () -> usersService.register(newUser, "")); + assertThrows(ResponseStatusException.class, () -> usersService.register(newUser, "")); assertEquals(2, usersRepository.count()); } @@ -244,7 +244,7 @@ void registerVoidCredentials() { void registerNullCredentials() { User newUser = new User(null, null, null, null, null, null, ""); - assertThrows(IllegalArgumentException.class, () -> usersService.register(newUser, null)); + assertThrows(ResponseStatusException.class, () -> usersService.register(newUser, null)); assertEquals(2, usersRepository.count()); } @@ -253,7 +253,7 @@ void registerExistingCredentials() { User newUser = new User("user", "test", "userTest1", "c/testAddress", "testuser1@example.com", null, "REGISTERED_USER"); - assertThrows(IllegalArgumentException.class, () -> usersService.register(newUser, "R3gister_Test_Pass")); + assertThrows(ResponseStatusException.class, () -> usersService.register(newUser, "R3gister_Test_Pass")); assertEquals(2, usersRepository.count()); } @@ -262,7 +262,7 @@ void registerBadFormatCredentials() { User newUser = new User("user", "test", "userTest", "c/testAddress", "test@example", null, "REGISTERED_USER"); - assertThrows(IllegalArgumentException.class, () -> usersService.register(newUser, "pass")); + assertThrows(ResponseStatusException.class, () -> usersService.register(newUser, "pass")); assertEquals(2, usersRepository.count()); } @@ -422,7 +422,7 @@ void postImageWithInvalidFile() { MockMultipartFile invalidTypeImage = new MockMultipartFile( "image", "image.txt", "text/plain", new byte[1024]); - assertThrows(IllegalArgumentException.class, () -> usersService.addUserImage(user.getId(), invalidTypeImage)); + assertThrows(ResponseStatusException.class, () -> usersService.addUserImage(user.getId(), invalidTypeImage)); } @@ -672,7 +672,7 @@ void updateVoidCredentials() { User updatedUser = new User("", "", "", "", "", "", ""); - assertThrows(IllegalArgumentException.class, () -> usersService.updateUser(updatedUser, "", user.getId())); + assertThrows(ResponseStatusException.class, () -> usersService.updateUser(updatedUser, "", user.getId())); } @@ -687,7 +687,7 @@ void updateNullCredentials() { User updatedUser = new User(null, null, null, null, null, null, ""); - assertThrows(IllegalArgumentException.class, () -> usersService.updateUser(updatedUser, null, user.getId())); + assertThrows(ResponseStatusException.class, () -> usersService.updateUser(updatedUser, null, user.getId())); } @@ -703,7 +703,7 @@ void updateExistingCredentials() { User updatedUser = new User("user", "test", "adminTest1", "c/testAddress", "testadmin1@example.com", null, "REGISTERED_USER"); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> usersService.updateUser(updatedUser, "Updat3_Test_Pass", user.getId())); } @@ -720,7 +720,7 @@ void updateBadFormatCredentials() { User updatedUser = new User("user", "test", "userTest", "c/testAddress", "test@example", null, "REGISTERED_USER"); - assertThrows(IllegalArgumentException.class, + assertThrows(ResponseStatusException.class, () -> usersService.updateUser(updatedUser, "pass", user.getId())); } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java index f1e0878..a2ad529 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java @@ -183,7 +183,7 @@ public void testCreateVoidComponentData() { Component component = new Component("", "", ComponentType.CPU, "", BigDecimal.valueOf(153.97), 14); - assertThrows(IllegalArgumentException.class, () -> componentsService.save(component)); + assertThrows(ResponseStatusException.class, () -> componentsService.save(component)); verify(componentsRepository, never()).save(any(Component.class)); } @@ -198,7 +198,7 @@ public void testCreateNullComponentData() { Component component = new Component(null, null, ComponentType.CPU, null, BigDecimal.valueOf(153.97), 14); - assertThrows(IllegalArgumentException.class, () -> componentsService.save(component)); + assertThrows(ResponseStatusException.class, () -> componentsService.save(component)); verify(componentsRepository, never()).save(any(Component.class)); } @@ -216,7 +216,7 @@ public void testCreateExistingComponentData() { when(componentsRepository.existsByName("Intel i5 12400F")).thenReturn(true); - assertThrows(IllegalArgumentException.class, () -> componentsService.save(component)); + assertThrows(ResponseStatusException.class, () -> componentsService.save(component)); verify(componentsRepository, never()).save(any(Component.class)); } @@ -348,9 +348,9 @@ public void testAddImageWithInvalidFile() throws IOException { MockMultipartFile invalidTypeImage = new MockMultipartFile( "image", "image.txt", "text/plain", new byte[1024]); - when(imageService.createImage(any())).thenThrow(IllegalArgumentException.class); + when(imageService.createImage(any())).thenThrow(ResponseStatusException.class); - assertThrows(IllegalArgumentException.class, () -> componentsService.addComponentImage(1L, invalidTypeImage)); + assertThrows(ResponseStatusException.class, () -> componentsService.addComponentImage(1L, invalidTypeImage)); } @Test @@ -469,7 +469,7 @@ public void testVoidUpdate() { when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(originalComponent)); - assertThrows(IllegalArgumentException.class, () -> componentsService.updateComponent(component, 1L)); + assertThrows(ResponseStatusException.class, () -> componentsService.updateComponent(component, 1L)); verify(componentsRepository, never()).save(any(Component.class)); } @@ -488,7 +488,7 @@ public void testNullUpdate() { when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(originalComponent)); - assertThrows(IllegalArgumentException.class, () -> componentsService.updateComponent(component, 1L)); + assertThrows(ResponseStatusException.class, () -> componentsService.updateComponent(component, 1L)); verify(componentsRepository, never()).save(any(Component.class)); } @@ -510,7 +510,7 @@ public void testExistingUpdate() { when(componentsRepository.existsByName("existingComponent")).thenReturn(true); - assertThrows(IllegalArgumentException.class, () -> componentsService.updateComponent(updatedComponent, 1L)); + assertThrows(ResponseStatusException.class, () -> componentsService.updateComponent(updatedComponent, 1L)); verify(componentsRepository, never()).save(any(Component.class)); } @@ -527,7 +527,7 @@ public void testBadFormatUpdate() { BigDecimal.valueOf(-5.00), -5); when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(component)); - assertThrows(IllegalArgumentException.class, () -> componentsService.updateComponent(component, 1L)); + assertThrows(ResponseStatusException.class, () -> componentsService.updateComponent(component, 1L)); verify(componentsRepository, never()).save(any(Component.class)); } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ImagesUnitTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ImagesUnitTests.java index 896a048..d9fa98a 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ImagesUnitTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ImagesUnitTests.java @@ -6,6 +6,7 @@ import org.springframework.core.io.Resource; import org.springframework.mock.web.MockMultipartFile; +import org.springframework.web.server.ResponseStatusException; import es.codeurjcstudents.pcmod.model.Image; import es.codeurjcstudents.pcmod.repository.ImageRepository; @@ -24,13 +25,12 @@ import java.util.Optional; import javax.sql.rowset.serial.SerialBlob; -import javax.sql.rowset.serial.SerialException; @Tag("server-unit") public class ImagesUnitTests { @Test - public void testCreateImage() throws SerialException, SQLException, IOException { + public void testCreateImage() throws SQLException, IOException { ImageRepository imageRepository = mock(ImageRepository.class); ImageService imageService = new ImageService(imageRepository); @@ -48,7 +48,7 @@ public void testCreateImage() throws SerialException, SQLException, IOException } @Test - public void testReplaceImage() throws SerialException, SQLException, IOException { + public void testReplaceImage() throws SQLException, IOException { ImageRepository imageRepository = mock(ImageRepository.class); ImageService imageService = new ImageService(imageRepository); @@ -71,7 +71,7 @@ public void testReplaceImage() throws SerialException, SQLException, IOException } @Test - public void testDeleteImage() throws IOException { + public void testDeleteImage() { ImageRepository imageRepository = mock(ImageRepository.class); ImageService imageService = new ImageService(imageRepository); @@ -101,9 +101,9 @@ void testValidateImage() { "image", "image.webp", "image/webp", new byte[10 * 1024 * 1024 + 1]); assertDoesNotThrow(() -> imageService.validate(validImage)); - assertThrows(IllegalArgumentException.class, () -> imageService.validate(invalidTypeImage)); - assertThrows(IllegalArgumentException.class, () -> imageService.validate(imageWithoutType)); - assertThrows(IllegalArgumentException.class, () -> imageService.validate(oversizedImage)); + assertThrows(ResponseStatusException.class, () -> imageService.validate(invalidTypeImage)); + assertThrows(ResponseStatusException.class, () -> imageService.validate(imageWithoutType)); + assertThrows(ResponseStatusException.class, () -> imageService.validate(oversizedImage)); } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java index b24e5c9..4331dc5 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java @@ -2,7 +2,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -205,8 +204,8 @@ public void testSaveReviewInComponentExistingSameUserReview() { when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, 1L, 1L)); - assertEquals("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.", exception.getMessage()); + ResponseStatusException exception = assertThrows(ResponseStatusException.class, () -> reviewsService.save(review, 1L, 1L)); + assertTrue(exception.getMessage().contains("Validación fallida:\n• Ya existe una reseña de este producto para tu usuario.")); verify(reviewsRepository, never()).save(any(Review.class)); } @@ -231,7 +230,7 @@ public void testSaveVoidReviewData() { when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); - assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, 1L, 1L)); + assertThrows(ResponseStatusException.class, () -> reviewsService.save(review, 1L, 1L)); verify(reviewsRepository, never()).save(any(Review.class)); } @@ -257,7 +256,7 @@ public void testSaveNullReviewData() { when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); - assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, 1L, 1L)); + assertThrows(ResponseStatusException.class, () -> reviewsService.save(review, 1L, 1L)); verify(reviewsRepository, never()).save(any(Review.class)); } @@ -283,7 +282,7 @@ public void testSaveBadNumReviewData() { when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); - assertThrows(IllegalArgumentException.class, () -> reviewsService.save(review, 1L, 1L)); + assertThrows(ResponseStatusException.class, () -> reviewsService.save(review, 1L, 1L)); verify(reviewsRepository, never()).save(any(Review.class)); } @@ -554,7 +553,7 @@ public void testUpdateVoidReviewData() { when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); - assertThrows(IllegalArgumentException.class, () -> reviewsService.updateReview(review, 1L, 1L)); + assertThrows(ResponseStatusException.class, () -> reviewsService.updateReview(review, 1L, 1L)); verify(reviewsRepository, never()).save(any(Review.class)); } @@ -581,7 +580,7 @@ public void testUpdateNullReviewData() { when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); - assertThrows(IllegalArgumentException.class, () -> reviewsService.updateReview(review, 1L, 1L)); + assertThrows(ResponseStatusException.class, () -> reviewsService.updateReview(review, 1L, 1L)); verify(reviewsRepository, never()).save(any(Review.class)); } @@ -608,7 +607,7 @@ public void testUpdateBadNumReviewData() { when(usersRepository.findById(1L)).thenReturn(Optional.of(user)); when(reviewsRepository.findById(1L)).thenReturn(Optional.of(review)); - assertThrows(IllegalArgumentException.class, () -> reviewsService.updateReview(review, 1L, 1L)); + assertThrows(ResponseStatusException.class, () -> reviewsService.updateReview(review, 1L, 1L)); verify(reviewsRepository, never()).save(any(Review.class)); } diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/UsersUnitTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/UsersUnitTests.java index 7f013b9..f73ee4f 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/UsersUnitTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/UsersUnitTests.java @@ -28,7 +28,6 @@ import java.sql.SQLException; import javax.sql.rowset.serial.SerialBlob; import java.util.List; -import java.util.NoSuchElementException; import es.codeurjcstudents.pcmod.model.Image; import es.codeurjcstudents.pcmod.model.User; @@ -157,7 +156,7 @@ public void testVoidCredentialsRegister() { User user = new User("", "", "", "", "", null, ""); - assertThrows(IllegalArgumentException.class, () -> usersService.register(user, "")); + assertThrows(ResponseStatusException.class, () -> usersService.register(user, "")); verify(usersRepository, never()).save(any(User.class)); } @@ -171,7 +170,7 @@ public void testNullCredentialsRegister() { User user = new User(null, null, null, null, null, null, ""); - assertThrows(IllegalArgumentException.class, () -> usersService.register(user, null)); + assertThrows(ResponseStatusException.class, () -> usersService.register(user, null)); verify(usersRepository, never()).save(any(User.class)); } @@ -188,7 +187,7 @@ public void testExistingCredentialsRegister() { when(usersRepository.existsByUsername("userTest")).thenReturn(true); when(usersRepository.existsByEmail("testuser@example.com")).thenReturn(true); - assertThrows(IllegalArgumentException.class, () -> usersService.register(user, "R3gister_Existing")); + assertThrows(ResponseStatusException.class, () -> usersService.register(user, "R3gister_Existing")); verify(usersRepository, never()).save(any(User.class)); } @@ -202,7 +201,7 @@ public void testBadFormatCredentialsRegister() { User user = new User("user", "test", "userTest", "c/testaddress", "test@email", null, ""); - assertThrows(IllegalArgumentException.class, () -> usersService.register(user, "pass")); + assertThrows(ResponseStatusException.class, () -> usersService.register(user, "pass")); verify(usersRepository, never()).save(any(User.class)); } @@ -339,9 +338,9 @@ public void testAddImageWithInvalidFile() throws IOException { MockMultipartFile invalidTypeImage = new MockMultipartFile( "image", "image.txt", "text/plain", new byte[1024]); - when(imageService.createImage(any())).thenThrow(IllegalArgumentException.class); + when(imageService.createImage(any())).thenThrow(ResponseStatusException.class); - assertThrows(IllegalArgumentException.class, () -> usersService.addUserImage(1L, invalidTypeImage)); + assertThrows(ResponseStatusException.class, () -> usersService.addUserImage(1L, invalidTypeImage)); } @Test @@ -451,7 +450,7 @@ public void testVoidCredentialsUpdate() { null, ""); when(usersRepository.findById(1L)).thenReturn(java.util.Optional.of(user)); - assertThrows(IllegalArgumentException.class, () -> usersService.updateUser(user, "", 1L)); + assertThrows(ResponseStatusException.class, () -> usersService.updateUser(user, "", 1L)); verify(usersRepository, never()).save(any(User.class)); } @@ -466,7 +465,7 @@ public void testNullCredentialsUpdate() { null, ""); when(usersRepository.findById(1L)).thenReturn(java.util.Optional.of(user)); - assertThrows(IllegalArgumentException.class, () -> usersService.updateUser(user, null, 1L)); + assertThrows(ResponseStatusException.class, () -> usersService.updateUser(user, null, 1L)); verify(usersRepository, never()).save(any(User.class)); } @@ -487,7 +486,7 @@ public void testExistingCredentialsUpdate() { when(usersRepository.existsByUsername("userTest")).thenReturn(true); when(usersRepository.existsByEmail("testuser@example.com")).thenReturn(true); - assertThrows(IllegalArgumentException.class, () -> usersService.updateUser(user, "Updat3_Existing", 1L)); + assertThrows(ResponseStatusException.class, () -> usersService.updateUser(user, "Updat3_Existing", 1L)); verify(usersRepository, never()).save(any(User.class)); } @@ -502,7 +501,7 @@ public void testBadFormatCredentialsUpdate() { null, ""); when(usersRepository.findById(1L)).thenReturn(java.util.Optional.of(user)); - assertThrows(IllegalArgumentException.class, () -> usersService.updateUser(user, "pass", 1L)); + assertThrows(ResponseStatusException.class, () -> usersService.updateUser(user, "pass", 1L)); verify(usersRepository, never()).save(any(User.class)); } From 450b2045de042c7e702278f3b36005d94c0bb9a1 Mon Sep 17 00:00:00 2001 From: jaimeeg5 Date: Sun, 15 Nov 2026 13:17:50 +0100 Subject: [PATCH 2/2] fix: return 404 when updating or deleting non-existent entities --- .../pcmod/service/ComponentsService.java | 14 ++--- .../pcmod/service/ImageService.java | 5 +- .../pcmod/service/ReviewsService.java | 26 ++++----- .../pcmod/service/UsersService.java | 15 +++-- .../pcmod/e2e/api/ComponentsSystemTests.java | 56 ++++++++++++++++++ .../pcmod/e2e/api/ReviewsSystemTests.java | 56 ++++++++++++++++++ .../pcmod/e2e/api/UsersSystemTests.java | 58 +++++++++++++++++++ .../ComponentsIntegrationTests.java | 31 ++++++++++ .../integration/ImagesIntegrationTests.java | 20 ++++++- .../integration/ReviewsIntegrationTests.java | 35 +++++++++++ .../integration/UsersIntegrationTests.java | 40 +++++++++++++ .../pcmod/unit/ComponentsUnitTests.java | 18 +++++- .../pcmod/unit/ImagesUnitTests.java | 26 +++++++++ .../pcmod/unit/ReviewsUnitTests.java | 20 ++++++- .../pcmod/unit/UsersUnitTests.java | 16 ++++- 15 files changed, 402 insertions(+), 34 deletions(-) diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java index fe6daaa..437fe92 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ComponentsService.java @@ -30,6 +30,8 @@ public class ComponentsService { private final ComponentMapper componentMapper; private final ImageService imagesService; + private static final String NOT_FOUND_MESSAGE = "Componente no encontrado."; + public ComponentsService(ComponentsRepository componentRepository, ComponentMapper componentMapper, ImageService imagesService) { this.componentRepository = componentRepository; @@ -47,7 +49,7 @@ public List findTop3MoreRecent() { public Component getComponent(long id) { return componentRepository.findById(id) - .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Componente no encontrado.")); + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); } public Resource getImageFile(long id) throws SQLException { @@ -96,19 +98,17 @@ public Image addComponentImage(long id, MultipartFile imageFile) throws IOExcept @PreAuthorize("hasRole('ADMIN')") public void delete(long id) { - Optional deletedComponent = componentRepository.findById(id); - - if (deletedComponent.isPresent()) { + componentRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); - componentRepository.deleteById(id); - - } + componentRepository.deleteById(id); } @PreAuthorize("hasRole('ADMIN')") public Component updateComponent(Component newComponentData, long id) { + componentRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); + List errors = validateComponent(newComponentData, id); if (!errors.isEmpty()) { diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ImageService.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ImageService.java index 82ca97d..0f6ae37 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ImageService.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ImageService.java @@ -19,6 +19,7 @@ public class ImageService { private static final long MAX_SIZE = 10L * 1024L * 1024L; // 10MB private static final List ALLOWED_TYPES = List.of("image/jpeg", "image/png", "image/webp"); + private static final String NOT_FOUND_MESSAGE = "Imagen no encontrada."; private final ImageRepository imageRepository; @@ -47,7 +48,7 @@ public Image createImage(InputStream inputStream) throws IOException { public Image replaceImageFile(long id, InputStream inputStream) throws IOException { - Image image = imageRepository.findById(id).orElseThrow(); + Image image = imageRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); try { image.setImageFile(new SerialBlob(inputStream.readAllBytes())); @@ -62,7 +63,7 @@ public Image replaceImageFile(long id, InputStream inputStream) throws IOExcepti public Image deleteImage(long id) { - Image image = imageRepository.findById(id).orElseThrow(); + Image image = imageRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); imageRepository.deleteById(id); return image; diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java index 48d106e..b2928f7 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/ReviewsService.java @@ -32,6 +32,10 @@ public class ReviewsService { private final ComponentsRepository componentRepository; private final UsersRepository userRepository; + private static final String NOT_FOUND_MESSAGE = "Reseña no encontrada."; + private static final String COMPONENT_NOT_FOUND_MESSAGE = "Componente no encontrado."; + private static final String USER_NOT_FOUND_MESSAGE = "Usuario no encontrado."; + public ReviewsService(ReviewsRepository reviewsRepository, ReviewMapper reviewMapper, ComponentsRepository componentRepository, UsersRepository userRepository) { this.reviewRepository = reviewsRepository; @@ -44,10 +48,10 @@ public ReviewsService(ReviewsRepository reviewsRepository, ReviewMapper reviewMa public Review createReview(Long userId, Long componentId, Review review) { User user = userRepository.findById(userId) - .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Usuario no encontrado.")); + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, USER_NOT_FOUND_MESSAGE)); Component component = componentRepository.findById(componentId) - .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Componente no encontrado.")); + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, COMPONENT_NOT_FOUND_MESSAGE)); user.addReview(review); component.addReview(review); @@ -74,10 +78,10 @@ public Review save(Review review, long userId, long componentId) { } User user = userRepository.findById(userId) - .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Usuario no encontrado.")); + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, USER_NOT_FOUND_MESSAGE)); Component component = componentRepository.findById(componentId) - .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Componente no encontrado.")); + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, COMPONENT_NOT_FOUND_MESSAGE)); review.setDate(LocalDate.now(ZoneId.of("Europe/Madrid"))); user.addReview(review); @@ -89,26 +93,22 @@ public Review save(Review review, long userId, long componentId) { @PreAuthorize("hasRole('ADMIN') or @reviewsService.isOwner(#reviewId, principal.username)") public void delete(long componentId, long reviewId) { - Optional reviewToDelete = reviewRepository.findById(reviewId); + Review reviewToDelete = reviewRepository.findById(reviewId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); - if ((reviewToDelete.isPresent()) && (reviewToDelete.get().getComponent().getId() != componentId)) { + if (reviewToDelete.getComponent().getId() != componentId) { throw new NoSuchElementException("La reseña no pertenece a ese componente."); } - if (reviewToDelete.isPresent()) { - - reviewRepository.deleteById(reviewId); - - } + reviewRepository.deleteById(reviewId); } @PreAuthorize("hasRole('ADMIN') or @reviewsService.isOwner(#reviewId, principal.username)") public Review updateReview(Review newReviewData, long componentId, long reviewId) { - Optional reviewToUpdate = reviewRepository.findById(reviewId); + Review reviewToUpdate = reviewRepository.findById(reviewId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); - if ((reviewToUpdate.isPresent()) && (reviewToUpdate.get().getComponent().getId() != componentId)) { + if (reviewToUpdate.getComponent().getId() != componentId) { throw new NoSuchElementException("La reseña no pertenece a ese componente."); } diff --git a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/UsersService.java b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/UsersService.java index 62daf40..b1d292b 100644 --- a/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/UsersService.java +++ b/backend/pcmod/src/main/java/es/codeurjcstudents/pcmod/service/UsersService.java @@ -33,6 +33,7 @@ public class UsersService { private static final String EMAIL_REGEX = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"; private static final String PASS_REGEX = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&\\-_])[A-Za-z\\d@$!%*?&\\-_]{8,}$"; + private static final String NOT_FOUND_MESSAGE = "Usuario no encontrado."; public UsersService(UsersRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, ImageService imagesService) { @@ -48,7 +49,7 @@ public User createUser(User user) { public User getUser(long id) { return userRepository.findById(id) - .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Usuario no encontrado.")); + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); } public Resource getImageFile(long id) throws SQLException { @@ -81,7 +82,7 @@ public Image addUserImage(long id, MultipartFile imageFile) throws IOException { imagesService.validate(imageFile); - User user = userRepository.findById(id).orElseThrow(); + User user = userRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); Image image; if (user.getImage() == null) { @@ -98,19 +99,17 @@ public Image addUserImage(long id, MultipartFile imageFile) throws IOException { @PreAuthorize("hasRole('ADMIN') or principal.username == #id.toString()") public void deleteUser(long id) { - Optional user = userRepository.findById(id); - - if (user.isPresent()) { + userRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); - userRepository.deleteById(id); - - } + userRepository.deleteById(id); } @PreAuthorize("hasRole('ADMIN') or principal.username == #id.toString()") public User updateUser(User newUserData, String rawPassword, long id) { + userRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, NOT_FOUND_MESSAGE)); + List errors = validateUser(newUserData, rawPassword, id); if (!errors.isEmpty()) { diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java index e4d76f9..9ab3486 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ComponentsSystemTests.java @@ -516,6 +516,29 @@ public void deleteComponentAsAdmin() { .then().statusCode(200); } + @Test + public void deleteNoExistingComponent() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .header("Content-Type", "application/json") + .cookie("AuthToken", authToken) + .when().delete("components/99") + .then().statusCode(404) + .body("error", equalTo("Not Found")) + .body("message", equalTo("Componente no encontrado.")); + } + @Test public void putComponentAsNoLoggedIn() { @@ -606,6 +629,39 @@ public void putComponentAsAdmin() { .body("stock", equalTo(5)); } + @Test + public void putNoExistingComponent() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "name": "sampleNamePUT", + "description": "sampleDescriptionPUT", + "type" : "CPU", + "brand" : "MSI", + "price" : 100.00, + "stock" : 5 + } + """) + .when().put("components/99") + .then().statusCode(404).contentType(ContentType.JSON) + .body("error", equalTo("Not Found")) + .body("message", equalTo("Componente no encontrado.")); + } + @Test public void putVoidComponent() { String authToken = given() diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java index d38f307..1bbbd73 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/ReviewsSystemTests.java @@ -412,6 +412,31 @@ public void deleteReviewsAsAdmin() { } + @Test + public void deleteNoExistingReview() { + + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .header("Content-Type", "application/json") + .cookie("AuthToken", authToken) + .when().delete("components/2/reviews/99") + .then().statusCode(404) + .body("error", equalTo("Not Found")) + .body("message", equalTo("Reseña no encontrada.")); + + } + @Test public void deleteReviewWithWrongComponentId() { @@ -562,6 +587,37 @@ public void putReviewsAsAdmin() { .body("rating", equalTo(5)); } + @Test + public void putNoExistingReview() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "title": "sample_title", + "message": "sample_message", + "rating": 5 + } + """) + .when().put("/components/2/reviews/99") + .then().statusCode(404).contentType(ContentType.JSON) + .body("error", equalTo("Not Found")) + .body("message", equalTo("Reseña no encontrada.")); + + } + @Test public void putVoidReviewData() { String authToken = given() diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/UsersSystemTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/UsersSystemTests.java index 91553d4..fda2185 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/UsersSystemTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/e2e/api/UsersSystemTests.java @@ -669,6 +669,30 @@ public void deleteUsersAsAdmin() { } + @Test + public void deleteNoExistingUser() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .header("Content-Type", "application/json") + .cookie("AuthToken", authToken) + .when().delete("users/99") + .then().statusCode(404) + .body("error", equalTo("Not Found")) + .body("message", equalTo("Usuario no encontrado.")); + + } + @Test public void putUserAsNoLoggedIn() { @@ -821,6 +845,40 @@ public void putUsersAccountsAsAdmin() { } + @Test + public void putNoExistingUser() { + String authToken = given() + .header("Content-Type", "application/json") + .body(""" + { + "username": "admin@example.com", + "password": "adminpass" + } + """) + .when().post("auth/login") + .then().statusCode(200).contentType(ContentType.JSON) + .extract().cookie("AuthToken"); + + given() + .cookie("AuthToken", authToken) + .header("Content-Type", "application/json") + .body(""" + { + "name": "update", + "surname": "user", + "username": "update.user", + "address" : "c/ example 3", + "email": "update.user@example.com", + "password": "Updat3_user_pass" + } + """) + .when().put("users/99") + .then().statusCode(404).contentType(ContentType.JSON) + .body("error", equalTo("Not Found")) + .body("message", equalTo("Usuario no encontrado.")); + + } + @Test public void putVoidCredentials() { String authToken = given() diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java index c441ac1..18f13c9 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ComponentsIntegrationTests.java @@ -460,6 +460,20 @@ void deleteComponentAsAdmin() { assertEquals(1, componentsRepository.count()); } + @Test + void deleteNoExistingComponent() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + assertThrows(ResponseStatusException.class, () -> componentsService.delete(99L)); + assertEquals(2, componentsRepository.count()); + } + @Test void updateImageAsNoRegisteredUser() throws IOException { User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); @@ -604,6 +618,23 @@ void updateComponentAsAdmin() { assertEquals(5, savedComponent.getStock()); } + @Test + void updateNoExistingComponent() { + + Component updatedComponent = new Component("sampleName", "sampleDescription", ComponentType.CPU, "sampleBrand", + BigDecimal.valueOf(100.00), 5); + + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + assertThrows(ResponseStatusException.class, () -> componentsService.updateComponent(updatedComponent, 99L)); + + } + @Test void updateVoidComponent() { User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ImagesIntegrationTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ImagesIntegrationTests.java index 064a972..dfc4ac5 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ImagesIntegrationTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ImagesIntegrationTests.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; @@ -20,7 +21,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; - +import org.springframework.web.server.ResponseStatusException; import org.testcontainers.containers.MySQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -113,6 +114,16 @@ void replaceImage() throws IOException, SQLException { } + @Test + void replaceNoExistingImage() { + + imageRepository.deleteAll(); + + Resource replacementPath = new ClassPathResource("/sample_images/i5-12400f.webp"); + + assertThrows(ResponseStatusException.class, () -> imageService.replaceImageFile(99L, replacementPath.getInputStream())); + } + @Test void deleteImage() { @@ -124,4 +135,11 @@ void deleteImage() { } + @Test + void deleteNoExistingImage() { + + assertThrows(ResponseStatusException.class, () -> imageService.deleteImage(99L)); + + } + } \ No newline at end of file diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java index 085c65e..4a397a2 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/ReviewsIntegrationTests.java @@ -473,6 +473,23 @@ void deleteReviewsAsAdmin() { } + @Test + void deleteNoExistingReview() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + Component component = componentsRepository.findAll().getFirst(); + + assertThrows(ResponseStatusException.class, () -> reviewsService.delete(component.getId(), 99L)); + assertEquals(2, reviewsRepository.count()); + + } + @Test void deleteReviewOfWrongComponent() { User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); @@ -571,6 +588,24 @@ void updateReviewAsAdmin() { } + @Test + void updateNoExistingReview() { + Component component = componentsRepository.findAll().getFirst(); + + Review updatedReview = new Review("sample_title", "sample_message", Integer.valueOf(5)); + + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + assertThrows(ResponseStatusException.class, () -> reviewsService.updateReview(updatedReview, component.getId(), 99L)); + + + } + @Test void updateVoidReview() { User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/UsersIntegrationTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/UsersIntegrationTests.java index 22229da..2997d8f 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/UsersIntegrationTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/integration/UsersIntegrationTests.java @@ -182,6 +182,13 @@ void getUsersAsAdmin() { } + @Test + void getNoExistingUser() { + + assertThrows(ResponseStatusException.class, () -> usersService.getUser(99L)); + + } + @Test void getUserImage() throws IOException, SQLException { Resource expectedImage = new ClassPathResource("/sample_images/user.png"); @@ -566,6 +573,21 @@ void deleteUsersAsAdmin() { } + @Test + void deleteNoExistingUser() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + assertThrows(ResponseStatusException.class, () -> usersService.deleteUser(99L)); + assertEquals(2, usersRepository.count()); + + } + @Test void updateAsNonRegisteredUser() { User user = usersRepository.findByEmail("testuser1@example.com").orElseThrow(); @@ -661,6 +683,24 @@ void updateUsersAccountAsAdmin() { } + @Test + void updateNoExisitingUser() { + User admin = usersRepository.findByEmail("testadmin1@example.com").orElseThrow(); + SecurityContextHolder.getContext().setAuthentication( + new UsernamePasswordAuthenticationToken( + org.springframework.security.core.userdetails.User.withUsername(admin.getId().toString()) + .password("").authorities("ROLE_ADMIN").build(), + null, java.util.List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))); + + User updated = new User("updatedName", "updatedSurname", "updatedUsernameNoExisting", + "c/testaddressUpdate", + "testUpdatedNoExisting@example.com", + null, "REGISTERED_USER"); + assertThrows(ResponseStatusException.class, () -> usersService.updateUser(updated, "Updat3_Test_Pass", 99L)); + + } + + @Test void updateVoidCredentials() { User user = usersRepository.findByEmail("testuser1@example.com").orElseThrow(); diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java index a2ad529..e6fd6c8 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ComponentsUnitTests.java @@ -420,7 +420,7 @@ public void testDeleteNonExistentComponent() { when(componentsRepository.findById(1L)).thenReturn(Optional.empty()); - componentsService.delete(1L); + assertThrows(ResponseStatusException.class, () -> componentsService.delete(1L)); verify(componentsRepository, never()).deleteById(1L); @@ -455,6 +455,22 @@ public void testUpdate() { } + @Test + public void testUpdateNonExistentComponent() { + + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + ComponentMapper componentMapper = mock(ComponentMapper.class); + ImageService imageService = mock(ImageService.class); + ComponentsService componentsService = new ComponentsService(componentsRepository, componentMapper, imageService); + + when(componentsRepository.findById(1L)).thenReturn(Optional.empty()); + + assertThrows(ResponseStatusException.class, () -> componentsService.updateComponent(new Component(), 1L)); + + verify(componentsRepository, never()).save(any(Component.class)); + + } + @Test public void testVoidUpdate() { diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ImagesUnitTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ImagesUnitTests.java index d9fa98a..eadda51 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ImagesUnitTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ImagesUnitTests.java @@ -70,6 +70,20 @@ public void testReplaceImage() throws SQLException, IOException { } + @Test + public void testReplaceNoExistingImage() { + + ImageRepository imageRepository = mock(ImageRepository.class); + ImageService imageService = new ImageService(imageRepository); + + when(imageRepository.findById(99L)).thenReturn(Optional.empty()); + + String classpathResource = "/sample_images/i5-12400f.webp"; + Resource imagePath = new ClassPathResource(classpathResource); + assertThrows(ResponseStatusException.class, () -> imageService.replaceImageFile(99L, imagePath.getInputStream())); + + } + @Test public void testDeleteImage() { @@ -85,6 +99,18 @@ public void testDeleteImage() { } + @Test + public void testDeleteNoExistingImage() { + + ImageRepository imageRepository = mock(ImageRepository.class); + ImageService imageService = new ImageService(imageRepository); + + when(imageRepository.findById(99L)).thenReturn(Optional.empty()); + + assertThrows(ResponseStatusException.class, () -> imageService.deleteImage(99L)); + + } + @Test void testValidateImage() { diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java index 4331dc5..3474471 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/ReviewsUnitTests.java @@ -407,7 +407,7 @@ public void testDeleteReviewNotFound() { when(reviewsRepository.findById(1L)).thenReturn(java.util.Optional.empty()); when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(component)); - reviewsService.delete(1L, 1L); + assertThrows(ResponseStatusException.class, () -> reviewsService.delete(1L, 1L)); verify(reviewsRepository, never()).deleteById(1L); @@ -531,6 +531,24 @@ public void testUpdateReview() { verify(reviewsRepository).save(any(Review.class)); } + @Test + public void testUpdateReviewNotFound() { + + ReviewsRepository reviewsRepository = mock(ReviewsRepository.class); + ReviewsService reviewsService = new ReviewsService(reviewsRepository, null, null, null ); + ComponentsRepository componentsRepository = mock(ComponentsRepository.class); + + Component component = new Component("sample_name", "sample_message", ComponentType.CPU, "sample_brand", BigDecimal.valueOf(100.00), 5); + + when(reviewsRepository.findById(1L)).thenReturn(java.util.Optional.empty()); + when(componentsRepository.findById(1L)).thenReturn(java.util.Optional.of(component)); + + assertThrows(ResponseStatusException.class, () -> reviewsService.updateReview(new Review(), 1L, 1L)); + + verify(reviewsRepository, never()).save(any(Review.class)); + + } + @Test public void testUpdateVoidReviewData() { diff --git a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/UsersUnitTests.java b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/UsersUnitTests.java index f73ee4f..da08951 100644 --- a/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/UsersUnitTests.java +++ b/backend/pcmod/src/test/java/es/codeurjcstudents/pcmod/unit/UsersUnitTests.java @@ -405,7 +405,7 @@ public void testDeleteUserNotFound() { when(usersRepository.findById(1L)).thenReturn(java.util.Optional.empty()); - usersService.deleteUser(1L); + assertThrows(ResponseStatusException.class, () -> usersService.deleteUser(1L)); verify(usersRepository, never()).deleteById(1L); @@ -440,6 +440,20 @@ public void testUpdate() { } + @Test + public void testUpdateUserNotFound() { + + UsersRepository usersRepository = mock(UsersRepository.class); + UsersService usersService = new UsersService(usersRepository, null, null, null); + + when(usersRepository.findById(1L)).thenReturn(java.util.Optional.empty()); + + assertThrows(ResponseStatusException.class, () -> usersService.updateUser(new User(), "password", 1L)); + + verify(usersRepository, never()).save(any(User.class)); + + } + @Test public void testVoidCredentialsUpdate() {