diff --git a/pom.xml b/pom.xml index cdbc5dd9..cc060702 100644 --- a/pom.xml +++ b/pom.xml @@ -23,23 +23,16 @@ 2.2.4.RELEASE 1.0.9.RELEASE 1.5.5.Final - 0.8.6 + 0.8.12 3.1.0 0.9.10 2.8 1.18.22 3.0.0 - - 0.6 - 3.13.1 - 3.3.0 - 4.1.50.Final 2.1.5 - 4.4.0 + 3.5.2 jcmdsbr https://sonarcloud.io - - @@ -175,22 +168,6 @@ ${caelum.stella.version} - - com.querydsl - querydsl-apt - - - - com.querydsl - querydsl-jpa - - - - com.querydsl - querydsl-sql - ${querydsl-apt.version} - - org.slf4j slf4j-api @@ -199,35 +176,19 @@ com.google.zxing core - 3.5.2 + ${google.zxing.version} com.google.zxing javase - 3.5.2 + ${google.zxing.version} - - com.mysema.maven - apt-maven-plugin - 1.1.3 - - - - process - - - target/generated-sources/java - com.querydsl.apt.jpa.JPAAnnotationProcessor - - - - org.apache.maven.plugins maven-compiler-plugin @@ -258,8 +219,8 @@ ${jacoco.version} - com/fiap/tc/usecase/service/**/* - com/fiap/tc/usecase/* + com/fiap/tc/core/usecase/**/* + com/fiap/tc/adapter/repository/output/** @@ -269,8 +230,8 @@ - jacoco-report - verify + report + prepare-package report diff --git a/src/main/java/com/fiap/tc/adapter/repository/CategoryRepository.java b/src/main/java/com/fiap/tc/adapter/repository/CategoryRepository.java index fa5f93d0..507ff6b1 100644 --- a/src/main/java/com/fiap/tc/adapter/repository/CategoryRepository.java +++ b/src/main/java/com/fiap/tc/adapter/repository/CategoryRepository.java @@ -4,12 +4,13 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import java.util.Optional; import java.util.UUID; @Repository public interface CategoryRepository extends JpaRepository { - CategoryEntity findByNameOrDescription(String name, String description); + Optional findByName(String name); - CategoryEntity findByUuid(UUID uuid); + Optional findByUuid(UUID uuid); } diff --git a/src/main/java/com/fiap/tc/adapter/repository/mapper/OrderListMapper.java b/src/main/java/com/fiap/tc/adapter/repository/mapper/OrderListMapper.java index 3ebad7d0..4a458f3e 100644 --- a/src/main/java/com/fiap/tc/adapter/repository/mapper/OrderListMapper.java +++ b/src/main/java/com/fiap/tc/adapter/repository/mapper/OrderListMapper.java @@ -3,7 +3,6 @@ import com.fiap.tc.adapter.repository.entity.OrderEntity; import com.fiap.tc.adapter.repository.entity.OrderHistoricEntity; import com.fiap.tc.adapter.repository.mapper.base.MapperEntity; -import com.fiap.tc.core.domain.model.Order; import com.fiap.tc.core.domain.model.enums.OrderStatus; import com.fiap.tc.core.domain.response.OrderListResponse; import org.mapstruct.Mapper; @@ -14,7 +13,6 @@ import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import static com.fiap.tc.common.constants.OrderConstants.WAIT_TIME_STATUS; @@ -45,7 +43,7 @@ default Optional getPreparingRegisterDate(OrderEntity orderEntity List preparingDates = orderEntity.getOrderHistoric().stream() .filter(historic -> historic.getStatus().equals(OrderStatus.PREPARING)) .map(OrderHistoricEntity::getRegisterDate) - .collect(Collectors.toList()); + .toList(); return preparingDates.stream().findFirst(); } diff --git a/src/main/java/com/fiap/tc/adapter/repository/output/CategoryOutputAdapter.java b/src/main/java/com/fiap/tc/adapter/repository/output/CategoryOutputAdapter.java index 5af3b532..f4d97464 100644 --- a/src/main/java/com/fiap/tc/adapter/repository/output/CategoryOutputAdapter.java +++ b/src/main/java/com/fiap/tc/adapter/repository/output/CategoryOutputAdapter.java @@ -18,8 +18,6 @@ import static com.fiap.tc.adapter.repository.mapper.base.MapperConstants.CATEGORY_MAPPER; import static java.lang.String.format; -import static java.util.Objects.isNull; -import static java.util.Objects.nonNull; @Service public class CategoryOutputAdapter implements SaveCategoryOutputPort, LoadCategoryOutputPort, @@ -32,10 +30,8 @@ public CategoryOutputAdapter(CategoryRepository categoryPersistenceRepository) { @Override public void delete(UUID uuid) { - var category = categoryRepository.findByUuid(uuid); - if (nonNull(category)) { - categoryRepository.delete(category); - } + var categoryEntityOptional = categoryRepository.findByUuid(uuid); + categoryEntityOptional.ifPresent(categoryRepository::delete); } @Override @@ -46,17 +42,18 @@ public Page list(Pageable pageable) { @Override public Category load(UUID uuid) { - var category = categoryRepository.findByUuid(uuid); - if (isNull(category)) { + var categoryEntityOptional = categoryRepository.findByUuid(uuid); + if (categoryEntityOptional.isEmpty()) { throw new NotFoundException(format("Category with uuid %s not found!", uuid)); } - return CATEGORY_MAPPER.fromEntity(category); + return CATEGORY_MAPPER.fromEntity(categoryEntityOptional.get()); } @Override public Category saveOrUpdate(String name, String description, boolean active) { - var categoryEntity = categoryRepository.findByNameOrDescription(name, description); - if (nonNull(categoryEntity)) { + var categoryEntityOptional = categoryRepository.findByName(name); + if (categoryEntityOptional.isPresent()) { + var categoryEntity = categoryEntityOptional.get(); categoryEntity.setName(name); categoryEntity.setDescription(description); categoryEntity.getAudit().setActive(active); diff --git a/src/main/java/com/fiap/tc/common/config/AuthorizationServerConfig.java b/src/main/java/com/fiap/tc/common/config/AuthorizationServerConfig.java index 713bb75b..ea0ccc65 100644 --- a/src/main/java/com/fiap/tc/common/config/AuthorizationServerConfig.java +++ b/src/main/java/com/fiap/tc/common/config/AuthorizationServerConfig.java @@ -36,8 +36,8 @@ public void configure(ClientDetailsServiceConfigurer clients) throws Exception { .secret(clientConfig.getSecret()) .scopes("read", "write") .authorizedGrantTypes("password", "refresh_token") - .accessTokenValiditySeconds(86400) - .refreshTokenValiditySeconds(3600 * 24); + .accessTokenValiditySeconds(clientConfig.getTokenExpirationTime()) + .refreshTokenValiditySeconds(clientConfig.getRefreshTokenExpirationTime()); } @Override @@ -45,11 +45,8 @@ public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws E TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter())); - endpoints - - .tokenStore(tokenStore()) + endpoints.tokenStore(tokenStore()) .tokenEnhancer(tokenEnhancerChain) - .reuseRefreshTokens(false) .userDetailsService(userDetailsService) .authenticationManager(authenticationManager); } diff --git a/src/main/java/com/fiap/tc/common/config/ClientConfig.java b/src/main/java/com/fiap/tc/common/config/ClientConfig.java index 7dc9c110..feeb0877 100644 --- a/src/main/java/com/fiap/tc/common/config/ClientConfig.java +++ b/src/main/java/com/fiap/tc/common/config/ClientConfig.java @@ -11,4 +11,6 @@ public class ClientConfig { private String name; private String secret; private String signKey; + private Integer tokenExpirationTime; + private Integer refreshTokenExpirationTime; } diff --git a/src/main/java/com/fiap/tc/common/config/WebConfig.java b/src/main/java/com/fiap/tc/common/config/WebConfig.java index e261c51d..76134880 100644 --- a/src/main/java/com/fiap/tc/common/config/WebConfig.java +++ b/src/main/java/com/fiap/tc/common/config/WebConfig.java @@ -1,10 +1,20 @@ package com.fiap.tc.common.config; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.i18n.SessionLocaleResolver; + +import java.util.Locale; @Configuration -@EnableScheduling public class WebConfig { + @Bean + public LocaleResolver localeResolver() { + SessionLocaleResolver slr = new SessionLocaleResolver(); + slr.setDefaultLocale(Locale.US); + return slr; + } + } diff --git a/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/ConfirmedOrderStatusValidator.java b/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/ConfirmedOrderStatusValidator.java deleted file mode 100644 index 5067ec8f..00000000 --- a/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/ConfirmedOrderStatusValidator.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.fiap.tc.core.domain.behavior.order.status.validator; - -import com.fiap.tc.core.domain.model.enums.OrderStatus; - -import java.util.List; - - -public class ConfirmedOrderStatusValidator extends OrderStatusValidatorTemplate { - @Override - public List next() { - return List.of(OrderStatus.PREPARING); - } -} diff --git a/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/OrderStatusValidatorTemplate.java b/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/OrderStatusValidatorTemplate.java index 526a156d..48b832ba 100644 --- a/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/OrderStatusValidatorTemplate.java +++ b/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/OrderStatusValidatorTemplate.java @@ -14,11 +14,9 @@ public abstract class OrderStatusValidatorTemplate implements OrderStatusValidat public void validate(OrderStatus status) { var allowedNextStatus = next(); if (!allowedNextStatus.contains(status)) { - throw new BadRequestException(format("Status %s is a invalid next state!", status.name())); + throw new BadRequestException(format("Status %s is in a invalid next state!", status.name())); } - log.info("status {} is valid!", status.name()); - } public abstract List next(); diff --git a/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/PendingOrderStatusValidator.java b/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/PendingOrderStatusValidator.java index 3a224ceb..ddada7d6 100644 --- a/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/PendingOrderStatusValidator.java +++ b/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/PendingOrderStatusValidator.java @@ -8,6 +8,6 @@ public class PendingOrderStatusValidator extends OrderStatusValidatorTemplate { @Override public List next() { - return List.of(OrderStatus.CONFIRMED, OrderStatus.PENDING, OrderStatus.CANCELED); + return List.of(OrderStatus.PREPARING, OrderStatus.PENDING, OrderStatus.CANCELED); } } diff --git a/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/ReceivedOrderStatusValidator.java b/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/ReceivedOrderStatusValidator.java index 6de5427f..c94487a2 100644 --- a/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/ReceivedOrderStatusValidator.java +++ b/src/main/java/com/fiap/tc/core/domain/behavior/order/status/validator/ReceivedOrderStatusValidator.java @@ -8,6 +8,6 @@ public class ReceivedOrderStatusValidator extends OrderStatusValidatorTemplate { @Override public List next() { - return List.of(OrderStatus.CONFIRMED, OrderStatus.PENDING, OrderStatus.CANCELED); + return List.of(OrderStatus.PREPARING, OrderStatus.PENDING, OrderStatus.CANCELED); } } diff --git a/src/main/java/com/fiap/tc/core/domain/exception/handler/ExceptionAdvice.java b/src/main/java/com/fiap/tc/core/domain/exception/handler/ExceptionAdvice.java index a368c4b8..20193817 100644 --- a/src/main/java/com/fiap/tc/core/domain/exception/handler/ExceptionAdvice.java +++ b/src/main/java/com/fiap/tc/core/domain/exception/handler/ExceptionAdvice.java @@ -4,14 +4,10 @@ import com.fiap.tc.core.domain.exception.BadRequestException; import com.fiap.tc.core.domain.exception.NotFoundException; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.MessageSource; -import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.security.access.AccessDeniedException; +import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; @@ -19,10 +15,10 @@ import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; -import java.util.List; import java.util.NoSuchElementException; +import java.util.Set; +import java.util.stream.Collectors; -import static java.util.stream.Collectors.toList; import static org.springframework.http.HttpStatus.*; import static org.springframework.http.ResponseEntity.status; @@ -30,9 +26,6 @@ @Slf4j public class ExceptionAdvice extends ResponseEntityExceptionHandler { - @Autowired - private MessageSource messageSource; - @ExceptionHandler(value = Exception.class) public ResponseEntity defaultExceptionHandler(Exception e) { @@ -40,36 +33,20 @@ public ResponseEntity defaultExceptionHandler(Exception e) { DefaultResponse response = new DefaultResponse(); response.setStatus("ERROR"); - response.setMessage("Ocorreu um erro inesperado!"); + response.setMessage("Unexpected error!"); return status(INTERNAL_SERVER_ERROR).body(response); } - @Override - protected ResponseEntity handleHttpMessageNotReadable(HttpMessageNotReadableException ex, - HttpHeaders headers, HttpStatus status, WebRequest request) { - - String mensagemUsuario = messageSource.getMessage("mensagem.invalida", null, LocaleContextHolder.getLocale()); - - DefaultResponse response = new DefaultResponse(); - response.setStatus(BAD_REQUEST.name()); - response.setMessage(mensagemUsuario); - - return status(BAD_REQUEST).body(response); - } - @Override protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpHeaders headers, HttpStatus status, WebRequest request) { log.warn(e.getMessage(), e); - List messages = e.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage) - .collect(toList()); - DefaultResponse response = new DefaultResponse(); response.setStatus(BAD_REQUEST.name()); - response.getMessages().addAll(messages); + response.getMessages().addAll(getValidationMessageErrors(e)); return status(BAD_REQUEST).body(response); } @@ -99,19 +76,21 @@ public ResponseEntity badRequestExceptionHandler(RuntimeExcepti return status(BAD_REQUEST).body(response); } - @ExceptionHandler(value = AccessDeniedException.class) - public ResponseEntity acccessDeniedExceptionHandler(AccessDeniedException e) { - log.warn(e.getMessage(), e); + private Set getValidationMessageErrors(MethodArgumentNotValidException e) { + var messages = e.getBindingResult().getAllErrors().stream() + .map(ObjectError::getDefaultMessage) + .collect(Collectors.toSet()); - String mensagemUsuario = messageSource.getMessage("recurso.operacao-nao-permitida", null, - LocaleContextHolder.getLocale()); - DefaultResponse response = new DefaultResponse(); - response.setStatus(UNAUTHORIZED.name()); - response.setMessage(mensagemUsuario); + var fields = e.getBindingResult().getFieldErrors().stream() + .map(FieldError::getField).toList(); + + return fields.stream().flatMap(field -> messages.stream() + .map(message -> field.concat(": ").concat(message))) + .collect(Collectors.toSet()); + - return status(UNAUTHORIZED).body(response); } } diff --git a/src/main/java/com/fiap/tc/core/domain/model/enums/OrderStatus.java b/src/main/java/com/fiap/tc/core/domain/model/enums/OrderStatus.java index 5c0f1f5d..c4957ccf 100644 --- a/src/main/java/com/fiap/tc/core/domain/model/enums/OrderStatus.java +++ b/src/main/java/com/fiap/tc/core/domain/model/enums/OrderStatus.java @@ -8,7 +8,6 @@ @Getter public enum OrderStatus { RECEIVED("order received", new ReceivedOrderStatusValidator()), - CONFIRMED("confirmed order with payment", new ConfirmedOrderStatusValidator()), PENDING("pending payment order", new PendingOrderStatusValidator()), PREPARING("order being prepared", new PreparingOrderStatusValidator()), READY("order ready", new ReadyOrderStatusValidator()), diff --git a/src/main/java/com/fiap/tc/core/domain/model/enums/PaymentResult.java b/src/main/java/com/fiap/tc/core/domain/model/enums/PaymentResult.java index 6343d314..2ccd30bb 100644 --- a/src/main/java/com/fiap/tc/core/domain/model/enums/PaymentResult.java +++ b/src/main/java/com/fiap/tc/core/domain/model/enums/PaymentResult.java @@ -6,8 +6,8 @@ @AllArgsConstructor @Getter public enum PaymentResult { - SUCCESS("payment confirmed", OrderStatus.CONFIRMED), - ERROR("payment pending", OrderStatus.PENDING); + SUCCESS("order payed", OrderStatus.PREPARING), + ERROR("order pending", OrderStatus.PENDING); private final String description; private final OrderStatus orderStatus; diff --git a/src/main/java/com/fiap/tc/core/domain/requests/OrderItemRequest.java b/src/main/java/com/fiap/tc/core/domain/requests/OrderItemRequest.java index 3406bd64..1c5cf07e 100644 --- a/src/main/java/com/fiap/tc/core/domain/requests/OrderItemRequest.java +++ b/src/main/java/com/fiap/tc/core/domain/requests/OrderItemRequest.java @@ -4,11 +4,13 @@ import lombok.Data; import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; import java.util.UUID; @Data public class OrderItemRequest { + @NotNull @ApiModelProperty( value = "Order Product Id", required = true, @@ -17,6 +19,7 @@ public class OrderItemRequest { ) private UUID idProduct; + @NotNull @Min(value = 1, message = "Invalid quantity") @ApiModelProperty( value = "Order quantity", diff --git a/src/main/java/com/fiap/tc/core/domain/requests/OrderRequest.java b/src/main/java/com/fiap/tc/core/domain/requests/OrderRequest.java index 3c3dccb7..ca36c7ff 100644 --- a/src/main/java/com/fiap/tc/core/domain/requests/OrderRequest.java +++ b/src/main/java/com/fiap/tc/core/domain/requests/OrderRequest.java @@ -3,11 +3,15 @@ import lombok.Data; import javax.validation.Valid; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; import java.util.List; import java.util.UUID; @Data public class OrderRequest { + @NotNull + @NotEmpty @Valid private List orderItems; diff --git a/src/main/java/com/fiap/tc/core/domain/requests/OrderStatusRequest.java b/src/main/java/com/fiap/tc/core/domain/requests/OrderStatusRequest.java index 5c388639..31eedc03 100644 --- a/src/main/java/com/fiap/tc/core/domain/requests/OrderStatusRequest.java +++ b/src/main/java/com/fiap/tc/core/domain/requests/OrderStatusRequest.java @@ -3,10 +3,13 @@ import com.fiap.tc.core.domain.model.enums.OrderStatus; import lombok.Data; +import javax.validation.constraints.NotNull; import java.util.UUID; @Data public class OrderStatusRequest { + @NotNull private UUID id; + @NotNull private OrderStatus status; } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d499833d..89c90f84 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -43,8 +43,6 @@ spring: properties: hibernate: dialect: org.hibernate.dialect.PostgreSQLDialect - # hbm2ddl.auto: create - # hbm2ddl.export_schema: true show_sql: true format_sql: true enable_lazy_load_no_trans: true @@ -62,5 +60,6 @@ app: name: tc_client secret: $2a$12$aNBFov6o75DX51iVqd5mM.Z5S.Wi7xHMS3OzcU5386TWRi28Y691W signKey: tech-challenge - + tokenExpirationTime: 3600 + refreshTokenExpirationTime: 43200 diff --git a/src/test/java/com/fiap/tc/adapter/repository/output/CategoryOutputAdapterTests.java b/src/test/java/com/fiap/tc/adapter/repository/output/CategoryOutputAdapterTests.java new file mode 100644 index 00000000..e5cd3a74 --- /dev/null +++ b/src/test/java/com/fiap/tc/adapter/repository/output/CategoryOutputAdapterTests.java @@ -0,0 +1,125 @@ +package com.fiap.tc.adapter.repository.output; + +import br.com.six2six.fixturefactory.Fixture; +import com.fiap.tc.adapter.repository.CategoryRepository; +import com.fiap.tc.adapter.repository.entity.CategoryEntity; +import com.fiap.tc.core.domain.exception.NotFoundException; +import com.fiap.tc.core.domain.requests.CategoryRequest; +import com.fiap.tc.util.BaseTest; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class CategoryOutputAdapterTests extends BaseTest { + + public static final UUID RANDOM_UUID = UUID.randomUUID(); + + @Mock + private CategoryRepository categoryRepository; + + @InjectMocks + private CategoryOutputAdapter categoryOutputAdapter; + + private CategoryEntity categoryEntity; + + private CategoryRequest request; + + private Pageable pageable; + + @BeforeEach + public void setUp() { + categoryEntity = Fixture.from(CategoryEntity.class).gimme("valid"); + request = Fixture.from(CategoryRequest.class).gimme("valid"); + pageable = Mockito.mock(Pageable.class); + } + + @Test + public void deleteTest() { + + when(categoryRepository.findByUuid(RANDOM_UUID)).thenReturn(Optional.of(categoryEntity)); + + categoryOutputAdapter.delete(RANDOM_UUID); + + verify(categoryRepository).delete(any()); + } + + @Test + public void loadTest() { + + when(categoryRepository.findByUuid(RANDOM_UUID)).thenReturn(Optional.of(categoryEntity)); + + var category = categoryOutputAdapter.load(RANDOM_UUID); + + assertNotNull(category); + verify(categoryRepository).findByUuid(RANDOM_UUID); + } + + + @Test + public void listTest() { + final var categoryEntities = new PageImpl(List.of(categoryEntity)); + when(categoryRepository.findAll(Mockito.any(Pageable.class))).thenReturn(categoryEntities); + + var categories = categoryOutputAdapter.list(pageable); + + assertEquals(1, categories.getSize()); + verify(categoryRepository).findAll(Mockito.any(Pageable.class)); + } + + @Test + public void loadNotFoundTest() { + + when(categoryRepository.findByUuid(RANDOM_UUID)).thenReturn(Optional.empty()); + + var assertThrows = Assertions.assertThrows(NotFoundException.class, + () -> categoryOutputAdapter.load(RANDOM_UUID)); + + assertTrue(assertThrows.getMessage().contains("not found")); + } + + @Test + public void saveTest() { + + when(categoryRepository.findByName(request.getName())).thenReturn(Optional.empty()); + when(categoryRepository.save(Mockito.any())).thenReturn(categoryEntity); + + var category = categoryOutputAdapter.saveOrUpdate(request.getName(), + request.getDescription(), request.getActive()); + + assertNotNull(category); + verify(categoryRepository).findByName(request.getName()); + verify(categoryRepository).save(Mockito.any()); + } + + @Test + public void updateTest() { + + when(categoryRepository.findByName(request.getName())).thenReturn(Optional.of(categoryEntity)); + when(categoryRepository.save(categoryEntity)).thenReturn(categoryEntity); + + var category = categoryOutputAdapter.saveOrUpdate(request.getName(), + request.getDescription(), request.getActive()); + + assertNotNull(category); + verify(categoryRepository).findByName(request.getName()); + verify(categoryRepository).save(Mockito.any()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/fiap/tc/core/usecase/category/DeleteCategoryUseCaseTest.java b/src/test/java/com/fiap/tc/core/usecase/category/DeleteCategoryUseCaseTest.java new file mode 100644 index 00000000..ecc7e84d --- /dev/null +++ b/src/test/java/com/fiap/tc/core/usecase/category/DeleteCategoryUseCaseTest.java @@ -0,0 +1,30 @@ +package com.fiap.tc.core.usecase.category; + +import com.fiap.tc.core.port.out.category.DeleteCategoryOutputPort; +import com.fiap.tc.util.BaseTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith(MockitoExtension.class) +public class DeleteCategoryUseCaseTest extends BaseTest { + + @Mock + private DeleteCategoryOutputPort deleteCategoryOutputPort; + @InjectMocks + private DeleteCategoryUseCase deleteCategoryUseCase; + + @Test + public void deleteCategoryTest() { + deleteCategoryUseCase.delete(UUID.randomUUID()); + Mockito.verify(deleteCategoryOutputPort).delete(Mockito.any()); + } + +} \ No newline at end of file diff --git a/src/test/java/com/fiap/tc/core/usecase/category/ListCategoriesUseCaseTest.java b/src/test/java/com/fiap/tc/core/usecase/category/ListCategoriesUseCaseTest.java new file mode 100644 index 00000000..62613ba9 --- /dev/null +++ b/src/test/java/com/fiap/tc/core/usecase/category/ListCategoriesUseCaseTest.java @@ -0,0 +1,28 @@ +package com.fiap.tc.core.usecase.category; + +import com.fiap.tc.core.port.out.category.ListCategoriesOutputPort; +import com.fiap.tc.util.BaseTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +public class ListCategoriesUseCaseTest extends BaseTest { + + @Mock + private ListCategoriesOutputPort listCategoriesOutputPort; + + @InjectMocks + private ListCategoriesUseCase listCategoriesUseCase; + + @Test + public void listCategoriesTest() { + listCategoriesUseCase.list(Mockito.any()); + verify(listCategoriesOutputPort).list(Mockito.any()); + } +} diff --git a/src/test/java/com/fiap/tc/core/usecase/category/LoadCategoryUseCaseTest.java b/src/test/java/com/fiap/tc/core/usecase/category/LoadCategoryUseCaseTest.java new file mode 100644 index 00000000..f49653d1 --- /dev/null +++ b/src/test/java/com/fiap/tc/core/usecase/category/LoadCategoryUseCaseTest.java @@ -0,0 +1,47 @@ +package com.fiap.tc.core.usecase.category; + +import br.com.six2six.fixturefactory.Fixture; +import com.fiap.tc.core.domain.model.Category; +import com.fiap.tc.core.port.out.category.LoadCategoryOutputPort; +import com.fiap.tc.util.BaseTest; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.UUID; + +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class LoadCategoryUseCaseTest extends BaseTest { + + @Mock + private LoadCategoryOutputPort loadCategoryOutputPort; + + @InjectMocks + private LoadCategoryUseCase loadCategoryUseCase; + + private Category category; + + @BeforeEach + public void setUp() { + category = Fixture.from(Category.class).gimme("valid"); + } + + + @Test + public void loadCategoryTest() { + when(loadCategoryOutputPort.load(Mockito.any())).thenReturn(category); + + var categoryResult = loadCategoryUseCase.load(UUID.randomUUID()); + Assertions.assertEquals(category, categoryResult); + + } + + +} \ No newline at end of file diff --git a/src/test/java/com/fiap/tc/core/usecase/category/RegisterCategoryUseCaseTest.java b/src/test/java/com/fiap/tc/core/usecase/category/RegisterCategoryUseCaseTest.java new file mode 100644 index 00000000..783156a6 --- /dev/null +++ b/src/test/java/com/fiap/tc/core/usecase/category/RegisterCategoryUseCaseTest.java @@ -0,0 +1,50 @@ +package com.fiap.tc.core.usecase.category; + +import br.com.six2six.fixturefactory.Fixture; +import com.fiap.tc.core.domain.model.Category; +import com.fiap.tc.core.domain.requests.CategoryRequest; +import com.fiap.tc.core.port.out.category.SaveCategoryOutputPort; +import com.fiap.tc.util.BaseTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class RegisterCategoryUseCaseTest extends BaseTest { + + @Mock + private SaveCategoryOutputPort saveCategoryOutputPort; + + @InjectMocks + private RegisterCategoryUseCase registerCategoryUseCase; + + private Category category; + private CategoryRequest categoryRequest; + + @BeforeEach + public void setUp() { + category = Fixture.from(Category.class).gimme("valid"); + categoryRequest = Fixture.from(CategoryRequest.class).gimme("valid"); + } + + @Test + public void registerCategoryTest() { + when(saveCategoryOutputPort.saveOrUpdate(categoryRequest.getName(), categoryRequest.getDescription(), + categoryRequest.getActive())).thenReturn(category); + + var categoryResult = registerCategoryUseCase.register(categoryRequest); + + assertEquals(category, categoryResult); + verify(saveCategoryOutputPort).saveOrUpdate(categoryRequest.getName(), + categoryRequest.getDescription(), categoryRequest.getActive()); + + } + +} \ No newline at end of file diff --git a/src/test/java/com/fiap/tc/jpa/ddl/GenerateSchemaTest.java b/src/test/java/com/fiap/tc/jpa/ddl/GenerateSchemaTest.java index eb582528..8897b9b6 100644 --- a/src/test/java/com/fiap/tc/jpa/ddl/GenerateSchemaTest.java +++ b/src/test/java/com/fiap/tc/jpa/ddl/GenerateSchemaTest.java @@ -7,6 +7,7 @@ import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaExport.Action; import org.hibernate.tool.schema.TargetType; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; @@ -17,26 +18,11 @@ import java.util.Map; import java.util.Set; -import static org.junit.Assert.assertTrue; - @Slf4j public class GenerateSchemaTest { @Test public void generate() { - Map settings = new HashMap<>(); - - /* - * settings.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect"); - * settings.put("hibernate.hbm2ddl.auto", "create"); - * settings.put("hibernate.dialect.storage_engine", "innodb"); - * settings.put("hibernate.physical_naming_strategy", - * "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy"); - */ - - settings.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"); - settings.put("hibernate.hbm2ddl.auto", "create"); - settings.put("hibernate.physical_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy"); - + final var settings = getSettings(); MetadataSources metadataSources = new MetadataSources( new StandardServiceRegistryBuilder() @@ -44,7 +30,8 @@ public void generate() { .build() ); - Reflections reflections = new Reflections("com.fiap.tc.adapter.repository.entity", new SubTypesScanner(false)); + Reflections reflections = new Reflections("com.fiap.tc.adapter.repository.entity", + new SubTypesScanner(false)); Set entityNames = reflections.getAllTypes(); entityNames.forEach(metadataSources::addAnnotatedClassName); @@ -69,8 +56,17 @@ public void generate() { schemaExport.execute(EnumSet.of(TargetType.SCRIPT), Action.CREATE, metadata); - assertTrue(outputFile.exists()); + Assertions.assertTrue(outputFile.exists()); log.info("Finished"); } + + private Map getSettings() { + Map settings = new HashMap<>(); + settings.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"); + settings.put("hibernate.hbm2ddl.auto", "create"); + settings.put("hibernate.physical_naming_strategy", + "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy"); + return settings; + } } diff --git a/src/test/java/com/fiap/tc/templates/CategoryTemplates.java b/src/test/java/com/fiap/tc/templates/CategoryTemplates.java new file mode 100644 index 00000000..12b80cec --- /dev/null +++ b/src/test/java/com/fiap/tc/templates/CategoryTemplates.java @@ -0,0 +1,55 @@ +package com.fiap.tc.templates; + +import br.com.six2six.fixturefactory.Fixture; +import br.com.six2six.fixturefactory.Rule; +import br.com.six2six.fixturefactory.loader.TemplateLoader; +import com.fiap.tc.adapter.repository.entity.CategoryEntity; +import com.fiap.tc.adapter.repository.entity.embeddable.Audit; +import com.fiap.tc.core.domain.model.Category; +import com.fiap.tc.core.domain.requests.CategoryRequest; + +import java.time.LocalDateTime; +import java.util.UUID; + +public class CategoryTemplates implements TemplateLoader { + + @Override + public void load() { + + Fixture.of(CategoryEntity.class).addTemplate("valid", new Rule() { + { + add("id", random(Integer.class, range(1, 100))); + add("uuid", UUID.randomUUID()); + add("name", random("Sandwich", "Sides", "Drink", "Dessert")); + add("description", random("Sandwich", "Sides", "Drink", "Dessert")); + add("audit", one(Audit.class, "valid")); + } + }); + + Fixture.of(Category.class).addTemplate("valid", new Rule() { + { + add("id", UUID.randomUUID()); + add("name", random("Sandwich", "Sides", "Drink", "Dessert")); + add("description", random("Sandwich", "Sides", "Drink", "Dessert")); + add("active", true); + } + }); + + Fixture.of(CategoryRequest.class).addTemplate("valid", new Rule() { + { + add("name", random("Sandwich", "Sides", "Drink", "Dessert")); + add("description", random("Sandwich", "Sides", "Drink", "Dessert")); + add("active", true); + } + }); + + Fixture.of(Audit.class).addTemplate("valid", new Rule() { + { + add("registerDate", LocalDateTime.now()); + add("active", true); + } + }); + + } + +} diff --git a/src/test/java/com/fiap/tc/templates/LoginTemplates.java b/src/test/java/com/fiap/tc/templates/LoginTemplates.java index 15ccb7f3..34c17e91 100644 --- a/src/test/java/com/fiap/tc/templates/LoginTemplates.java +++ b/src/test/java/com/fiap/tc/templates/LoginTemplates.java @@ -17,9 +17,9 @@ public void load() { { add("id", random(Long.class, range(1, 100))); add("uuid", UUID.randomUUID()); - add("login", random("myller@teste.com", "dener@teste.com")); - add("nome", random("Myller", "Dener")); - add("email", random("myller@teste.com", "dener@teste.com")); + add("login", random("myller@teste.com")); + add("nome", random("Myller")); + add("email", random("myller@teste.com")); add("senha", RandomStringUtils.randomAlphabetic(32)); add("senhaAes", RandomStringUtils.randomAlphabetic(32));