From 6275ce1c1d9211d3f38d7be93d1822bbe8b8c71c Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 6 Dec 2023 16:08:24 +0100 Subject: [PATCH] refactor: handle exceptions in controller --- .../controller/CampaignController.java | 5 ++- .../metadata/controller/OwnerController.java | 8 +++- .../controller/PartitioningController.java | 5 ++- .../metadata/controller/SourceController.java | 11 ++++-- .../controller/SupportController.java | 8 +++- .../metadata/controller/SurveyController.java | 20 +++++----- .../metadata/dto/OwnerDto.java | 2 + .../metadata/dto/PartitioningDto.java | 6 ++- .../metadata/dto/SourceCompleteDto.java | 2 + .../metadata/dto/SupportDto.java | 2 + .../metadata/dto/SurveyDto.java | 5 ++- .../query/controller/WebclientController.java | 19 +++++---- .../controller/SurveyUnitController.java | 30 +++++++------- .../questioning/dto/SurveyUnitDto.java | 4 +- .../user/controller/UserController.java | 6 +-- .../user/validation/UserRoleValid.java | 2 +- ...acollectionManagementApplicationTests.java | 6 +-- .../controller/AddressControllerTest.java | 32 +++++++-------- .../controller/ContactControllerTest.java | 39 ++++++++++--------- .../ContactEventControllerTest.java | 27 ++++++------- .../dataloader/DataloaderTest.java | 6 +-- .../controller/CampaignControllerTest.java | 9 +++-- .../controller/SourceControllerTest.java | 17 ++++---- .../controller/SurveyControllerTest.java | 33 ++++++++-------- .../CheckHabilitationControllerTest.java | 13 +------ .../query/controller/MoogControllerTest.java | 26 ++++++------- .../MyQuestioningsControllerTest.java | 6 +-- ...estionningAccreditationControllerTest.java | 28 ++++++------- .../QuestionningControllerTest.java | 13 +++---- .../QuestionningEventControllerTest.java | 16 ++++---- .../controller/SurveyUnitControllerTest.java | 38 +++++++++--------- .../controller/UserControllerTest.java | 27 ++++++------- .../controller/UserEventControllerTest.java | 16 ++++---- .../util/JsonUtil.java | 19 +++++++++ 34 files changed, 276 insertions(+), 230 deletions(-) create mode 100644 src/test/java/fr/insee/survey/datacollectionmanagement/util/JsonUtil.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java index d46d02d9..1b3072ac 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; @@ -122,8 +123,8 @@ public ResponseEntity getCampaign(@PathVariable("id") String id) { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity putCampaign(@PathVariable("id") String id, @RequestBody @Valid CampaignDto campaignDto) { - if (StringUtils.isBlank(campaignDto.getId()) || !campaignDto.getId().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idCampaign don't match"); + if ( !campaignDto.getId().equalsIgnoreCase(id)) { + throw new NotMatchException("id and idCampaign don't match"); } HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(HttpHeaders.LOCATION, diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java index ac8fb154..2910a649 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; import fr.insee.survey.datacollectionmanagement.metadata.dto.OwnerDto; import fr.insee.survey.datacollectionmanagement.metadata.service.OwnerService; @@ -11,6 +12,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; @@ -19,6 +21,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -32,6 +35,7 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @RequiredArgsConstructor +@Validated public class OwnerController { private final ModelMapper modelmapper; @@ -73,9 +77,9 @@ public ResponseEntity getOwner(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = OwnerDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putOwner(@PathVariable("id") String id, @RequestBody OwnerDto ownerDto) { + public ResponseEntity putOwner(@PathVariable("id") String id, @RequestBody @Valid OwnerDto ownerDto) { if (!ownerDto.getId().equals(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and owner id don't match"); + throw new NotMatchException("id and owner id don't match"); } HttpHeaders responseHeaders = new HttpHeaders(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java index 7d1038fd..e09229a1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.dto.PartitioningDto; @@ -94,8 +95,8 @@ public ResponseEntity getPartitioning(@PathVariable("id") String id) { }) public ResponseEntity putPartitioning(@PathVariable("id") String id, @RequestBody PartitioningDto partitioningDto) { - if (StringUtils.isBlank(partitioningDto.getId()) || !partitioningDto.getId().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idPartitioning don't match"); + if (!partitioningDto.getId().equalsIgnoreCase(id)) { + throw new NotMatchException("id and owner id don't match"); } Partitioning partitioning; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java index 8e2c1a40..cd2c2f49 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; @@ -20,6 +21,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -30,6 +32,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -43,6 +46,7 @@ @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @Slf4j @RequiredArgsConstructor +@Validated public class SourceController { private final SourceService sourceService; @@ -93,9 +97,10 @@ public ResponseEntity getSource(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SourceCompleteDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putSource(@PathVariable("id") String id, @RequestBody SourceCompleteDto SourceCompleteDto) { - if (StringUtils.isBlank(SourceCompleteDto.getId()) || !SourceCompleteDto.getId().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and source id don't match"); + public ResponseEntity putSource(@PathVariable("id") String id, @RequestBody @Valid SourceCompleteDto SourceCompleteDto) { + if ( !SourceCompleteDto.getId().equalsIgnoreCase(id)) { + throw new NotMatchException("id and source id don't match"); + } Source source; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java index 70286ff4..5fe9a754 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Support; import fr.insee.survey.datacollectionmanagement.metadata.dto.SupportDto; import fr.insee.survey.datacollectionmanagement.metadata.service.SupportService; @@ -11,6 +12,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; @@ -19,6 +21,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -32,6 +35,7 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @RequiredArgsConstructor +@Validated public class SupportController { private final ModelMapper modelmapper; @@ -73,9 +77,9 @@ public ResponseEntity getSupport(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SupportDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putSupport(@PathVariable("id") String id, @RequestBody SupportDto supportDto) { + public ResponseEntity putSupport(@PathVariable("id") String id, @RequestBody @Valid SupportDto supportDto) { if (!supportDto.getId().equals(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and support id don't match"); + throw new NotMatchException("id and support id don't match"); } HttpHeaders responseHeaders = new HttpHeaders(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java index 38a7c519..34820613 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; @@ -18,6 +19,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -79,14 +81,10 @@ public ResponseEntity getSurveysBySource(@PathVariable("id") String id) { @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity getSurvey(@PathVariable("id") String id) { + public ResponseEntity getSurvey(@PathVariable("id") String id) { Survey survey = surveyService.findById(StringUtils.upperCase(id)); - try { - return ResponseEntity.ok().body(convertToDto(survey)); + return ResponseEntity.ok().body(convertToDto(survey)); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } } @@ -97,9 +95,11 @@ public ResponseEntity getSurvey(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SurveyDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putSurvey(@PathVariable("id") String id, @RequestBody SurveyDto surveyDto) { - if (StringUtils.isBlank(surveyDto.getId()) || !surveyDto.getId().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idSurvey don't match"); + public ResponseEntity putSurvey(@PathVariable("id") String id, @RequestBody @Valid SurveyDto surveyDto) { + if (!surveyDto.getId().equalsIgnoreCase(id)) { + throw new NotMatchException("id and idSurvey don't match"); + + } Survey survey; HttpHeaders responseHeaders = new HttpHeaders(); @@ -131,7 +131,7 @@ public ResponseEntity putSurvey(@PathVariable("id") String id, @RequestBody S @ApiResponse(responseCode = "400", description = "Bad Request") }) @Transactional - public ResponseEntity deleteSurvey(@PathVariable("id") String id) { + public ResponseEntity deleteSurvey(@PathVariable("id") String id) { Survey survey = surveyService.findById(id); try { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/OwnerDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/OwnerDto.java index cd4047b1..3c4ecc6f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/OwnerDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/OwnerDto.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @@ -7,6 +8,7 @@ @Setter public class OwnerDto { + @NotBlank private String id; private String label; private String ministry; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PartitioningDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PartitioningDto.java index 750b7680..8a18e185 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PartitioningDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PartitioningDto.java @@ -1,12 +1,14 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; -import java.util.Date; - +import jakarta.validation.constraints.NotBlank; import lombok.Data; +import java.util.Date; + @Data public class PartitioningDto { + @NotBlank private String id; private String campaignId; private String label; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SourceCompleteDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SourceCompleteDto.java index b2419eb3..806a40e0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SourceCompleteDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SourceCompleteDto.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @@ -8,6 +9,7 @@ @Setter public class SourceCompleteDto { + @NotBlank private String id; private String longWording; private String shortWording; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SupportDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SupportDto.java index f0c110a7..8ae7c2e0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SupportDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SupportDto.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @@ -7,6 +8,7 @@ @Setter public class SupportDto { + @NotBlank private String id; private String label; private String phoneNumber; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SurveyDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SurveyDto.java index 6e8c7ed8..a408b27a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SurveyDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SurveyDto.java @@ -1,15 +1,16 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; -import lombok.NonNull; import lombok.Setter; @Getter @Setter public class SurveyDto { + @NotBlank private String id; - @NonNull + @NotBlank private String sourceId; private Integer year; private Integer sampleSize; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java index 3caa08ce..f5717290 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java @@ -9,6 +9,7 @@ import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.*; import fr.insee.survey.datacollectionmanagement.metadata.dto.*; import fr.insee.survey.datacollectionmanagement.metadata.service.*; @@ -33,6 +34,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -42,6 +44,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -54,6 +57,7 @@ @Slf4j @Tag(name = "6 - Webclients", description = "Enpoints for webclients") @RequiredArgsConstructor +@Validated public class WebclientController { private final QuestioningService questioningService; @@ -118,12 +122,11 @@ public ResponseEntity putQuestioning(@RequestBody QuestioningWebclientDto que su = convertToEntity(questioningWebclientDto.getSurveyUnit()); // Create su if not exists or update - try{ + try { SurveyUnit optSuBase = surveyUnitService.findbyId(idSu); su.setQuestionings(optSuBase.getQuestionings()); - } - catch (NotFoundException e){ + } catch (NotFoundException e) { log.warn("survey unit {} does not exist - Creation of the survey unit", idSu); su.setQuestionings(new HashSet<>()); @@ -299,12 +302,12 @@ public ResponseEntity getMetadata(@PathVariable("id") String id) { }) @Transactional public ResponseEntity putMetadata(@PathVariable("id") String id, - @RequestBody MetadataDto metadataDto) { + @RequestBody @Valid MetadataDto metadataDto) { + if (!metadataDto.getPartitioningDto().getId().equalsIgnoreCase(id)) { + throw new NotMatchException("id and idPartitioning don't match"); + } try { - if (StringUtils.isBlank(metadataDto.getPartitioningDto().getId()) - || !metadataDto.getPartitioningDto().getId().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idPartitioning don't match"); - } + MetadataDto metadataReturn = new MetadataDto(); HttpHeaders responseHeaders = new HttpHeaders(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java index bf69bd01..ee24e5e0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import fr.insee.survey.datacollectionmanagement.questioning.dto.SurveyUnitDto; import fr.insee.survey.datacollectionmanagement.questioning.service.SurveyUnitService; @@ -11,6 +12,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -20,6 +22,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -33,6 +36,7 @@ @Tag(name = "2 - Questioning", description = "Enpoints to create, update, delete and find entities around the questionings") @Slf4j @RequiredArgsConstructor +@Validated public class SurveyUnitController { private final SurveyUnitService surveyUnitService; @@ -75,10 +79,9 @@ public ResponseEntity findSurveyUnit(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SurveyUnitDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBody SurveyUnitDto surveyUnitDto) { - if (StringUtils.isBlank(surveyUnitDto.getIdSu()) || !surveyUnitDto.getIdSu().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idSu don't match"); - + public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBody @Valid SurveyUnitDto surveyUnitDto) { + if (!surveyUnitDto.getIdSu().equalsIgnoreCase(id)) { + throw new NotMatchException("id and idSu don't match"); } SurveyUnit surveyUnit; @@ -92,12 +95,11 @@ public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBo } catch (ParseException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse survey unit"); } - try{ + try { surveyUnitService.findbyId(surveyUnitDto.getIdSu()); responseStatus = HttpStatus.OK; - } - catch (NotFoundException e){ + } catch (NotFoundException e) { log.info("Creating survey with the id {}", surveyUnitDto.getIdSu()); responseStatus = HttpStatus.CREATED; } @@ -118,13 +120,13 @@ public ResponseEntity deleteSurveyUnit(@PathVariable("id") String id) { SurveyUnit surveyUnit = surveyUnitService.findbyId(StringUtils.upperCase(id)); try { - if (!surveyUnit.getQuestionings().isEmpty()) { - log.warn("Some questionings exist for the survey unit {}, the survey unit can't be deleted", id); - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Some questionings exist for this survey unit, the survey unit can't be deleted"); - } - surveyUnitService.deleteSurveyUnit(id); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Survey unit deleted"); + if (!surveyUnit.getQuestionings().isEmpty()) { + log.warn("Some questionings exist for the survey unit {}, the survey unit can't be deleted", id); + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body("Some questionings exist for this survey unit, the survey unit can't be deleted"); + } + surveyUnitService.deleteSurveyUnit(id); + return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Survey unit deleted"); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/SurveyUnitDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/SurveyUnitDto.java index 7f1c0f93..805b2cc1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/SurveyUnitDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/SurveyUnitDto.java @@ -1,12 +1,14 @@ package fr.insee.survey.datacollectionmanagement.questioning.dto; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @Getter @Setter public class SurveyUnitDto { - + + @NotBlank private String idSu; private String identificationCode; private String identificationName; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index 0144176c..8eaf3e04 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; import fr.insee.survey.datacollectionmanagement.user.domain.SourceAccreditation; @@ -18,7 +19,6 @@ import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; @@ -84,8 +84,8 @@ public ResponseEntity getUser(@PathVariable("id") String id) { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestBody UserDto userDto) { - if (StringUtils.isBlank(userDto.getIdentifier()) || !userDto.getIdentifier().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and user identifier don't match"); + if (!userDto.getIdentifier().equalsIgnoreCase(id)) { + throw new NotMatchException("id and user identifier don't match"); } User user; HttpHeaders responseHeaders = new HttpHeaders(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java index b3a614e0..75f97f5f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java @@ -16,7 +16,7 @@ @Constraint(validatedBy = UserRoleValidator.class) public @interface UserRoleValid { //error message - String message() default "Role missing or not recognized. Only CREATE, UPDATE, DELETE"; + String message() default "Role missing or not recognized. Only RESPONSABLE, GESTIONNAIRE, ASSISTANCE are valid"; //represents group of constraints Class[] groups() default {}; diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java b/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java index a6e44c20..36d8de69 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java @@ -8,8 +8,8 @@ @EnableJpaRepositories class DatacollectionManagementApplicationTests { - @Test - void contextLoads() { - } + @Test + void contextLoads() { + } } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java index fd65ce3c..eaf83504 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java @@ -28,34 +28,34 @@ @SpringBootTest @ActiveProfiles("test") @ContextConfiguration -public class AddressControllerTest { +class AddressControllerTest { @Autowired private MockMvc mockMvc; @Autowired private ContactService contactService; - + @Autowired private AddressService addressService; @Test - public void getAddressOk() throws Exception { + void getAddressOk() throws Exception { String identifier = "CONT1"; Contact contact = contactService.findByIdentifier(identifier); String json = createJsonAddress(contact); - this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS , identifier)).andDo(print()).andExpect(status().isOk()).andExpect(content().json(json, false)); + this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS, identifier)).andDo(print()).andExpect(status().isOk()).andExpect(content().json(json, false)); } @Test - public void getAddressContacttNotFound() throws Exception { + void getAddressContacttNotFound() throws Exception { String identifier = "CONT500"; - this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS , identifier)).andDo(print()).andExpect(status().is(HttpStatus.NOT_FOUND.value())); + this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS, identifier)).andDo(print()).andExpect(status().is(HttpStatus.NOT_FOUND.value())); } @Test - public void putAddressCreateUpdate() throws Exception { + void putAddressCreateUpdate() throws Exception { String identifier = "CONT5"; Contact contact = contactService.findByIdentifier(identifier); @@ -65,31 +65,31 @@ public void putAddressCreateUpdate() throws Exception { contact.setAddress(null); contact = contactService.saveContact(contact); addressService.deleteAddressById(addressBefore.getId()); - - this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS , identifier)).andDo(print()).andExpect(status().is(HttpStatus.NOT_FOUND.value())); + + this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS, identifier)).andDo(print()).andExpect(status().is(HttpStatus.NOT_FOUND.value())); // Create address - status created Address addressCreated = initAddressMock(identifier); contact.setAddress(addressCreated); String jsonCreate = createJsonAddress(contact); - this.mockMvc.perform(put(Constants.API_CONTACTS_ID_ADDRESS , identifier).content(jsonCreate).contentType(MediaType.APPLICATION_JSON)).andDo(print()) - .andExpect(status().isCreated()).andExpect(content().json(jsonCreate.toString(), false)); + this.mockMvc.perform(put(Constants.API_CONTACTS_ID_ADDRESS, identifier).content(jsonCreate).contentType(MediaType.APPLICATION_JSON)).andDo(print()) + .andExpect(status().isCreated()).andExpect(content().json(jsonCreate.toString(), false)); Contact contactAfterCreate = contactService.findByIdentifier(identifier); assertEquals(contactAfterCreate.getAddress().getCityName(), addressCreated.getCityName()); assertEquals(contactAfterCreate.getAddress().getStreetName(), addressCreated.getStreetName()); assertEquals(contactAfterCreate.getAddress().getCountryName(), addressCreated.getCountryName()); - + // Update address - status OK Address addressUpdated = initAddressMock("UPDATE"); contact.setAddress(addressUpdated); String jsonUpdate = createJsonAddress(contact); - this.mockMvc.perform(put(Constants.API_CONTACTS_ID_ADDRESS , identifier).content(jsonUpdate).contentType(MediaType.APPLICATION_JSON)).andDo(print()) - .andExpect(status().isOk()).andExpect(content().json(jsonUpdate.toString(), false)); + this.mockMvc.perform(put(Constants.API_CONTACTS_ID_ADDRESS, identifier).content(jsonUpdate).contentType(MediaType.APPLICATION_JSON)).andDo(print()) + .andExpect(status().isOk()).andExpect(content().json(jsonUpdate.toString(), false)); Contact contactAfterUpdate = contactService.findByIdentifier(identifier); assertEquals(contactAfterUpdate.getAddress().getCityName(), addressUpdated.getCityName()); assertEquals(contactAfterUpdate.getAddress().getStreetName(), addressUpdated.getStreetName()); assertEquals(contactAfterUpdate.getAddress().getCountryName(), addressUpdated.getCountryName()); - + // back to before contact.setAddress(addressBefore); addressService.saveAddress(addressBefore); @@ -97,7 +97,7 @@ public void putAddressCreateUpdate() throws Exception { assertEquals(contact.getAddress().getCityName(), addressBefore.getCityName()); assertEquals(contact.getAddress().getStreetName(), addressBefore.getStreetName()); assertEquals(contact.getAddress().getCountryName(), addressBefore.getCountryName()); - + } private Address initAddressMock(String identifier) { diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java index 2edbe23b..14d2907d 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java @@ -9,6 +9,7 @@ import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -32,7 +33,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class ContactControllerTest { +class ContactControllerTest { @Autowired private MockMvc mockMvc; @@ -47,7 +48,7 @@ public class ContactControllerTest { private ContactRepository contactRepository; @Test - public void getContactOk() throws Exception { + void getContactOk() throws Exception { String identifier = "CONT1"; Contact contact = contactService.findByIdentifier(identifier); String json = createJson(contact); @@ -56,7 +57,7 @@ public void getContactOk() throws Exception { } @Test - public void getContactNotFound() throws Exception { + void getContactNotFound() throws Exception { String identifier = "CONT500"; this.mockMvc.perform(get(Constants.API_CONTACTS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -64,7 +65,7 @@ public void getContactNotFound() throws Exception { } @Test - public void getContactsOk() throws Exception { + void getContactsOk() throws Exception { JSONObject jo = new JSONObject(); jo.put("totalElements", contactRepository.count()); jo.put("numberOfElements", contactRepository.count()); @@ -74,14 +75,14 @@ public void getContactsOk() throws Exception { } @Test - public void putContactCreateUpdateDelete() throws Exception { + void putContactCreateUpdateDelete() throws Exception { String identifier = "TESTPUT"; // create contact - status created Contact contact = initContact(identifier); String jsonContact = createJson(contact); mockMvc.perform( - put(Constants.API_CONTACTS_ID, identifier).content(jsonContact).contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_CONTACTS_ID, identifier).content(jsonContact).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonContact.toString(), false)); Contact contactFound = contactService.findByIdentifier(identifier); @@ -90,14 +91,14 @@ public void putContactCreateUpdateDelete() throws Exception { assertEquals(contact.getEmail(), contactFound.getEmail()); List list = new ArrayList<>(contactEventService.findContactEventsByContact(contactFound)); // List list = new ArrayList<>(contactFound.getContactEvents()); - assertEquals(list.size(), 1); - assertEquals(list.get(0).getType(), ContactEventType.create); + assertEquals(1, list.size()); + assertEquals(ContactEventType.create, list.get(0).getType()); // update contact - status ok contact.setLastName("lastNameUpdate"); String jsonContactUpdate = createJson(contact); mockMvc.perform(put(Constants.API_CONTACTS_ID, identifier).content(jsonContactUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonContactUpdate.toString(), false)); Contact contactFoundAfterUpdate = contactService.findByIdentifier(identifier); assertEquals("lastNameUpdate", contactFoundAfterUpdate.getLastName()); @@ -105,13 +106,13 @@ public void putContactCreateUpdateDelete() throws Exception { assertEquals(contact.getEmail(), contactFoundAfterUpdate.getEmail()); List listUpdate = new ArrayList<>( contactEventService.findContactEventsByContact(contactFoundAfterUpdate)); - assertEquals(listUpdate.size(), 2); - assertEquals(listUpdate.get(1).getType(), ContactEventType.update); + assertEquals(2, listUpdate.size()); + assertEquals(ContactEventType.update, listUpdate.get(1).getType()); // delete contact mockMvc.perform(delete(Constants.API_CONTACTS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertThrows(NotFoundException.class, ()->contactService.findByIdentifier(identifier)); + assertThrows(NotFoundException.class, () -> contactService.findByIdentifier(identifier)); assertTrue(contactEventService.findContactEventsByContact(contactFoundAfterUpdate).isEmpty()); // delete contact not found @@ -121,14 +122,14 @@ public void putContactCreateUpdateDelete() throws Exception { } @Test - public void putContactAddressCreateUpdateDelete() throws Exception { + void putContactAddressCreateUpdateDelete() throws Exception { String identifier = "TESTADDRESS"; // create contact - status created Contact contact = initContactAddress(identifier); String jsonContact = createJsonContactAddress(contact); mockMvc.perform( - put(Constants.API_CONTACTS_ID, identifier).content(jsonContact).contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_CONTACTS_ID, identifier).content(jsonContact).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonContact.toString(), false)); Contact countactFound = contactService.findByIdentifier(identifier); @@ -139,7 +140,7 @@ public void putContactAddressCreateUpdateDelete() throws Exception { contact.getAddress().setCityName(newCityName); String jsonContactUpdate = createJsonContactAddress(contact); mockMvc.perform(put(Constants.API_CONTACTS_ID, identifier).content(jsonContactUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonContactUpdate.toString(), false)); Contact countactFoundAfterUpdate = contactService.findByIdentifier(identifier); assertEquals(contact.getAddress().getCityName(), countactFoundAfterUpdate.getAddress().getCityName()); @@ -147,20 +148,20 @@ public void putContactAddressCreateUpdateDelete() throws Exception { // delete contact mockMvc.perform(delete(Constants.API_CONTACTS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertThrows(NotFoundException.class, ()->contactService.findByIdentifier(identifier)); + assertThrows(NotFoundException.class, () -> contactService.findByIdentifier(identifier)); } @Test - public void putContactsErrorId() throws Exception { + void putContactsErrorId() throws Exception { String identifier = "NEWONE"; String otherIdentifier = "WRONG"; Contact contact = initContact(identifier); String jsonContact = createJson(contact); mockMvc.perform(put(Constants.API_CONTACTS_ID, otherIdentifier).content(jsonContact) - .contentType(MediaType.APPLICATION_JSON)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) - .andExpect(content().string("id and contact identifier don't match")); + .andExpect(content().json(JsonUtil.createJsonErrorBadRequest("id and contact identifier don't match"), false)); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactEventControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactEventControllerTest.java index 91abaef8..db885e53 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactEventControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactEventControllerTest.java @@ -1,10 +1,6 @@ package fr.insee.survey.datacollectionmanagement.contacts.controller; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - +import fr.insee.survey.datacollectionmanagement.constants.Constants; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -16,34 +12,39 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class ContactEventControllerTest { +class ContactEventControllerTest { @Autowired private MockMvc mockMvc; @Test - public void getContactEventOk() throws Exception { + void getContactEventOk() throws Exception { String identifier = "CONT1"; String json = createJsonContactEvent(identifier); - this.mockMvc.perform(get(Constants.API_CONTACTS_ID_CONTACTEVENTS,identifier)).andDo(print()).andExpect(status().isOk()) - .andExpect(content().json(json, false)); + this.mockMvc.perform(get(Constants.API_CONTACTS_ID_CONTACTEVENTS, identifier)).andDo(print()).andExpect(status().isOk()) + .andExpect(content().json(json, false)); } @Test - public void getContactEventNotFound() throws Exception { + void getContactEventNotFound() throws Exception { String identifier = "CONT500"; - this.mockMvc.perform(get(Constants.API_CONTACTS_ID_CONTACTEVENTS,identifier)).andDo(print()) - .andExpect(status().is(HttpStatus.NOT_FOUND.value())); + this.mockMvc.perform(get(Constants.API_CONTACTS_ID_CONTACTEVENTS, identifier)).andDo(print()) + .andExpect(status().is(HttpStatus.NOT_FOUND.value())); } private String createJsonContactEvent(String identifier) throws JSONException { + //region Description JSONObject jo = new JSONObject(); + //endregion JSONObject joPayload = new JSONObject(); joPayload.put("contact_identifier", identifier); jo.put("payload", joPayload); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java index 65cd570f..f1ac2b45 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java @@ -107,7 +107,7 @@ private void initUser() { User user = new User(); user.setIdentifier("USER1"); user.setRole(User.UserRoleType.ASSISTANCE); - userService.createUser(user,null); + userService.createUser(user, null); } private void initOrder() { @@ -292,8 +292,8 @@ private void initMetadata() throws ParseException { sourceRepository.save(source); log.info("Source created : " + source.toString()); ownerInsee.setSources(setSourcesInsee); - ownerRepository.saveAll(Arrays.asList(new Owner[] { - ownerInsee })); + ownerRepository.saveAll(Arrays.asList(new Owner[]{ + ownerInsee})); } } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java index b419cebc..7365f051 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java @@ -6,6 +6,7 @@ import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import net.minidev.json.JSONObject; import org.assertj.core.util.DateUtil; import org.junit.jupiter.api.Test; @@ -60,9 +61,10 @@ void putCampaignsErrorId() throws Exception { String otherIdentifier = "WRONG"; Campaign campaign = initOpenedCampaign(identifier); String jsonCampaign = createJson(campaign, "SOURCE12023"); + String jsonError = JsonUtil.createJsonErrorBadRequest("id and idCampaign don't match"); mockMvc.perform(put(Constants.API_CAMPAIGNS_ID, otherIdentifier).content(jsonCampaign) .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andExpect(content().string("id and idCampaign don't match")); + .andExpect(status().isBadRequest()).andExpect(content().json(jsonError, false)); } @@ -206,7 +208,7 @@ private String createJsonPart(Partitioning part) { return jo.toString(); } - private String createJson(Campaign campaign, String idSurvey) { + private String createJson(Campaign campaign, String idSurvey) { JSONObject jo = new JSONObject(); jo.put("id", campaign.getId()); jo.put("year", campaign.getYear()); @@ -222,11 +224,12 @@ private String createJson(Campaign campaign, String idSurvey) { void getCampaignOk() throws Exception { String identifier = "SOURCE12023T01"; - assertDoesNotThrow(()->campaignService.findById(identifier)); + assertDoesNotThrow(() -> campaignService.findById(identifier)); Campaign campaign = campaignService.findById(identifier); String json = createJson(campaign, "SOURCE12023"); this.mockMvc.perform(get(Constants.API_CAMPAIGNS_ID, identifier)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); } + } \ No newline at end of file diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java index a01cd7e7..a779bb33 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java @@ -6,6 +6,7 @@ import fr.insee.survey.datacollectionmanagement.metadata.repository.SourceRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -26,7 +27,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class SourceControllerTest { +class SourceControllerTest { @Autowired MockMvc mockMvc; @@ -38,7 +39,7 @@ public class SourceControllerTest { SourceRepository sourceRepository; @Test - public void getSourceOk() throws Exception { + void getSourceOk() throws Exception { String identifier = "SOURCE1"; assertDoesNotThrow(() -> sourceService.findById(identifier)); Source source = sourceService.findById(identifier); @@ -48,7 +49,7 @@ public void getSourceOk() throws Exception { } @Test - public void getSourceNotFound() throws Exception { + void getSourceNotFound() throws Exception { String identifier = "SOURCENOTFOUND"; this.mockMvc.perform(get(Constants.API_SOURCES_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -56,7 +57,7 @@ public void getSourceNotFound() throws Exception { } @Test - public void getSourcesOk() throws Exception { + void getSourcesOk() throws Exception { JSONObject jo = new JSONObject(); jo.put("totalElements", sourceRepository.count()); jo.put("numberOfElements", sourceRepository.count()); @@ -66,7 +67,7 @@ public void getSourcesOk() throws Exception { } @Test - public void putSourceCreateUpdateDelete() throws Exception { + void putSourceCreateUpdateDelete() throws Exception { String identifier = "SOURCEPUT"; // create source - status created @@ -98,7 +99,7 @@ public void putSourceCreateUpdateDelete() throws Exception { // delete source mockMvc.perform(delete(Constants.API_SOURCES_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertThrows(NotFoundException.class, ()->sourceService.findById(identifier)); + assertThrows(NotFoundException.class, () -> sourceService.findById(identifier)); // delete source not found mockMvc.perform(delete(Constants.API_SOURCES + "/" + identifier).contentType(MediaType.APPLICATION_JSON)) @@ -107,14 +108,14 @@ public void putSourceCreateUpdateDelete() throws Exception { } @Test - public void putSourcesErrorId() throws Exception { + void putSourcesErrorId() throws Exception { String identifier = "NEWONE"; String otherIdentifier = "WRONG"; Source source = initSource(identifier); String jsonSource = createJson(source); mockMvc.perform(put(Constants.API_SOURCES + "/" + otherIdentifier).content(jsonSource) .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andExpect(content().string("id and source id don't match")); + .andExpect(status().isBadRequest()).andExpect(content().json(JsonUtil.createJsonErrorBadRequest("id and source id don't match"))); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java index b51896fc..2f941ebe 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java @@ -5,6 +5,7 @@ import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.repository.SurveyRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.SurveyService; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -25,7 +26,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class SurveyControllerTest { +class SurveyControllerTest { @Autowired private MockMvc mockMvc; @@ -37,9 +38,8 @@ public class SurveyControllerTest { private SurveyRepository surveyRepository; - @Test - public void getSurveyNotFound() throws Exception { + void getSurveyNotFound() throws Exception { String identifier = "SURVEYNOTFOUND"; this.mockMvc.perform(get(Constants.API_SURVEYS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -48,19 +48,19 @@ public void getSurveyNotFound() throws Exception { @Test - public void putSurveyCreateUpdateDelete() throws Exception { + void putSurveyCreateUpdateDelete() throws Exception { String identifier = "SURVEYPUT"; // create survey - status created Survey survey = initSurvey(identifier); String jsonSurvey = createJson(survey, "SOURCE1"); mockMvc.perform( - put(Constants.API_SURVEYS_ID, identifier).content(jsonSurvey) - .contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_SURVEYS_ID, identifier).content(jsonSurvey) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonSurvey.toString(), false)); - assertDoesNotThrow(()->surveyService.findById(identifier)); + assertDoesNotThrow(() -> surveyService.findById(identifier)); Survey surveyFound = surveyService.findById(identifier); assertEquals(survey.getLongWording(), surveyFound.getLongWording()); assertEquals(survey.getShortWording(), surveyFound.getShortWording()); @@ -68,11 +68,11 @@ public void putSurveyCreateUpdateDelete() throws Exception { // update survey - status ok survey.setLongWording("Long wording update"); - String jsonSurveyUpdate = createJson(survey,"SOURCE1"); + String jsonSurveyUpdate = createJson(survey, "SOURCE1"); mockMvc.perform(put(Constants.API_SURVEYS_ID, identifier).content(jsonSurveyUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonSurveyUpdate.toString(), false)); - assertDoesNotThrow(()->surveyService.findById(identifier)); + assertDoesNotThrow(() -> surveyService.findById(identifier)); Survey surveyFoundAfterUpdate = surveyService.findById(identifier); assertEquals("Long wording update", surveyFoundAfterUpdate.getLongWording()); @@ -82,7 +82,7 @@ public void putSurveyCreateUpdateDelete() throws Exception { mockMvc.perform(delete(Constants.API_SURVEYS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertThrows(NotFoundException.class,()->surveyService.findById(identifier)); + assertThrows(NotFoundException.class, () -> surveyService.findById(identifier)); // delete survey not found mockMvc.perform(delete(Constants.API_SURVEYS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) @@ -91,14 +91,15 @@ public void putSurveyCreateUpdateDelete() throws Exception { } @Test - public void putSurveysErrorId() throws Exception { + void putSurveysErrorId() throws Exception { String identifier = "NEWONE"; String otherIdentifier = "WRONG"; Survey survey = initSurvey(identifier); String jsonSurvey = createJson(survey, "SOURCE1"); mockMvc.perform(put(Constants.API_SURVEYS_ID, otherIdentifier).content(jsonSurvey) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andExpect(content().string("id and idSurvey don't match")); + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andExpect(content().json(JsonUtil.createJsonErrorBadRequest("id and idSurvey don't match"))); + } @@ -124,9 +125,9 @@ private String createJson(Survey survey, String idSource) throws JSONException { } @Test - public void getSurveyOk() throws Exception { + void getSurveyOk() throws Exception { String identifier = "SOURCE12022"; - assertDoesNotThrow(()->surveyService.findById(identifier)); + assertDoesNotThrow(() -> surveyService.findById(identifier)); Survey survey = surveyService.findById(identifier); String json = createJson(survey, "SOURCE1"); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationControllerTest.java index 9a41cf22..4c70a115 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationControllerTest.java @@ -1,24 +1,13 @@ package fr.insee.survey.datacollectionmanagement.query.controller; -import static org.hamcrest.Matchers.containsString; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.jupiter.api.Test; +import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; - @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java index 4975f7c9..f0183d35 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java @@ -17,7 +17,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class MoogControllerTest { +class MoogControllerTest { @Autowired private MockMvc mockMvc; @@ -26,25 +26,25 @@ public class MoogControllerTest { private MoogService moogService; @Test - public void getMoogReadOnlyUrl() throws Exception { - String idCampaign= "SOURCE12023T01"; - String surveyUnitId= "100000000"; - this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign,surveyUnitId)).andDo(print()).andExpect(status().isOk()) + void getMoogReadOnlyUrl() throws Exception { + String idCampaign = "SOURCE12023T01"; + String surveyUnitId = "100000000"; + this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign, surveyUnitId)).andDo(print()).andExpect(status().isOk()) .andExpect(content().string("http://localhost:8081/readonly/questionnaire/m0/unite-enquetee/100000000")); } @Test - public void getMoogReadOnlyUrlCampaignNotFound() throws Exception { - String idCampaign= "CAMPAIGN"; - String surveyUnitId= "100000000"; - this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign,surveyUnitId)).andDo(print()).andExpect(status().isNotFound()); + void getMoogReadOnlyUrlCampaignNotFound() throws Exception { + String idCampaign = "CAMPAIGN"; + String surveyUnitId = "100000000"; + this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign, surveyUnitId)).andDo(print()).andExpect(status().isNotFound()); } @Test - public void getMoogReadOnlyUrlQuestioningNotFound() throws Exception { - String idCampaign= "SOURCE12023T01"; - String surveyUnitId= "SU"; - this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign,surveyUnitId)).andDo(print()).andExpect(status().isNotFound()); + void getMoogReadOnlyUrlQuestioningNotFound() throws Exception { + String idCampaign = "SOURCE12023T01"; + String surveyUnitId = "SU"; + this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign, surveyUnitId)).andDo(print()).andExpect(status().isNotFound()); } } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java index b90d8ac4..2945d8fd 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java @@ -23,7 +23,7 @@ @SpringBootTest @ActiveProfiles("test") @ContextConfiguration -public class MyQuestioningsControllerTest { +class MyQuestioningsControllerTest { @Autowired private MockMvc mockMvc; @@ -32,7 +32,7 @@ public class MyQuestioningsControllerTest { private CheckHabilitationService checkAccreditationService; // @Test -// public void myQuestionings() throws Exception { +// void myQuestionings() throws Exception { // String identifier = "CONT2"; // // MvcResult result = this.mockMvc.perform(get(Constants.API_MY_QUESTIONINGS_ID, identifier)).andDo(print()) @@ -52,7 +52,7 @@ public class MyQuestioningsControllerTest { // } @Test - public void myQuestioningsContactNotExist() throws Exception { + void myQuestioningsContactNotExist() throws Exception { String identifier = "CONT500"; MvcResult result = this.mockMvc.perform(get(Constants.API_MY_QUESTIONINGS_ID, identifier)).andDo(print()) diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java index bb6d028e..59da0593 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java @@ -29,7 +29,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class QuestionningAccreditationControllerTest { +class QuestionningAccreditationControllerTest { @Autowired private MockMvc mockMvc; @@ -38,7 +38,7 @@ public class QuestionningAccreditationControllerTest { private QuestioningService questioningService; @Test - public void getQuestioningAccreditationOk() throws Exception { + void getQuestioningAccreditationOk() throws Exception { Questioning questioning = questioningService.findBySurveyUnitIdSu("100000001").stream().findFirst().get(); Long identifier = questioning.getQuestioningAccreditations().stream().findFirst().get().getId(); String json = createJsonQuestioningAcreditation(identifier); @@ -47,7 +47,7 @@ public void getQuestioningAccreditationOk() throws Exception { } @Test - public void getQuestioningAccreditationNotFound() throws Exception { + void getQuestioningAccreditationNotFound() throws Exception { String identifier = "300"; this.mockMvc.perform(get(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -55,7 +55,7 @@ public void getQuestioningAccreditationNotFound() throws Exception { } @Test - public void postAccreditationQuestioningNotFound() throws Exception { + void postAccreditationQuestioningNotFound() throws Exception { int idQuestioning = 10000; String idContact = "CONT1"; @@ -63,13 +63,13 @@ public void postAccreditationQuestioningNotFound() throws Exception { QuestioningAccreditation accreditation = initAccreditation(idContact); String jsonAccreditation = createJson(accreditation); mockMvc.perform( - post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) - .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) + post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) + .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test - public void postAccreditationContactNotFound() throws Exception { + void postAccreditationContactNotFound() throws Exception { Questioning q = questioningService.findByIdPartitioning("SOURCE12023T1000").stream().findFirst().get(); Long idQuestioning = q.getId(); String idContact = "CONT7500"; @@ -78,13 +78,13 @@ public void postAccreditationContactNotFound() throws Exception { QuestioningAccreditation accreditation = initAccreditation(idContact); String jsonAccreditation = createJson(accreditation); mockMvc.perform( - post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) - .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) + post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) + .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test - public void postAccreditationCreateUpdate() throws Exception { + void postAccreditationCreateUpdate() throws Exception { Questioning q = questioningService.findByIdPartitioning("SOURCE12023T1000").stream().findFirst().get(); Long idQuestioning = q.getId(); String idContact = "CONT5"; @@ -93,8 +93,8 @@ public void postAccreditationCreateUpdate() throws Exception { QuestioningAccreditation accreditation = initAccreditation(idContact); String jsonAccreditation = createJson(accreditation); mockMvc.perform( - post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) - .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) + post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) + .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonAccreditation.toString(), false)); Questioning questioning = questioningService.findbyId((long) idQuestioning); @@ -109,8 +109,8 @@ public void postAccreditationCreateUpdate() throws Exception { accreditation.setMain(true); String jsonAccreditationUpdate = createJson(accreditation); mockMvc.perform( - post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) - .content(jsonAccreditationUpdate).contentType(MediaType.APPLICATION_JSON)) + post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) + .content(jsonAccreditationUpdate).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().json(jsonAccreditationUpdate.toString(), false)); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java index 56a4816c..380ab2f5 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java @@ -22,16 +22,15 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class QuestionningControllerTest { - - @Autowired - private MockMvc mockMvc; +class QuestionningControllerTest { @Autowired QuestioningService questioningService; + @Autowired + private MockMvc mockMvc; @Test - public void getQuestioningOk() throws Exception { + void getQuestioningOk() throws Exception { Questioning questioning = questioningService.findBySurveyUnitIdSu("100000001").stream().findFirst().get(); Long id = questioning.getQuestioningAccreditations().stream().findFirst().get().getId(); String json = createJson(id).toString(); @@ -40,7 +39,7 @@ public void getQuestioningOk() throws Exception { } @Test - public void getQuestioningNotFound() throws Exception { + void getQuestioningNotFound() throws Exception { String id = "300"; this.mockMvc.perform(get(Constants.API_QUESTIONINGS_ID, id)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -48,7 +47,7 @@ public void getQuestioningNotFound() throws Exception { } @Test - public void getQuestioningsBySurveyUnit() throws Exception { + void getQuestioningsBySurveyUnit() throws Exception { String idSu = "100000000"; String json = createJsonQuestionings(idSu); this.mockMvc.perform(get(Constants.API_SURVEY_UNITS_ID_QUESTIONINGS, idSu)).andDo(print()) diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java index 23efccdb..5433d7e8 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java @@ -22,28 +22,26 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class QuestionningEventControllerTest { - - @Autowired - private MockMvc mockMvc; +class QuestionningEventControllerTest { @Autowired QuestioningService questioningService; - + @Autowired + private MockMvc mockMvc; @Test - public void getQuestioningEventOk() throws Exception { + void getQuestioningEventOk() throws Exception { Questioning questioning = questioningService.findBySurveyUnitIdSu("100000001").stream().findFirst().get(); Long id = questioning.getQuestioningAccreditations().stream().findFirst().get().getId(); String json = createJsonQuestioningEvent(id); - this.mockMvc.perform(get(Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS,id)).andDo(print()).andExpect(status().isOk()) + this.mockMvc.perform(get(Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS, id)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); } @Test - public void getQuestioningEventNotFound() throws Exception { + void getQuestioningEventNotFound() throws Exception { String identifier = "300"; - this.mockMvc.perform(get(Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS,identifier)).andDo(print()) + this.mockMvc.perform(get(Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java index 5ce3c03c..b89e1dd1 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java @@ -6,6 +6,7 @@ import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnitAddress; import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitRepository; import fr.insee.survey.datacollectionmanagement.questioning.service.SurveyUnitService; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -17,7 +18,8 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -27,7 +29,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class SurveyUnitControllerTest { +class SurveyUnitControllerTest { @Autowired private MockMvc mockMvc; @@ -39,7 +41,7 @@ public class SurveyUnitControllerTest { private SurveyUnitRepository surveyUnitRepository; @Test - public void getSurveyUnitOk() throws Exception { + void getSurveyUnitOk() throws Exception { String identifier = "100000000"; SurveyUnit surveyUnit = surveyUnitService.findbyId(identifier); String json = createJson(surveyUnit); @@ -48,7 +50,7 @@ public void getSurveyUnitOk() throws Exception { } @Test - public void getSurveyUnitNotFound() throws Exception { + void getSurveyUnitNotFound() throws Exception { String identifier = "900000000"; this.mockMvc.perform(get(Constants.API_SURVEY_UNITS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -56,7 +58,7 @@ public void getSurveyUnitNotFound() throws Exception { } @Test - public void getSurveyUnitsOk() throws Exception { + void getSurveyUnitsOk() throws Exception { JSONObject jo = new JSONObject(); jo.put("totalElements", surveyUnitRepository.count()); jo.put("numberOfElements", surveyUnitRepository.count()); @@ -66,15 +68,15 @@ public void getSurveyUnitsOk() throws Exception { } @Test - public void putSurveyUnitCreateUpdateDelete() throws Exception { + void putSurveyUnitCreateUpdateDelete() throws Exception { String identifier = "TESTPUT"; // create surveyUnit - status created SurveyUnit surveyUnit = initSurveyUnit(identifier); String jsonSurveyUnit = createJson(surveyUnit); mockMvc.perform( - put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnit) - .contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnit) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonSurveyUnit.toString(), false)); SurveyUnit surveyUnitFound = surveyUnitService.findbyId(identifier); @@ -86,7 +88,7 @@ public void putSurveyUnitCreateUpdateDelete() throws Exception { surveyUnit.setIdentificationName("identificationNameUpdate"); String jsonSurveyUnitUpdate = createJson(surveyUnit); mockMvc.perform(put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnitUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonSurveyUnitUpdate.toString(), false)); SurveyUnit surveyUnitFoundAfterUpdate = surveyUnitService.findbyId(identifier); assertEquals("identificationNameUpdate", surveyUnitFoundAfterUpdate.getIdentificationName()); @@ -95,21 +97,21 @@ public void putSurveyUnitCreateUpdateDelete() throws Exception { // delete surveyUnit surveyUnitService.deleteSurveyUnit(identifier); - assertThrows(NotFoundException.class,()->surveyUnitService.findbyId(identifier)); + assertThrows(NotFoundException.class, () -> surveyUnitService.findbyId(identifier)); } @Test - public void putSurveyUnitAddressCreateUpdateDelete() throws Exception { + void putSurveyUnitAddressCreateUpdateDelete() throws Exception { String identifier = "TESTADDRESS"; // create surveyUnit - status created SurveyUnit surveyUnit = initSurveyUnitAddress(identifier); String jsonSurveyUnit = createJsonSurveyUnitAddress(surveyUnit); mockMvc.perform( - put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnit) - .contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnit) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonSurveyUnit.toString(), false)); SurveyUnit suFound = surveyUnitService.findbyId(identifier); @@ -120,7 +122,7 @@ public void putSurveyUnitAddressCreateUpdateDelete() throws Exception { surveyUnit.getSurveyUnitAddress().setCityName(newCityName); String jsonSurveyUnitUpdate = createJsonSurveyUnitAddress(surveyUnit); mockMvc.perform(put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnitUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonSurveyUnitUpdate.toString(), false)); SurveyUnit countactFoundAfterUpdate = surveyUnitService.findbyId(identifier); assertEquals(surveyUnit.getSurveyUnitAddress().getCityName(), @@ -128,20 +130,20 @@ public void putSurveyUnitAddressCreateUpdateDelete() throws Exception { // delete surveyUnit surveyUnitService.deleteSurveyUnit(identifier); - assertThrows(NotFoundException.class,()->surveyUnitService.findbyId(identifier)); + assertThrows(NotFoundException.class, () -> surveyUnitService.findbyId(identifier)); } @Test - public void putSurveyUnitsErrorId() throws Exception { + void putSurveyUnitsErrorId() throws Exception { String identifier = "NEWONE"; String otherIdentifier = "WRONG"; SurveyUnit surveyUnit = initSurveyUnit(identifier); String jsonSurveyUnit = createJson(surveyUnit); mockMvc.perform(put(Constants.API_SURVEY_UNITS_ID, otherIdentifier).content(jsonSurveyUnit) - .contentType(MediaType.APPLICATION_JSON)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) - .andExpect(content().string("id and idSu don't match")); + .andExpect(content().json(JsonUtil.createJsonErrorBadRequest("id and idSu don't match"))); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java index d2b9821a..be744971 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java @@ -8,6 +8,7 @@ import fr.insee.survey.datacollectionmanagement.user.repository.UserRepository; import fr.insee.survey.datacollectionmanagement.user.service.UserEventService; import fr.insee.survey.datacollectionmanagement.user.service.UserService; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -31,7 +32,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class UserControllerTest { +class UserControllerTest { @Autowired private MockMvc mockMvc; @@ -46,7 +47,7 @@ public class UserControllerTest { private UserRepository userRepository; @Test - public void getUserNotFound() throws Exception { + void getUserNotFound() throws Exception { String identifier = "CONT500"; this.mockMvc.perform(get(Constants.API_USERS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -54,7 +55,7 @@ public void getUserNotFound() throws Exception { } @Test - public void getUserOk() throws Exception { + void getUserOk() throws Exception { String identifier = "USER1"; this.mockMvc.perform(get(Constants.API_USERS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.OK.value())); @@ -62,7 +63,7 @@ public void getUserOk() throws Exception { } @Test - public void getUsersOk() throws Exception { + void getUsersOk() throws Exception { JSONObject jo = new JSONObject(); jo.put("totalElements", userRepository.count()); jo.put("numberOfElements", userRepository.count()); @@ -72,14 +73,14 @@ public void getUsersOk() throws Exception { } @Test - public void putUserCreateUpdateDelete() throws Exception { + void putUserCreateUpdateDelete() throws Exception { String identifier = "TESTPUT"; // create user - status created User user = initGestionnaire(identifier); String jsonUser = createJson(user); mockMvc.perform( - put(Constants.API_USERS_ID, identifier).content(jsonUser).contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_USERS_ID, identifier).content(jsonUser).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonUser.toString(), false)); assertDoesNotThrow(() -> userService.findByIdentifier(identifier)); @@ -91,19 +92,19 @@ public void putUserCreateUpdateDelete() throws Exception { user.setRole(User.UserRoleType.ASSISTANCE); String jsonUserUpdate = createJson(user); mockMvc.perform(put(Constants.API_USERS_ID, identifier).content(jsonUserUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonUserUpdate.toString(), false)); User userFoundAfterUpdate = userService.findByIdentifier(identifier); assertEquals(User.UserRoleType.ASSISTANCE, userFoundAfterUpdate.getRole()); List listUpdate = new ArrayList<>( userEventService.findUserEventsByUser(userFoundAfterUpdate)); - assertEquals(listUpdate.size(), 2); - assertEquals(listUpdate.get(1).getType(), UserEventType.UPDATE); + assertEquals(2, listUpdate.size()); + assertEquals(UserEventType.UPDATE, listUpdate.get(1).getType()); // delete user mockMvc.perform(delete(Constants.API_USERS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertThrows(NotFoundException.class,() -> userService.findByIdentifier(identifier)); + assertThrows(NotFoundException.class, () -> userService.findByIdentifier(identifier)); assertTrue(userEventService.findUserEventsByUser(userFoundAfterUpdate).isEmpty()); @@ -114,15 +115,15 @@ public void putUserCreateUpdateDelete() throws Exception { } @Test - public void putUsersErrorId() throws Exception { + void putUsersErrorId() throws Exception { String identifier = "NEWONE"; String otherIdentifier = "WRONG"; User user = initGestionnaire(identifier); String jsonUser = createJson(user); mockMvc.perform(put(Constants.API_USERS_ID, otherIdentifier).content(jsonUser) - .contentType(MediaType.APPLICATION_JSON)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) - .andExpect(content().string("id and user identifier don't match")); + .andExpect(content().json(JsonUtil.createJsonErrorBadRequest("id and user identifier don't match"))); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java index 9c7d6705..bf163ea7 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java @@ -21,29 +21,29 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class UserEventControllerTest { +class UserEventControllerTest { @Autowired private MockMvc mockMvc; @Test - public void getUserEventOk() throws Exception { + void getUserEventOk() throws Exception { String identifier = "USER1"; String json = createJsonUserEvent(identifier, null); - this.mockMvc.perform(get(Constants.API_USERS_ID_USEREVENTS,identifier)).andDo(print()).andExpect(status().isOk()) - .andExpect(content().json(json, false)); + this.mockMvc.perform(get(Constants.API_USERS_ID_USEREVENTS, identifier)).andDo(print()).andExpect(status().isOk()) + .andExpect(content().json(json, false)); } @Test - public void getUserEventNotFound() throws Exception { + void getUserEventNotFound() throws Exception { String identifier = "CONT500"; - this.mockMvc.perform(get(Constants.API_USERS_ID_USEREVENTS,identifier)).andDo(print()) - .andExpect(status().is(HttpStatus.NOT_FOUND.value())); + this.mockMvc.perform(get(Constants.API_USERS_ID_USEREVENTS, identifier)).andDo(print()) + .andExpect(status().is(HttpStatus.NOT_FOUND.value())); } - private String createJsonUserEvent(String identifier, JSONObject payload ) throws JSONException { + private String createJsonUserEvent(String identifier, JSONObject payload) throws JSONException { JSONObject jo = new JSONObject(); JSONObject joPayload = new JSONObject(); joPayload.put("identifier", identifier); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/util/JsonUtil.java b/src/test/java/fr/insee/survey/datacollectionmanagement/util/JsonUtil.java new file mode 100644 index 00000000..40221c03 --- /dev/null +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/util/JsonUtil.java @@ -0,0 +1,19 @@ +package fr.insee.survey.datacollectionmanagement.util; + +import net.minidev.json.JSONObject; +import org.springframework.http.HttpStatus; + +public class JsonUtil { + + + public static String createJsonError(int code, String message) { + JSONObject jo = new JSONObject(); + jo.put("code", code); + jo.put("message", message); + return jo.toString(); + } + + public static String createJsonErrorBadRequest(String message) { + return createJsonError(HttpStatus.BAD_REQUEST.value(), message); + } +}