Skip to content

Commit

Permalink
build(ut): fix some ut
Browse files Browse the repository at this point in the history
  • Loading branch information
dtrouillet committed Jul 30, 2024
1 parent 07b537d commit 11a733e
Show file tree
Hide file tree
Showing 14 changed files with 64 additions and 45 deletions.
5 changes: 0 additions & 5 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,6 @@
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-json-org</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.15.0</version>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
Expand Down
8 changes: 4 additions & 4 deletions settings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@
<servers>
<server>
<id>github-public</id>
<username>${env.USERNAME}</username>
<password>${env.PASSWORD}</password>
<username>${env.GITHUB_USERNAME}</username>
<password>${env.GITHUB_pASSWORD}</password>
</server>
<server>
<id>github</id>
<username>${env.USERNAME}</username>
<password>${env.PASSWORD}</password>
<username>${env.GITHUB_USERNAME}</username>
<password>${env.GITHUB_PASSWORD}</password>
</server>
</servers>
</settings>
6 changes: 4 additions & 2 deletions src/main/java/fr/icdc/ebad/domain/Notification.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
import lombok.Data;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.joda.time.DateTime;

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters;

import java.time.LocalDateTime;

/**
* Entite des notifications permettant d'enregistrer des notications
*/
Expand All @@ -39,7 +41,7 @@ public class Notification {
@CreatedDate
@Column(nullable = false, name = "created_date")
@Convert(converter= Jsr310JpaConverters.LocalDateConverter.class)
private DateTime createdDate = DateTime.now();
private LocalDateTime createdDate = LocalDateTime.now();

@NotNull
@Column(nullable = false, name = "is_read")
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/fr/icdc/ebad/repository/UserRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import com.querydsl.core.types.dsl.StringPath;
import fr.icdc.ebad.domain.QUser;
import fr.icdc.ebad.domain.User;
import org.joda.time.DateTime;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
Expand All @@ -17,6 +16,7 @@
import org.springframework.data.querydsl.binding.SingleValueBinding;
import org.springframework.data.repository.query.Param;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

Expand All @@ -40,7 +40,7 @@ default void customize(QuerydslBindings bindings, QUser root) {

Optional<User> findOneByActivationKey(String activationKey);

List<User> findAllByActivatedIsFalseAndCreatedDateBefore(DateTime dateTime);
List<User> findAllByActivatedIsFalseAndCreatedDateBefore(LocalDateTime dateTime);

Optional<User> findOneByEmail(String email);

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/fr/icdc/ebad/service/NotificationService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
import fr.icdc.ebad.domain.User;
import fr.icdc.ebad.repository.NotificationRepository;
import fr.icdc.ebad.security.SecurityUtils;
import org.joda.time.DateTime;
import org.springframework.data.domain.Sort;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
Expand All @@ -32,7 +32,7 @@ public void createNotification(String message, User user, boolean isDanger) {
}
Notification notification = new Notification();
notification.setContent(message);
notification.setCreatedDate(DateTime.now());
notification.setCreatedDate(LocalDateTime.now());
notification.setReceiver(user);
notification.setDanger(isDanger);
Notification result = notificationRepository.save(notification);
Expand Down
7 changes: 5 additions & 2 deletions src/main/java/fr/icdc/ebad/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import fr.icdc.ebad.service.util.EbadServiceException;
import fr.icdc.ebad.service.util.RandomUtil;
import fr.icdc.ebad.web.rest.dto.AuthorityApplicationDTO;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
Expand All @@ -22,6 +21,10 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
Expand Down Expand Up @@ -129,7 +132,7 @@ public User getUserWithAuthorities() throws EbadServiceException {
@Scheduled(cron = "0 0 1 * * ?")
@Transactional
public void removeNotActivatedUsers() {
DateTime now = new DateTime();
LocalDateTime now = LocalDateTime.now();
List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(NUMBERS_OF_DAY_KEEP_INACTIVATE_USERS));
for (User user : users) {
LOGGER.debug("Deleting not activated user {}", user.getLogin());
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/fr/icdc/ebad/web/rest/dto/NotificationDto.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package fr.icdc.ebad.web.rest.dto;

import lombok.Data;
import org.joda.time.DateTime;

import java.time.LocalDateTime;

@Data
public class NotificationDto {
private Long id;
private String content;
private DateTime createdDate = DateTime.now();
private LocalDateTime createdDate = LocalDateTime.now();
private boolean read = false;
}
21 changes: 10 additions & 11 deletions src/main/java/fr/icdc/ebad/web/rest/errors/ExceptionTranslator.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ public ExceptionTranslator(MessageSource messageSource) {
* @return the ApiError object
*/
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(
protected ResponseEntity<Object> handleMissingServletRequestParameter(
MissingServletRequestParameterException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
HttpStatusCode status, WebRequest request) {
String error = ex.getParameterName() + " parameter is missing";
return buildResponseEntity(new ApiError(BAD_REQUEST, error, ex));
}
Expand Down Expand Up @@ -108,12 +108,12 @@ protected ResponseEntity<Object> handleMethodArgumentNotValid(
* @param ex the ConstraintViolationException
* @return the ApiError object
*/
@ExceptionHandler(javax.validation.ConstraintViolationException.class)
@ExceptionHandler(ConstraintViolationException.class)
protected ResponseEntity<Object> handleConstraintViolation(
javax.validation.ConstraintViolationException ex) {
ConstraintViolationException ex) {
ApiError apiError = new ApiError(BAD_REQUEST);
apiError.setMessage("Error occured when validate field");
apiError.addValidationErrors(ex.getConstraintViolations());
// apiError.addValidationErrors(ex.getConstraintViolations());
return buildResponseEntity(apiError);
}

Expand Down Expand Up @@ -188,25 +188,24 @@ protected ResponseEntity<Object> handleEbadNotFound(EbadNotFoundException ex) {
*/
@ExceptionHandler(EbadServiceException.class)
protected ResponseEntity<Object> handleEbadServiceException(EbadServiceException ex) {
return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR,ex.getMessage(), ex));
return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex));
}

/**
* Handle IllegalStateException
*/
@ExceptionHandler(IllegalStateException.class)
protected ResponseEntity<Object> handleIllegalStateException(IllegalStateException ex) {
return buildResponseEntity(new ApiError(BAD_REQUEST,ex.getMessage(), ex));
return buildResponseEntity(new ApiError(BAD_REQUEST, ex.getMessage(), ex));
}


@ExceptionHandler({InsufficientAuthenticationException.class, UserNotActivatedException.class, AccessDeniedException.class})
public ResponseEntity<Object> handleInsufficientAuthenticationException(Exception ex){
return buildResponseEntity(new ApiError(HttpStatus.FORBIDDEN,messageSource.getMessage(ErrorConstants.ERR_FORBIDDEN, null, LocaleContextHolder.getLocale()), ex));
public ResponseEntity<Object> handleInsufficientAuthenticationException(Exception ex) {
return buildResponseEntity(new ApiError(HttpStatus.FORBIDDEN, messageSource.getMessage(ErrorConstants.ERR_FORBIDDEN, null, LocaleContextHolder.getLocale()), ex));
}



/**
* Handle DataIntegrityViolationException, inspects the cause for different DB causes.
*
Expand Down Expand Up @@ -243,7 +242,7 @@ protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgument
@ExceptionHandler(Exception.class)
protected ResponseEntity<Object> handleException(Exception ex) {
logger.error(ex.getMessage(), ex);
return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR,"Internal Server Error", ex));
return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, "Internal Server Error", ex));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,11 @@ public void requestNewAccreditation() throws EbadServiceException, MessagingExce
when(applicationRepository.findById(eq(1L))).thenReturn(Optional.of(accreditationRequest.getApplication()));
when(userService.getUser(any())).thenReturn(Optional.of(User.builder().login("testlogin").email("[email protected]").build()));

when(accreditationRequestRepository.save(eq(accreditationRequest))).thenReturn(accreditationRequestWithId);
when(accreditationRequestRepository.saveAndFlush(eq(accreditationRequest))).thenReturn(accreditationRequestWithId);
doNothing().when(notificationService).createNotification(any(), any(), eq(false));
AccreditationRequest result = accreditationRequestService.requestNewAccreditation(1L, true, false);

verify(accreditationRequestRepository).save(eq(accreditationRequest));
verify(accreditationRequestRepository).saveAndFlush(eq(accreditationRequest));
verify(messagingTemplate).convertAndSendToUser(any(), eq("/queue/accreditations"), any());
verify(mailService).sendMailAccreditation(eq("[email protected]"));

Expand Down Expand Up @@ -150,14 +150,14 @@ public void requestNewAccreditationErrorMail() throws EbadServiceException, Mess
when(applicationRepository.findById(eq(1L))).thenReturn(Optional.of(accreditationRequest.getApplication()));
when(userService.getUser(any())).thenReturn(Optional.of(User.builder().login("testlogin").email("[email protected]").build()));

when(accreditationRequestRepository.save(eq(accreditationRequest))).thenReturn(accreditationRequestWithId);
when(accreditationRequestRepository.saveAndFlush(eq(accreditationRequest))).thenReturn(accreditationRequestWithId);

doThrow(MessagingException.class).when(mailService).sendMailAccreditation(eq("[email protected]"));

doNothing().when(notificationService).createNotification(any(), any(), eq(false));
AccreditationRequest result = accreditationRequestService.requestNewAccreditation(1L, true, false);

verify(accreditationRequestRepository).save(eq(accreditationRequest));
verify(accreditationRequestRepository).saveAndFlush(eq(accreditationRequest));
verify(messagingTemplate).convertAndSendToUser(any(), eq("/queue/accreditations"), any());
verify(mailService).sendMailAccreditation(eq("[email protected]"));

Expand Down Expand Up @@ -323,7 +323,7 @@ public void answerToRequestReject() throws EbadServiceException {
when(accreditationRequestRepository.findByIdAndState(eq(1L), eq(StateRequest.SENT))).thenReturn(Optional.of(accreditationRequest));
accreditationRequestService.answerToRequest(1L, false);

verify(accreditationRequestRepository).save(eq(accreditationRequestRejected));
verify(accreditationRequestRepository).saveAndFlush(eq(accreditationRequestRejected));
}

@Test
Expand Down Expand Up @@ -357,7 +357,7 @@ public void answerToRequestAccept() throws EbadServiceException {

accreditationRequestService.answerToRequest(1L, true);

verify(accreditationRequestRepository).save(eq(accreditationRequestAccepted));
verify(accreditationRequestRepository).saveAndFlush(eq(accreditationRequestAccepted));

verify(userService).changeAutorisationApplication(argThat(authorityApplicationDTO ->
"testlogin".equals(authorityApplicationDTO.getLoginUser())
Expand Down
2 changes: 1 addition & 1 deletion src/test/java/fr/icdc/ebad/service/ChaineServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public void addChaine() {
public void testGetChaine() {
Chaine chaine = new Chaine();
chaine.setId(1L);
when(chaineRepository.getById(chaine.getId())).thenReturn(chaine);
when(chaineRepository.getReferenceById(chaine.getId())).thenReturn(chaine);

Chaine result = chaineService.getChaine(chaine.getId());

Expand Down
5 changes: 3 additions & 2 deletions src/test/java/fr/icdc/ebad/service/DirectoryServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import fr.icdc.ebad.web.rest.dto.FilesDto;
import org.apache.commons.io.IOUtils;
import org.apache.sshd.sftp.client.SftpClient;
import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
Expand All @@ -25,6 +24,8 @@
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

Expand Down Expand Up @@ -139,7 +140,7 @@ private SftpClient.DirEntry lsEntryWithGivenFilenameAndMTime(String filename, lo
}

private long unixTimestampForDaysAgo(int days) {
return new DateTime().minusDays(days).getMillis() / 1000;
return LocalDateTime.now().minusDays(days).toInstant(ZoneOffset.UTC).toEpochMilli() / 1000;
}

@Test
Expand Down
17 changes: 14 additions & 3 deletions src/test/java/fr/icdc/ebad/service/EnvironnementServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import fr.icdc.ebad.repository.SchedulingRepository;
import fr.icdc.ebad.service.util.EbadServiceException;
import org.jobrunr.scheduling.JobScheduler;
import org.joda.time.format.DateTimeFormat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand All @@ -45,6 +44,9 @@
import org.springframework.data.domain.Pageable;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
Expand Down Expand Up @@ -218,7 +220,12 @@ public void testChangeDateTraiement() throws EbadServiceException {
Environnement environnement = Environnement.builder().id(1L).homePath("/home").norme(norme).application(application).build();
when(shellService.runCommandNew(eq(environnement), eq("echo 01022018 > /home/date.tr"))).thenReturn(retourBatch);
when(environnementRepository.getById(eq(environnement.getId()))).thenReturn(environnement);
environnementService.changeDateTraiement(1L, DateTimeFormat.forPattern("ddMMyyyy").parseDateTime("01022018").toDate());

LocalDate now = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
LocalDate parsedDate = LocalDate.parse("01022018", formatter);

environnementService.changeDateTraiement(1L, Date.from(parsedDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));

verify(shellService).runCommandNew(eq(environnement), eq("echo 01022018 > /home/date.tr"));
}
Expand All @@ -234,7 +241,11 @@ public void testChangeDateTraiementError() throws EbadServiceException {
when(shellService.runCommandNew(eq(environnement), eq("echo 01022018 > /home/date.tr"))).thenThrow(new EbadServiceException());
when(environnementRepository.getById(eq(environnement.getId()))).thenReturn(environnement);

environnementService.changeDateTraiement(1L, DateTimeFormat.forPattern("ddMMyyyy").parseDateTime("01022018").toDate());
LocalDate now = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
LocalDate parsedDate = LocalDate.parse("01022018", formatter);

environnementService.changeDateTraiement(1L, Date.from(parsedDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import fr.icdc.ebad.web.rest.dto.ApplicationDto;
import fr.icdc.ebad.web.rest.dto.NormeDto;
import fr.icdc.ebad.web.rest.errors.ExceptionTranslator;
import jakarta.persistence.EntityNotFoundException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validation;
Expand Down Expand Up @@ -162,7 +161,7 @@ public void testHandleHttpMessageNotReadable() throws Exception {
@WithMockUser(roles = {"ADMIN"})
public void testHandleEntityNotFound() throws Exception {
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put("/norms").content("{\"name\": \"toto\"}").contentType("application/json");
when(normeService.saveNorme(any())).thenThrow(EntityNotFoundException.class);
when(normeService.saveNorme(any())).thenThrow(javax.persistence.EntityNotFoundException.class);
restMvc.perform(builder)
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.apierror.message", is("Unexpected error")));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package fr.icdc.ebad.web.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import fr.icdc.ebad.config.Constants;
import fr.icdc.ebad.domain.Notification;
import fr.icdc.ebad.repository.NotificationRepository;
Expand All @@ -12,6 +14,7 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
Expand Down Expand Up @@ -46,11 +49,16 @@ public class NotificationResourceTest {
private NotificationResource notificationResource;

private MockMvc restMvc;
private ObjectMapper objectMapper = new ObjectMapper();


@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.restMvc = MockMvcBuilders.standaloneSetup(notificationResource).build();
this.restMvc = MockMvcBuilders
.standaloneSetup(notificationResource)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.build();
}

@Test
Expand Down

0 comments on commit 11a733e

Please sign in to comment.