diff --git a/core/src/main/java/greencity/exception/handler/CustomExceptionHandler.java b/core/src/main/java/greencity/exception/handler/CustomExceptionHandler.java index d55362562..cb1e83937 100644 --- a/core/src/main/java/greencity/exception/handler/CustomExceptionHandler.java +++ b/core/src/main/java/greencity/exception/handler/CustomExceptionHandler.java @@ -49,7 +49,8 @@ public class CustomExceptionHandler extends ResponseEntityExceptionHandler { ConstraintViolationException.class, MappingException.class, CourierAlreadyExists.class, - ServiceAlreadyExistsException.class + ServiceAlreadyExistsException.class, + IllegalArgumentException.class }) public final ResponseEntity handleBadRequestException(WebRequest request) { ExceptionResponce exceptionResponse = new ExceptionResponce(getErrorAttributes(request)); diff --git a/service-api/src/main/java/greencity/constant/ErrorMessage.java b/service-api/src/main/java/greencity/constant/ErrorMessage.java index 2c1eaf212..eddaa72d1 100644 --- a/service-api/src/main/java/greencity/constant/ErrorMessage.java +++ b/service-api/src/main/java/greencity/constant/ErrorMessage.java @@ -33,6 +33,7 @@ public final class ErrorMessage { public static final String ORDER_STATUS_NOT_FOUND = "Order status not found"; public static final String ORDER_PAYMENT_STATUS_NOT_FOUND = "Order payment status not found"; public static final String FILE_NOT_SAVED = "File hasn't been saved"; + public static final String FILE_IS_NULL = "File equals null"; public static final String EMPLOYEE_NOT_FOUND = "Employee with current id doesn't exist: "; public static final String EMPLOYEE_WITH_UUID_NOT_FOUND = "Employee with current uuid doesn't exist: "; public static final String CURRENT_PHONE_NUMBER_ALREADY_EXISTS = "Employee with this phone number already exists: "; diff --git a/service/src/main/java/greencity/service/ubs/AzureCloudStorageService.java b/service/src/main/java/greencity/service/ubs/AzureCloudStorageService.java index eef5e3163..c105bffbd 100644 --- a/service/src/main/java/greencity/service/ubs/AzureCloudStorageService.java +++ b/service/src/main/java/greencity/service/ubs/AzureCloudStorageService.java @@ -4,6 +4,7 @@ import com.azure.storage.blob.BlobContainerClient; import com.azure.storage.blob.BlobServiceClient; import com.azure.storage.blob.BlobServiceClientBuilder; +import com.google.common.annotations.VisibleForTesting; import greencity.constant.ErrorMessage; import greencity.exceptions.BadRequestException; import greencity.exceptions.image.FileNotSavedException; @@ -40,6 +41,9 @@ public AzureCloudStorageService(@Autowired PropertyResolver propertyResolver) { */ @Override public String upload(MultipartFile multipartFile) { + if (multipartFile == null) { + throw new IllegalArgumentException(ErrorMessage.FILE_IS_NULL); + } final String blob = UUID.randomUUID().toString(); BlobClient client = containerClient() .getBlobClient(blob + multipartFile.getOriginalFilename()); @@ -65,7 +69,8 @@ public void delete(String url) { } } - private BlobContainerClient containerClient() { + @VisibleForTesting + BlobContainerClient containerClient() { BlobServiceClient serviceClient = new BlobServiceClientBuilder() .connectionString(connectionString).buildClient(); return serviceClient.getBlobContainerClient(containerName); diff --git a/service/src/main/java/greencity/service/ubs/ValuesForUserTableServiceImpl.java b/service/src/main/java/greencity/service/ubs/ValuesForUserTableServiceImpl.java index c95a70d96..023447c74 100644 --- a/service/src/main/java/greencity/service/ubs/ValuesForUserTableServiceImpl.java +++ b/service/src/main/java/greencity/service/ubs/ValuesForUserTableServiceImpl.java @@ -1,5 +1,6 @@ package greencity.service.ubs; +import com.google.common.annotations.VisibleForTesting; import greencity.dto.order.UserWithSomeOrderDetailDto; import greencity.dto.pageble.PageableDto; import greencity.enums.SortingOrder; @@ -50,7 +51,8 @@ public PageableDto getAllFields(CustomerPage page, S users.getPageable().getPageNumber(), users.getTotalPages()); } - private UserWithSomeOrderDetailDto mapToDto(User u) { + @VisibleForTesting + UserWithSomeOrderDetailDto mapToDto(User u) { final UserWithSomeOrderDetailDto allFieldsFromTableDto = new UserWithSomeOrderDetailDto(); StringBuilder name = new StringBuilder(); allFieldsFromTableDto.setUserId(u.getId()); diff --git a/service/src/test/java/greencity/service/ubs/AzureCloudStorageServiceTest.java b/service/src/test/java/greencity/service/ubs/AzureCloudStorageServiceTest.java new file mode 100644 index 000000000..5fd246b63 --- /dev/null +++ b/service/src/test/java/greencity/service/ubs/AzureCloudStorageServiceTest.java @@ -0,0 +1,149 @@ +package greencity.service.ubs; + +import com.azure.storage.blob.BlobClient; +import com.azure.storage.blob.BlobContainerClient; +import greencity.constant.ErrorMessage; +import greencity.exceptions.BadRequestException; +import greencity.exceptions.image.FileNotSavedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.core.env.PropertyResolver; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; + +@ExtendWith(MockitoExtension.class) +class AzureCloudStorageServiceTest { + + private final String connectionString = + "DefaultEndpointsProtocol=https;AccountName=2fdsgd;AccountKey=qV2VLads==;EndpointSuffix=core.windows.net"; + + private final String containerName = "container"; + + @Mock + private PropertyResolver propertyResolver; + + private AzureCloudStorageService azureCloudStorageService; + + @Mock + private BlobContainerClient containerClient; + + @Mock + private BlobClient blobClient; + + @BeforeEach + void setUp() { + MockEnvironment mockEnvironment = new MockEnvironment(); + mockEnvironment.setProperty("azure.connection.string", connectionString); + mockEnvironment.setProperty("azure.container.name", containerName); + propertyResolver = mockEnvironment; + azureCloudStorageService = spy(new AzureCloudStorageService(propertyResolver)); + } + + @Test + void checkUpload() { + MultipartFile multipartFile = new MockMultipartFile("Image", "Image".getBytes(StandardCharsets.UTF_8)); + doReturn(containerClient).when(azureCloudStorageService).containerClient(); + when(containerClient.getBlobClient(anyString())).thenReturn(blobClient); + doReturn("blobUrl").when(blobClient).getBlobUrl(); + azureCloudStorageService.upload(multipartFile); + assertNotNull(azureCloudStorageService.getConnectionString()); + assertNotNull(azureCloudStorageService.getContainerName()); + assertEquals(connectionString, azureCloudStorageService.getConnectionString()); + assertEquals(containerName, azureCloudStorageService.getContainerName()); + verify(containerClient).getBlobClient(anyString()); + verify(blobClient).upload(any(InputStream.class), anyLong()); + verify(blobClient).getBlobUrl(); + } + + @Test + void checkDelete() { + doReturn(containerClient).when(azureCloudStorageService).containerClient(); + when(containerClient.getBlobClient(anyString())).thenReturn(blobClient); + when(blobClient.exists()).thenReturn(true); + doNothing().when(blobClient).delete(); + azureCloudStorageService.delete("url/somepath/somefile.txt"); + assertNotNull(azureCloudStorageService.getConnectionString()); + assertNotNull(azureCloudStorageService.getContainerName()); + verify(containerClient).getBlobClient(anyString()); + assertEquals(true, blobClient.exists()); + verify(blobClient).delete(); + } + + @Test + void checkDeleteIfClientNull() { + doReturn(containerClient).when(azureCloudStorageService).containerClient(); + when(containerClient.getBlobClient(anyString())).thenReturn(blobClient); + when(blobClient.exists()).thenReturn(null); + azureCloudStorageService.delete("url/somepath/somefile.txt"); + verify(blobClient, never()).delete(); + } + + @Test + void checkDeleteIfClientFalse() { + doReturn(containerClient).when(azureCloudStorageService).containerClient(); + when(containerClient.getBlobClient(anyString())).thenReturn(blobClient); + when(blobClient.exists()).thenReturn(false); + azureCloudStorageService.delete("url/somepath/somefile.txt"); + verify(blobClient, never()).delete(); + } + + @Test + void checkUploadThrowsException() { + doReturn(containerClient).when(azureCloudStorageService).containerClient(); + when(containerClient.getBlobClient(anyString())).thenReturn(blobClient); + doAnswer(invocation -> { + throw new IOException(); + }).when(blobClient).upload(any(InputStream.class), anyLong()); + MultipartFile multipartFile = new MockMultipartFile("Image", "Image".getBytes(StandardCharsets.UTF_8)); + FileNotSavedException ex = + assertThrows(FileNotSavedException.class, () -> azureCloudStorageService.upload(multipartFile)); + assertEquals(ErrorMessage.FILE_NOT_SAVED, ex.getMessage()); + } + + @Test + void checkUploadNullImage() { + MultipartFile multipartFile = null; + IllegalArgumentException ex = + assertThrows(IllegalArgumentException.class, () -> azureCloudStorageService.upload(multipartFile)); + assertEquals(ErrorMessage.FILE_IS_NULL, ex.getMessage()); + } + + @Test + void checkInvalidConnectionString() { + azureCloudStorageService = new AzureCloudStorageService(new MockEnvironment()); + assertThrows(IllegalArgumentException.class, () -> azureCloudStorageService.containerClient()); + } + + @Test + void checkContainerClient() { + BlobContainerClient client = azureCloudStorageService.containerClient(); + assertEquals(containerName, client.getBlobContainerName()); + } + + @Test + void checkDeleteThrowsException() { + String url = "aa#26#1"; + BadRequestException ex = assertThrows(BadRequestException.class, () -> azureCloudStorageService.delete(url)); + assertEquals(ErrorMessage.PARSING_URL_FAILED + url, ex.getMessage()); + } +} \ No newline at end of file diff --git a/service/src/test/java/greencity/service/ubs/ValuesForUserTableServiceImplTest.java b/service/src/test/java/greencity/service/ubs/ValuesForUserTableServiceImplTest.java new file mode 100644 index 000000000..d5085274f --- /dev/null +++ b/service/src/test/java/greencity/service/ubs/ValuesForUserTableServiceImplTest.java @@ -0,0 +1,93 @@ +package greencity.service.ubs; + +import greencity.ModelUtils; +import greencity.constant.ErrorMessage; +import greencity.dto.order.UserWithSomeOrderDetailDto; +import greencity.dto.pageble.PageableDto; +import greencity.entity.user.User; +import greencity.entity.user.employee.Employee; +import greencity.enums.SortingOrder; +import greencity.filters.CustomerPage; +import greencity.filters.UserFilterCriteria; +import greencity.repository.EmployeeRepository; +import greencity.repository.UserRepository; +import greencity.repository.UserTableRepo; +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.PageRequest; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; + +import javax.persistence.EntityNotFoundException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ValuesForUserTableServiceImplTest { + + @Mock + private UserRepository userRepository; + + @Mock + private UserTableRepo userTableRepo; + + @Mock + private EmployeeRepository employeeRepository; + + @InjectMocks + private ValuesForUserTableServiceImpl valuesForUserTableService; + + @Test + void checkGetAllFields() { + User user = User.builder() + .orders(new ArrayList<>()) + .violations(5) + .currentPoints(8) + .build(); + Pageable pageable = PageRequest.of(1, 1); + Employee employee = ModelUtils.getEmployee(); + List tariffsInfo = List.of(1L, 2L, 3L); + UserWithSomeOrderDetailDto userWithSomeOrderDetail = valuesForUserTableService.mapToDto(user); + when(employeeRepository.findByEmail(anyString())).thenReturn(Optional.of(employee)); + when(employeeRepository.findTariffsInfoForEmployee(anyLong())).thenReturn(tariffsInfo); + when(userRepository.getAllUsersByTariffsInfoId(anyLong())).thenReturn(tariffsInfo); + when(userTableRepo.findAll(any(UserFilterCriteria.class), anyString(), any(SortingOrder.class), + any(CustomerPage.class), Mockito.anyList())).thenReturn(new PageImpl<>(List.of(user), pageable, 1L)); + PageableDto actual = valuesForUserTableService.getAllFields(new CustomerPage(), "column", SortingOrder.ASC, + new UserFilterCriteria(), + employee.getEmail()); + verify(employeeRepository).findByEmail(anyString()); + verify(employeeRepository).findTariffsInfoForEmployee(anyLong()); + verify(userRepository, times(tariffsInfo.size())).getAllUsersByTariffsInfoId(anyLong()); + verify(userTableRepo).findAll(any(UserFilterCriteria.class), anyString(), any(SortingOrder.class), + any(CustomerPage.class), Mockito.anyList()); + assertEquals(2L, actual.getTotalElements()); + assertEquals(2, actual.getTotalPages()); + assertEquals(List.of(userWithSomeOrderDetail), actual.getPage()); + } + + @Test + void checkGetAllFieldsIfEmployeeIsNull() { + CustomerPage customerPage = new CustomerPage(); + UserFilterCriteria userFilterCriteria = new UserFilterCriteria(); + EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> valuesForUserTableService + .getAllFields(customerPage, "column", SortingOrder.ASC, userFilterCriteria, "email")); + assertEquals(ErrorMessage.EMPLOYEE_NOT_FOUND, ex.getMessage()); + } + +} \ No newline at end of file diff --git a/service/src/test/java/greencity/service/ubs/ViolationServiceImplTest.java b/service/src/test/java/greencity/service/ubs/ViolationServiceImplTest.java index 3b4173b87..87a41a65a 100644 --- a/service/src/test/java/greencity/service/ubs/ViolationServiceImplTest.java +++ b/service/src/test/java/greencity/service/ubs/ViolationServiceImplTest.java @@ -3,8 +3,10 @@ import java.util.List; import java.util.Optional; +import greencity.constant.ErrorMessage; +import greencity.entity.order.TariffsInfo; +import greencity.entity.user.employee.Employee; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -33,8 +35,11 @@ import greencity.repository.ViolationRepository; import greencity.service.notification.NotificationServiceImpl; +import javax.persistence.EntityNotFoundException; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyLong; import static org.mockito.Mockito.anyString; @@ -105,23 +110,30 @@ void deleteViolationFromOrderByOrderId() { } @Test - @Disabled void checkAddUserViolation() { + Employee employee = ModelUtils.getEmployee(); + List tariffsInfos = List.of(1L, 2L, 3L); + TariffsInfo tariffsInfo = ModelUtils.getTariffsInfo(); User user = ModelUtils.getTestUser(); Order order = user.getOrders().get(0); + order.setTariffsInfo(tariffsInfo); order.setUser(user); AddingViolationsToUserDto add = ModelUtils.getAddingViolationsToUserDto(); add.setOrderID(order.getId()); when(orderRepository.findById(order.getId())).thenReturn(Optional.ofNullable(order)); - when(userRepository.findUserByUuid("abc")).thenReturn(Optional.of(user)); when(userRepository.countTotalUsersViolations(1L)).thenReturn(1); + when(employeeRepository.findByEmail(anyString())).thenReturn(Optional.ofNullable(employee)); + when(employeeRepository.findTariffsInfoForEmployee(anyLong())).thenReturn(tariffsInfos); violationService.addUserViolation(add, new MultipartFile[2], "abc"); + verify(orderRepository, times(2)).findById(anyLong()); + verify(userRepository).countTotalUsersViolations(anyLong()); + verify(employeeRepository).findByEmail(anyString()); + verify(employeeRepository).findTariffsInfoForEmployee(anyLong()); assertEquals(1, user.getViolations()); } @Test - @Disabled void checkAddUserViolationThrowsException() { User user = ModelUtils.getTestUser(); Order order = user.getOrders().get(0); @@ -129,11 +141,11 @@ void checkAddUserViolationThrowsException() { AddingViolationsToUserDto add = ModelUtils.getAddingViolationsToUserDto(); add.setOrderID(order.getId()); when(orderRepository.findById(order.getId())).thenReturn(Optional.ofNullable(order)); - when(userRepository.findUserByUuid("abc")).thenReturn(Optional.of(user)); - when(violationRepository.findByOrderId(order.getId())).thenReturn(Optional.of(ModelUtils.getViolation())); - assertThrows(NotFoundException.class, + verify(orderRepository, never()).findById(anyLong()); + EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> violationService.addUserViolation(add, new MultipartFile[2], "abc")); + assertEquals(ErrorMessage.EMPLOYEE_NOT_FOUND, ex.getMessage()); } @Test diff --git a/service/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/service/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 000000000..ca6ee9cea --- /dev/null +++ b/service/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline \ No newline at end of file