Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix core, service and service-api issues #403

Merged
merged 11 commits into from
Oct 1, 2024
6 changes: 2 additions & 4 deletions core/src/main/java/greencity/annotations/ApiLocale.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package greencity.annotations;

import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import java.lang.annotation.ElementType;
Expand All @@ -17,8 +16,7 @@
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Parameters({
@Parameter(name = "lang", schema = @Schema(type = "string"), in = ParameterIn.QUERY,
description = "Code of the needed language.")})
@Parameter(name = "lang", schema = @Schema(type = "string"), in = ParameterIn.QUERY,
description = "Code of the needed language.")
public @interface ApiLocale {
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,25 @@ public final ResponseEntity<Object> handleConstraintViolationException(
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(exceptionResponse);
}

/**
* Method intercept exception {@link IllegalArgumentException}.
*
* @param ex the IllegalArgumentException that was thrown
* @param request the WebRequest that triggered the exception
* @return a ResponseEntity containing the {@link ExceptionResponse} with
* details about the error and a 400 Bad Request HTTP status
* @author Roman Kasarab
*/
@ExceptionHandler(IllegalArgumentException.class)
public final ResponseEntity<Object> handleIllegalArgumentException(
IllegalArgumentException ex,
WebRequest request) {
log.info(ex.getMessage());
ExceptionResponse exceptionResponse = new ExceptionResponse(getErrorAttributes(request));
exceptionResponse.setMessage(ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(exceptionResponse);
}

/**
* Method intercept exception {@link BadRequestException}.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,24 +190,10 @@ void handleConversionFailedException() {
ResponseEntity.status(HttpStatus.BAD_REQUEST).body(exceptionResponse));
}

/*
* @Test void handleMethodArgumentNotValid() { HttpStatus httpStatus =
* HttpStatus.BAD_REQUEST; FieldError fieldError = new FieldError("G", "field",
* "default"); ValidationExceptionDto validationExceptionDto = new
* ValidationExceptionDto(fieldError);
* when(notValidException.getBindingResult()).thenReturn(bindingResult);
* when(bindingResult.getFieldErrors()).thenReturn(Collections.singletonList(
* fieldError)); assertEquals(
* customExceptionHandler.handleMethodArgumentNotValid(notValidException,
* headers, httpStatus, webRequest),
* ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Collections.singletonList(
* validationExceptionDto))); }
*/

@Test
void handleMethodArgumentNotValid() {
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
FieldError fieldError = new FieldError("G", "field", "default");
fieldError = new FieldError("G", "field", "default");
ValidationExceptionDto validationExceptionDto = new ValidationExceptionDto(fieldError);

final BindingResult bindingResult = mock(BindingResult.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ void loginPage() throws Exception {

@Test
void loginPageInvalidDto() throws Exception {
OwnSignInDto dto = new OwnSignInDto("", "");
mockMvc.perform(post(LINK + "/login"))
.andExpect(view().name("core/management_login"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public String getEmailOutOfAccessToken(String token) {
try {
jsonNode = objectMapper.readTree(payload);
} catch (Exception e) {
throw new RuntimeException("Error parsing JSON payload", e);
throw new IllegalArgumentException("Error parsing JSON payload", e);
KizerovDmitriy marked this conversation as resolved.
Show resolved Hide resolved
}
return jsonNode.path("sub").asText();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*
* @author Volodymyr Mladonov
*/
@SuppressWarnings("java:S1118")
public class EmailAddressValidator {
public static final Pattern REGEX_PATTERN = Pattern.compile(AppConstant.VALIDATION_EMAIL_REGEXP);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*
* @author Volodymyr Mladonov
*/
@SuppressWarnings("java:S1118")
public class LanguageValidationUtils {
private static final List<String> SUPPORTED_LANGUAGES = List.of("en", "ua");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings("java:S1118")
public class UrlValidator {
/**
* Method that checks if received URL is valid (string could be parsed as a URI
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
Expand All @@ -13,7 +12,6 @@ class SearchCriteriaTest {

@BeforeEach
void init() {
MockitoAnnotations.initMocks(this);
searchCriteria = new SearchCriteria("test", "test", "test");
}

Expand Down
12 changes: 12 additions & 0 deletions service-api/src/test/java/greencity/security/jwt/JwtToolTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
Expand Down Expand Up @@ -134,6 +135,17 @@ void isTokenValidWithValidTokenTest() {
assertEquals(expectedExpiration, actualExpiration);
}

@Test
void getEmailOutOfAccessTokenThrowsExceptionOnInvalidTokenTest() {
String invalidToken = "eyJhbGciOiJIUzI1NiJ9.invalid_payload.signature";

IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
jwtTool.getEmailOutOfAccessToken(invalidToken);
});

assertEquals("Error parsing JSON payload", exception.getMessage());
}

@Test
void getTokenFromHttpServletRequest() {
final String expectedToken = "An AccessToken";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import greencity.dto.user.UserManagementViewDto;
import greencity.entity.User;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Expression;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
Expand All @@ -15,16 +14,16 @@
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class CustomSpecificationTest {
@Mock
private Root<User> root;
@Mock
private CriteriaQuery<User> criteriaQuery;
@Mock
private CriteriaBuilder criteriaBuilder;
@Mock
private Predicate expected;
Expand All @@ -37,7 +36,6 @@ class CustomSpecificationTest {

@BeforeEach
void init() {
MockitoAnnotations.initMocks(this);
searchCriteriaList = new ArrayList<>();
UserManagementViewDto userViewDto = UserManagementViewDto.builder()
.id("1")
Expand Down Expand Up @@ -85,15 +83,13 @@ void getIdPredicate() {
when(root.get(searchCriteriaList.getFirst().getKey())).thenReturn(objectPathExpected);
when(criteriaBuilder.equal(objectPathExpected, searchCriteriaList.getFirst().getValue()))
.thenThrow(NumberFormatException.class);
when(criteriaBuilder.conjunction()).thenReturn(expected);
when(criteriaBuilder.disjunction()).thenReturn(expected);
Predicate actual = userSpecification.getIdPredicate(root, criteriaBuilder, searchCriteriaList.getFirst());
assertEquals(expected, actual);
}

@Test
void getStringPredicate() {
when(criteriaBuilder.conjunction()).thenReturn(expected);
when(root.get(searchCriteriaList.get(1).getKey())).thenReturn(objectPathExpected);
when(criteriaBuilder.like(any(), eq("%" + searchCriteriaList.get(1).getValue() + "%"))).thenReturn(expected);
Predicate actual = userSpecification.getStringPredicate(root, criteriaBuilder, searchCriteriaList.get(1));
Expand All @@ -103,7 +99,6 @@ void getStringPredicate() {

@Test
void getEnumPredicate() {
when(criteriaBuilder.conjunction()).thenReturn(expected);
when(root.get(searchCriteriaList.get(5).getKey())).thenReturn(objectPathExpected);
when(objectPathExpected.as(Integer.class)).thenReturn(as);
when(criteriaBuilder.equal(as, searchCriteriaList.get(5).getValue())).thenReturn(expected);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import static org.mockito.ArgumentMatchers.eq;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
Expand All @@ -40,7 +39,6 @@ class UserSpecificationTest {

@BeforeEach
void init() {
MockitoAnnotations.initMocks(this);
searchCriteriaList = new ArrayList<>();
UserManagementViewDto userViewDto = UserManagementViewDto.builder()
.id("1")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -602,16 +602,17 @@ void deleteUserByEmail_UserNotExists() {

@Test
void deleteUserByEmailNotVerifiedUserTest() {
User notVerifiedUser = User.builder()
User newNotVerifiedUser = User.builder()
.id(1L)
.email("test@somemail.com")
.userStatus(UserStatus.DEACTIVATED)
.build();
Optional<User> optionalUser = Optional.of(notVerifiedUser);
Optional<User> optionalUser = Optional.of(newNotVerifiedUser);
String email = newNotVerifiedUser.getEmail();

when(userRepo.findByEmail(notVerifiedUser.getEmail())).thenReturn(optionalUser);
assertThrows(EmailNotVerified.class, () -> ownSecurityService.deleteUserByEmail(notVerifiedUser.getEmail()));
when(userRepo.findByEmail(newNotVerifiedUser.getEmail())).thenReturn(optionalUser);
assertThrows(EmailNotVerified.class, () -> ownSecurityService.deleteUserByEmail(email));

verify(userRepo, times(1)).findByEmail(notVerifiedUser.getEmail());
verify(userRepo, times(1)).findByEmail(newNotVerifiedUser.getEmail());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,4 @@ void verifyByTokenNoTokenFoundTest() {

assertEquals(expectedExceptionMessage, exception.getMessage());
}

/*
* @Test void deleteAllUsersThatDidNotVerifyEmailTest() {
* verifyEmailService.deleteAllUsersThatDidNotVerifyEmail();
* verify(verifyEmailRepo).deleteAllUsersThatDidNotVerifyEmail(); }
*/
}
Loading
Loading