diff --git a/backend/src/main/java/ch/puzzle/okr/ErrorKey.java b/backend/src/main/java/ch/puzzle/okr/ErrorKey.java index f5a67168eb..c460e66b4e 100644 --- a/backend/src/main/java/ch/puzzle/okr/ErrorKey.java +++ b/backend/src/main/java/ch/puzzle/okr/ErrorKey.java @@ -1,8 +1,22 @@ package ch.puzzle.okr; public enum ErrorKey { - ATTRIBUTE_NULL, ATTRIBUTE_CHANGED, ATTRIBUTE_SET_FORBIDDEN, ATTRIBUTE_NOT_SET, ATTRIBUTE_CANNOT_CHANGE, - ATTRIBUTE_MUST_BE_DRAFT, KEY_RESULT_CONVERSION, ALREADY_EXISTS_SAME_NAME, CONVERT_TOKEN, DATA_HAS_BEEN_UPDATED, - MODEL_NULL, MODEL_WITH_ID_NOT_FOUND, NOT_AUTHORIZED_TO_READ, NOT_AUTHORIZED_TO_WRITE, NOT_AUTHORIZED_TO_DELETE, - TOKEN_NULL, TRIED_TO_DELETE_LAST_ADMIN, TRIED_TO_REMOVE_LAST_OKR_CHAMPION + ATTRIBUTE_NULL, + ATTRIBUTE_CHANGED, + ATTRIBUTE_SET_FORBIDDEN, + ATTRIBUTE_NOT_SET, + ATTRIBUTE_CANNOT_CHANGE, + ATTRIBUTE_MUST_BE_DRAFT, + KEY_RESULT_CONVERSION, + ALREADY_EXISTS_SAME_NAME, + CONVERT_TOKEN, + DATA_HAS_BEEN_UPDATED, + MODEL_NULL, + MODEL_WITH_ID_NOT_FOUND, + NOT_AUTHORIZED_TO_READ, + NOT_AUTHORIZED_TO_WRITE, + NOT_AUTHORIZED_TO_DELETE, + TOKEN_NULL, + TRIED_TO_DELETE_LAST_ADMIN, + TRIED_TO_REMOVE_LAST_OKR_CHAMPION } diff --git a/backend/src/main/java/ch/puzzle/okr/ForwardFilter.java b/backend/src/main/java/ch/puzzle/okr/ForwardFilter.java index c5c8368a11..c530d13647 100644 --- a/backend/src/main/java/ch/puzzle/okr/ForwardFilter.java +++ b/backend/src/main/java/ch/puzzle/okr/ForwardFilter.java @@ -1,9 +1,8 @@ package ch.puzzle.okr; -import java.io.IOException; import jakarta.servlet.*; import jakarta.servlet.http.HttpServletRequest; - +import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.filter.GenericFilterBean; diff --git a/backend/src/main/java/ch/puzzle/okr/OkrApplication.java b/backend/src/main/java/ch/puzzle/okr/OkrApplication.java index 830bac19ad..35c4585e55 100644 --- a/backend/src/main/java/ch/puzzle/okr/OkrApplication.java +++ b/backend/src/main/java/ch/puzzle/okr/OkrApplication.java @@ -10,7 +10,7 @@ public class OkrApplication { public static void main(String[] args) { new SpringApplicationBuilder(OkrApplication.class) // - .initializers(new OkrApplicationContextInitializer()) // - .run(args); + .initializers(new OkrApplicationContextInitializer()) // + .run(args); } } diff --git a/backend/src/main/java/ch/puzzle/okr/OkrErrorAttributes.java b/backend/src/main/java/ch/puzzle/okr/OkrErrorAttributes.java index 0a721ff03b..1b84868059 100644 --- a/backend/src/main/java/ch/puzzle/okr/OkrErrorAttributes.java +++ b/backend/src/main/java/ch/puzzle/okr/OkrErrorAttributes.java @@ -1,13 +1,12 @@ package ch.puzzle.okr; import ch.puzzle.okr.exception.OkrResponseStatusException; +import java.util.Map; import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; -import java.util.Map; - @Component public class OkrErrorAttributes extends DefaultErrorAttributes { diff --git a/backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java b/backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java index a7613f5b26..d051559ccf 100644 --- a/backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java +++ b/backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java @@ -13,8 +13,11 @@ public class OpenAPI30Configuration { public OpenAPI customizeOpenAPI() { final String securitySchemeName = "bearerAuth"; return new OpenAPI().addSecurityItem(new SecurityRequirement().addList(securitySchemeName)) - .components(new Components().addSecuritySchemes(securitySchemeName, new SecurityScheme() - .name(securitySchemeName).type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT"))); + .components(new Components().addSecuritySchemes(securitySchemeName, + new SecurityScheme().name(securitySchemeName) + .type(SecurityScheme.Type.HTTP) + .scheme("bearer") + .bearerFormat("JWT"))); } } diff --git a/backend/src/main/java/ch/puzzle/okr/SecurityConfig.java b/backend/src/main/java/ch/puzzle/okr/SecurityConfig.java index 051f3309f0..0bfe2f4459 100644 --- a/backend/src/main/java/ch/puzzle/okr/SecurityConfig.java +++ b/backend/src/main/java/ch/puzzle/okr/SecurityConfig.java @@ -1,5 +1,9 @@ package ch.puzzle.okr; +import static org.springframework.security.web.header.writers.CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP; +import static org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER; +import static org.springframework.security.web.header.writers.XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK; + import com.nimbusds.jose.proc.SecurityContext; import com.nimbusds.jwt.proc.ConfigurableJWTProcessor; import com.nimbusds.jwt.proc.DefaultJWTProcessor; @@ -33,10 +37,6 @@ import org.springframework.security.web.header.writers.CrossOriginResourcePolicyHeaderWriter; import org.springframework.security.web.header.writers.StaticHeadersWriter; -import static org.springframework.security.web.header.writers.CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP; -import static org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER; -import static org.springframework.security.web.header.writers.XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK; - @Configuration @EnableWebSecurity @EnableMethodSecurity @@ -50,17 +50,18 @@ public class SecurityConfig { @Bean @Order(1) // Must be First order! Otherwise unauthorized Requests are sent to Controllers - public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http, @Value("${connect.src}") String connectSrc) - throws Exception { + public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http, @Value("${connect.src}") + String connectSrc) throws Exception { this.connectSrc = connectSrc; setHeaders(http); http.addFilterAfter(new ForwardFilter(), BasicAuthenticationFilter.class); logger.debug("*** apiSecurityFilterChain reached"); return http.cors(Customizer.withDefaults()) - .authorizeHttpRequests(e -> e.requestMatchers("/api/**").authenticated().anyRequest().permitAll()) - .exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))) - .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())).build(); + .authorizeHttpRequests(e -> e.requestMatchers("/api/**").authenticated().anyRequest().permitAll()) + .exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))) + .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())) + .build(); } @Bean @@ -81,52 +82,53 @@ JWTProcessor jwtProcessor(JWTClaimsSetAwareJWSKeySelector jwtProcessor, OAuth2TokenValidator jwtValidator) { NimbusJwtDecoder decoder = new NimbusJwtDecoder(jwtProcessor); OAuth2TokenValidator validator = new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefault(), - jwtValidator); + jwtValidator); decoder.setJwtValidator(validator); return decoder; } private HttpSecurity setHeaders(HttpSecurity http) throws Exception { - return http.headers(headers -> headers - .contentSecurityPolicy(c -> c.policyDirectives(okrContentSecurityPolicy())) - .crossOriginEmbedderPolicy(c -> c.policy(REQUIRE_CORP)) - .crossOriginOpenerPolicy(c -> c.policy(OPENER_SAME_ORIGIN)) - .crossOriginResourcePolicy(c -> c.policy(RESOURCE_SAME_ORIGIN)) - .addHeaderWriter(new StaticHeadersWriter("X-Permitted-Cross-Domain-Policies", "none")) - .frameOptions(HeadersConfigurer.FrameOptionsConfig::deny) - .xssProtection(c -> c.headerValue(ENABLED_MODE_BLOCK)) - .httpStrictTransportSecurity(c -> c.includeSubDomains(true).maxAgeInSeconds(31536000)) - .referrerPolicy(c -> c.policy(NO_REFERRER)).permissionsPolicy(c -> c.policy(okrPermissionPolicy()))); + return http.headers(headers -> headers.contentSecurityPolicy(c -> c.policyDirectives(okrContentSecurityPolicy())) + .crossOriginEmbedderPolicy(c -> c.policy(REQUIRE_CORP)) + .crossOriginOpenerPolicy(c -> c.policy(OPENER_SAME_ORIGIN)) + .crossOriginResourcePolicy(c -> c.policy(RESOURCE_SAME_ORIGIN)) + .addHeaderWriter(new StaticHeadersWriter("X-Permitted-Cross-Domain-Policies", + "none")) + .frameOptions(HeadersConfigurer.FrameOptionsConfig::deny) + .xssProtection(c -> c.headerValue(ENABLED_MODE_BLOCK)) + .httpStrictTransportSecurity(c -> c.includeSubDomains(true) + .maxAgeInSeconds(31536000)) + .referrerPolicy(c -> c.policy(NO_REFERRER)) + .permissionsPolicy(c -> c.policy(okrPermissionPolicy()))); } private String okrContentSecurityPolicy() { return "default-src 'self';" // - + "script-src 'self' 'unsafe-inline';" // - + " style-src 'self' 'unsafe-inline';" // - + " object-src 'none';" // - + " base-uri 'self';" // - + " connect-src 'self' " + connectSrc + ";" // - + " font-src 'self';" // - + " frame-src 'self';" // - + " img-src 'self' data: ;" // - + " manifest-src 'self';" // - + " media-src 'self';" // - + " worker-src 'none';"; // + + "script-src 'self' 'unsafe-inline';" // + + " style-src 'self' 'unsafe-inline';" // + + " object-src 'none';" // + + " base-uri 'self';" // + + " connect-src 'self' " + connectSrc + ";" // + + " font-src 'self';" // + + " frame-src 'self';" // + + " img-src 'self' data: ;" // + + " manifest-src 'self';" // + + " media-src 'self';" // + + " worker-src 'none';"; // } private String okrPermissionPolicy() { return "accelerometer=(), ambient-light-sensor=(), autoplay=(), " - + "battery=(), camera=(), cross-origin-isolated=(), display-capture=(), document-domain=(), encrypted-media=(), " - + "execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=()," - + " geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), " - + "midi=(), navigation-override=(), payment=(), picture-in-picture=()," - + " publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(self), " - + "usb=(), web-share=(), xr-spatial-tracking=()"; + + "battery=(), camera=(), cross-origin-isolated=(), display-capture=(), document-domain=(), encrypted-media=(), " + + "execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=()," + + " geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), " + + "midi=(), navigation-override=(), payment=(), picture-in-picture=()," + + " publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(self), " + + "usb=(), web-share=(), xr-spatial-tracking=()"; } @Bean - public AuthenticationEventPublisher authenticationEventPublisher( - ApplicationEventPublisher applicationEventPublisher) { + public AuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { return new DefaultAuthenticationEventPublisher(applicationEventPublisher); } diff --git a/backend/src/main/java/ch/puzzle/okr/UserKeyGenerator.java b/backend/src/main/java/ch/puzzle/okr/UserKeyGenerator.java index 144a056e30..c66adf8a65 100644 --- a/backend/src/main/java/ch/puzzle/okr/UserKeyGenerator.java +++ b/backend/src/main/java/ch/puzzle/okr/UserKeyGenerator.java @@ -2,10 +2,9 @@ import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantContext; -import org.springframework.cache.interceptor.KeyGenerator; - import java.lang.reflect.Method; import java.text.MessageFormat; +import org.springframework.cache.interceptor.KeyGenerator; public class UserKeyGenerator implements KeyGenerator { @Override diff --git a/backend/src/main/java/ch/puzzle/okr/controller/ActionController.java b/backend/src/main/java/ch/puzzle/okr/controller/ActionController.java index d6b9855b7b..85270e87ae 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/ActionController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/ActionController.java @@ -9,9 +9,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; -import org.springframework.web.bind.annotation.*; - import java.util.List; +import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("api/v2/action") @@ -27,20 +26,22 @@ public ActionController(ActionAuthorizationService actionAuthorizationService, A @Operation(summary = "Update Actions", description = "Update Actions of KeyResult") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Updated Actions of KeyResult", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ActionDto.class)) }), - @ApiResponse(responseCode = "400", description = "Can't update Actions, attributes are not set", content = @Content) }) + @Content(mediaType = "application/json", schema = @Schema(implementation = ActionDto.class))}), + @ApiResponse(responseCode = "400", description = "Can't update Actions, attributes are not set", content = @Content)}) @PutMapping - public void updateActions( - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Action as json to update existing Actions.", required = true) @RequestBody List actionDtoList) { + public void updateActions(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Action as json to update existing Actions.", required = true) + @RequestBody + List actionDtoList) { List actionList = actionMapper.toActions(actionDtoList); actionAuthorizationService.updateEntities(actionList); } @Operation(summary = "Delete Action by Id", description = "Delete Action by Id") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted Action by Id"), - @ApiResponse(responseCode = "404", description = "Did not find the Action with requested id") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted Action by Id"), + @ApiResponse(responseCode = "404", description = "Did not find the Action with requested id")}) @DeleteMapping("/{actionId}") - public void deleteActionById(@PathVariable long actionId) { + public void deleteActionById(@PathVariable + long actionId) { actionAuthorizationService.deleteActionByActionId(actionId); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/AlignmentController.java b/backend/src/main/java/ch/puzzle/okr/controller/AlignmentController.java index 85b6a77ec1..40b0d359e8 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/AlignmentController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/AlignmentController.java @@ -8,6 +8,7 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -15,8 +16,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.util.List; - @RestController @RequestMapping("api/v2/alignments") public class AlignmentController { @@ -24,7 +23,7 @@ public class AlignmentController { private final AlignmentSelectionBusinessService alignmentSelectionBusinessService; public AlignmentController(AlignmentSelectionMapper alignmentSelectionMapper, - AlignmentSelectionBusinessService alignmentSelectionBusinessService) { + AlignmentSelectionBusinessService alignmentSelectionBusinessService) { this.alignmentSelectionMapper = alignmentSelectionMapper; this.alignmentSelectionBusinessService = alignmentSelectionBusinessService; } @@ -32,14 +31,14 @@ public AlignmentController(AlignmentSelectionMapper alignmentSelectionMapper, @Operation(summary = "Get all objectives and their key results to select the alignment", description = "Get a list of objectives with their key results to select the alignment") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned a list of objectives with their key results to select the alignment", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = AlignmentObjectiveDto.class)) }), - @ApiResponse(responseCode = "400", description = "Can't return list of objectives with their key results to select the alignment", content = @Content) }) + @Content(mediaType = "application/json", schema = @Schema(implementation = AlignmentObjectiveDto.class))}), + @ApiResponse(responseCode = "400", description = "Can't return list of objectives with their key results to select the alignment", content = @Content)}) @GetMapping("/selections") - public ResponseEntity> getAlignmentSelections( - @RequestParam(required = false, defaultValue = "", name = "quarter") Long quarterFilter, - @RequestParam(required = false, defaultValue = "", name = "team") Long teamFilter) { + public ResponseEntity> getAlignmentSelections(@RequestParam(required = false, defaultValue = "", name = "quarter") + Long quarterFilter, @RequestParam(required = false, defaultValue = "", name = "team") + Long teamFilter) { return ResponseEntity.status(HttpStatus.OK) - .body(alignmentSelectionMapper.toDto(alignmentSelectionBusinessService - .getAlignmentSelectionByQuarterIdAndTeamIdNot(quarterFilter, teamFilter))); + .body(alignmentSelectionMapper.toDto(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(quarterFilter, + teamFilter))); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/CacheController.java b/backend/src/main/java/ch/puzzle/okr/controller/CacheController.java index ee46548003..1e2cc88e2f 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/CacheController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/CacheController.java @@ -18,14 +18,14 @@ public CacheController(CacheService cacheService) { } @Operation(summary = "Delete authorization users cache", description = "Delete authorization users cache") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Authorization users cache deleted") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Authorization users cache deleted")}) @PostMapping("emptyAuthorizationUsersCache") public void emptyAuthorizationUsersCache() { cacheService.emptyAuthorizationUsersCache(); } @Operation(summary = "Delete all caches", description = "Delete all caches") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "All caches deleted") }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "All caches deleted")}) @PostMapping("emptyAllCaches") public void emptyAllCaches() { cacheService.emptyAllCaches(); diff --git a/backend/src/main/java/ch/puzzle/okr/controller/CheckInController.java b/backend/src/main/java/ch/puzzle/okr/controller/CheckInController.java index 83c6030f2e..3af382bb89 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/CheckInController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/CheckInController.java @@ -29,54 +29,59 @@ public CheckInController(CheckInMapper checkInMapper, CheckInAuthorizationServic @Operation(summary = "Get Check-in", description = "Get Check-in by ID") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned a Check-in with a specified ID", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class))}), @ApiResponse(responseCode = "401", description = "Not authorized to read Check-in", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find a Check-in with a specified ID", content = @Content) }) + @ApiResponse(responseCode = "404", description = "Did not find a Check-in with a specified ID", content = @Content)}) @GetMapping("/{id}") - public ResponseEntity getCheckInById(@PathVariable long id) { + public ResponseEntity getCheckInById(@PathVariable + long id) { return ResponseEntity.status(HttpStatus.OK) - .body(checkInMapper.toDto(this.checkInAuthorizationService.getEntityById(id))); + .body(checkInMapper.toDto(this.checkInAuthorizationService.getEntityById(id))); } @Operation(summary = "Update Check-in", description = "Update a Check-in by ID") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Updated Check-in in db", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class))}), @ApiResponse(responseCode = "400", description = "Can't create new Check-in, attributes are not set", content = @Content), @ApiResponse(responseCode = "401", description = "Not authorized to update Check-in", content = @Content), @ApiResponse(responseCode = "404", description = "Given ID of Check-in wasn't found.", content = @Content), - @ApiResponse(responseCode = "422", description = "Can't update Check-in since Check-in was updated or deleted by another user.", content = @Content) }) + @ApiResponse(responseCode = "422", description = "Can't update Check-in since Check-in was updated or deleted by another user.", content = @Content)}) @PutMapping("/{id}") - public ResponseEntity updateCheckIn( - @Parameter(description = "The ID for updating a Check-in.", required = true) @PathVariable Long id, - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Check-in as json to update an existing Check-in.", required = true) @RequestBody CheckInDto checkInDto) { + public ResponseEntity updateCheckIn(@Parameter(description = "The ID for updating a Check-in.", required = true) + @PathVariable + Long id, @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Check-in as json to update an existing Check-in.", required = true) + @RequestBody + CheckInDto checkInDto) { CheckIn checkIn = checkInMapper.toCheckIn(checkInDto); - CheckInDto updatedCheckIn = this.checkInMapper - .toDto(this.checkInAuthorizationService.updateEntity(id, checkIn)); + CheckInDto updatedCheckIn = this.checkInMapper.toDto(this.checkInAuthorizationService.updateEntity(id, + checkIn)); return ResponseEntity.status(HttpStatus.OK).body(updatedCheckIn); } @Operation(summary = "Create Check-in", description = "Create a new Check-in") @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "Created new Check-in.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class))}), @ApiResponse(responseCode = "400", description = "Can't create new Check-in, not allowed to give an ID", content = @Content), - @ApiResponse(responseCode = "401", description = "Not authorized to create Check-in", content = @Content) }) + @ApiResponse(responseCode = "401", description = "Not authorized to create Check-in", content = @Content)}) @PostMapping - public ResponseEntity createCheckIn( - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Check-in as json to create a new Check-in.", required = true) @RequestBody CheckInDto checkInDto) { + public ResponseEntity createCheckIn(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Check-in as json to create a new Check-in.", required = true) + @RequestBody + CheckInDto checkInDto) { CheckIn checkIn = checkInMapper.toCheckIn(checkInDto); CheckInDto createdCheckIn = checkInMapper.toDto(checkInAuthorizationService.createEntity(checkIn)); return ResponseEntity.status(HttpStatus.CREATED).body(createdCheckIn); } @Operation(summary = "Delete Check-in by ID", description = "Delete Check-in by ID") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted Check-in by ID"), + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted Check-in by ID"), @ApiResponse(responseCode = "401", description = "Not authorized to delete Check-in", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Check-in with requested ID") }) + @ApiResponse(responseCode = "404", description = "Did not find the Check-in with requested ID")}) @DeleteMapping("/{id}") - public void deleteCheckInById( - @Parameter(description = "The ID of an Check-in to delete it.", required = true) @PathVariable long id) { + public void deleteCheckInById(@Parameter(description = "The ID of an Check-in to delete it.", required = true) + @PathVariable + long id) { this.checkInAuthorizationService.deleteEntityById(id); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/ClientConfigController.java b/backend/src/main/java/ch/puzzle/okr/controller/ClientConfigController.java index ec45e2f782..d6b72cef3b 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/ClientConfigController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/ClientConfigController.java @@ -21,7 +21,7 @@ public ClientConfigController(ClientConfigService configService) { @GetMapping("/config") public ResponseEntity getConfig(HttpServletRequest request) { return ResponseEntity.status(HttpStatus.OK) - .body(configService.getConfigBasedOnActiveEnv(request.getServerName())); + .body(configService.getConfigBasedOnActiveEnv(request.getServerName())); } @RequestMapping(value = "/**/{[path:[^\\.]*}") diff --git a/backend/src/main/java/ch/puzzle/okr/controller/CompletedController.java b/backend/src/main/java/ch/puzzle/okr/controller/CompletedController.java index 4b8e10e5dc..ee75a9cbdd 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/CompletedController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/CompletedController.java @@ -21,7 +21,7 @@ public class CompletedController { private final CompletedMapper completedMapper; public CompletedController(CompletedAuthorizationService completedAuthorizationService, - CompletedMapper completedMapper) { + CompletedMapper completedMapper) { this.completedAuthorizationService = completedAuthorizationService; this.completedMapper = completedMapper; } @@ -29,22 +29,24 @@ public CompletedController(CompletedAuthorizationService completedAuthorizationS @Operation(summary = "Create Completed", description = "Create a new Completed Reference.") @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "Created new Completed.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = Completed.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = Completed.class))}), @ApiResponse(responseCode = "401", description = "Not authorized to create Completed Reference", content = @Content), - @ApiResponse(responseCode = "404", description = "Could not create Completed Reference", content = @Content) }) + @ApiResponse(responseCode = "404", description = "Could not create Completed Reference", content = @Content)}) @PostMapping - public ResponseEntity createCompleted(@RequestBody CompletedDto completedDto) { + public ResponseEntity createCompleted(@RequestBody + CompletedDto completedDto) { Completed completed = completedMapper.toCompleted(completedDto); Completed createdCompleted = completedAuthorizationService.createCompleted(completed); return ResponseEntity.status(HttpStatus.CREATED).body(completedMapper.toDto(createdCompleted)); } @Operation(summary = "Delete Completed by Objective Id", description = "Delete Completed Reference by Objective Id") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted Completed by Objective Id"), + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted Completed by Objective Id"), @ApiResponse(responseCode = "401", description = "Not authorized to delete Completed Reference", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Completed with requested Objective id") }) + @ApiResponse(responseCode = "404", description = "Did not find the Completed with requested Objective id")}) @DeleteMapping("/{objectiveId}") - public void deleteCompletedByObjectiveId(@PathVariable long objectiveId) { + public void deleteCompletedByObjectiveId(@PathVariable + long objectiveId) { completedAuthorizationService.deleteCompletedByObjectiveId(objectiveId); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/KeyResultController.java b/backend/src/main/java/ch/puzzle/okr/controller/KeyResultController.java index 0940bdc333..03b9dadd4a 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/KeyResultController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/KeyResultController.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.controller; +import static org.springframework.http.HttpStatus.*; + import ch.puzzle.okr.dto.checkin.CheckInDto; import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultMetricDto; @@ -18,13 +20,10 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import java.util.List; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import java.util.List; - -import static org.springframework.http.HttpStatus.*; - @RestController @RequestMapping("api/v2/keyresults") public class KeyResultController { @@ -36,8 +35,8 @@ public class KeyResultController { private final ActionMapper actionMapper; public KeyResultController(KeyResultAuthorizationService keyResultAuthorizationService, - ActionAuthorizationService actionAuthorizationService, KeyResultMapper keyResultMapper, - CheckInMapper checkInMapper, ActionMapper actionMapper) { + ActionAuthorizationService actionAuthorizationService, KeyResultMapper keyResultMapper, + CheckInMapper checkInMapper, ActionMapper actionMapper) { this.keyResultAuthorizationService = keyResultAuthorizationService; this.actionAuthorizationService = actionAuthorizationService; this.keyResultMapper = keyResultMapper; @@ -48,12 +47,13 @@ public KeyResultController(KeyResultAuthorizationService keyResultAuthorizationS @Operation(summary = "Get KeyResult by Id", description = "Get KeyResult by Id") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Got KeyResult by Id", content = { - @Content(mediaType = "application/json", schema = @Schema(allOf = { KeyResultMetricDto.class, - KeyResultOrdinalDto.class })) }), + @Content(mediaType = "application/json", schema = @Schema(allOf = {KeyResultMetricDto.class, + KeyResultOrdinalDto.class}))}), @ApiResponse(responseCode = "401", description = "Not authorized to read a KeyResult", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the KeyResult with requested id", content = @Content) }) + @ApiResponse(responseCode = "404", description = "Did not find the KeyResult with requested id", content = @Content)}) @GetMapping("/{id}") - public KeyResultDto getKeyResultById(@PathVariable long id) { + public KeyResultDto getKeyResultById(@PathVariable + long id) { KeyResult keyResult = keyResultAuthorizationService.getEntityById(id); List actionList = actionAuthorizationService.getActionsByKeyResult(keyResult); return keyResultMapper.toDto(keyResult, actionList); @@ -62,24 +62,26 @@ public KeyResultDto getKeyResultById(@PathVariable long id) { @Operation(summary = "Get Check-ins from KeyResult", description = "Get all Check-ins from one KeyResult by keyResultId.") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned all Check-ins from KeyResult.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = CheckInDto.class))}), @ApiResponse(responseCode = "401", description = "Not authorized to read Check-ins from a KeyResult", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find a KeyResult with a specified ID to get Check-ins from.", content = @Content) }) + @ApiResponse(responseCode = "404", description = "Did not find a KeyResult with a specified ID to get Check-ins from.", content = @Content)}) @GetMapping("/{id}/checkins") - public List getCheckInsFromKeyResult( - @Parameter(description = "The ID for getting all Check-ins from a KeyResult.", required = true) @PathVariable long id) { + public List getCheckInsFromKeyResult(@Parameter(description = "The ID for getting all Check-ins from a KeyResult.", required = true) + @PathVariable + long id) { return keyResultAuthorizationService.getAllCheckInsByKeyResult(id).stream().map(checkInMapper::toDto).toList(); } @Operation(summary = "Create KeyResult", description = "Create a new KeyResult.") @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "Created new KeyResult.", content = { - @Content(mediaType = "application/json", schema = @Schema(allOf = { KeyResultDto.class, - KeyResultOrdinalDto.class })) }), + @Content(mediaType = "application/json", schema = @Schema(allOf = {KeyResultDto.class, + KeyResultOrdinalDto.class}))}), @ApiResponse(responseCode = "401", description = "Not authorized to create a KeyResult", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find an Objective on which the KeyResult tries to refer to.", content = @Content) }) + @ApiResponse(responseCode = "404", description = "Did not find an Objective on which the KeyResult tries to refer to.", content = @Content)}) @PostMapping - public ResponseEntity createKeyResult(@RequestBody KeyResultDto keyResultDto) { + public ResponseEntity createKeyResult(@RequestBody + KeyResultDto keyResultDto) { KeyResult keyResult = keyResultAuthorizationService.createEntity(keyResultMapper.toKeyResult(keyResultDto)); List actionList = actionMapper.toActions(keyResultDto.getActionList(), keyResult); List savedActions = actionAuthorizationService.createEntities(actionList); @@ -90,32 +92,35 @@ public ResponseEntity createKeyResult(@RequestBody KeyResultDto ke @Operation(summary = "Update KeyResult", description = "Update a KeyResult by ID.") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Updated KeyResult in db.", content = { - @Content(mediaType = "application/json", schema = @Schema(allOf = { KeyResultDto.class, - KeyResultOrdinalDto.class })) }), + @Content(mediaType = "application/json", schema = @Schema(allOf = {KeyResultDto.class, + KeyResultOrdinalDto.class}))}), @ApiResponse(responseCode = "226", description = "Updated KeyResult in db but keyResultType was not changed", content = { - @Content(mediaType = "application/json", schema = @Schema(allOf = KeyResultDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(allOf = KeyResultDto.class))}), @ApiResponse(responseCode = "401", description = "Not authorized to update a KeyResult", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find a KeyResult with a specified ID to update.", content = @Content), - @ApiResponse(responseCode = "422", description = "Can't update KeyResult since KeyResult was updated or deleted by another user.", content = @Content) }) + @ApiResponse(responseCode = "422", description = "Can't update KeyResult since KeyResult was updated or deleted by another user.", content = @Content)}) @PutMapping("/{id}") - public ResponseEntity updateKeyResult( - @Parameter(description = "The ID for updating a KeyResult.", required = true) @PathVariable long id, - @RequestBody KeyResultDto keyResultDto) { + public ResponseEntity updateKeyResult(@Parameter(description = "The ID for updating a KeyResult.", required = true) + @PathVariable + long id, @RequestBody + KeyResultDto keyResultDto) { KeyResult keyResult = keyResultMapper.toKeyResult(keyResultDto); List actionList = actionMapper.toActions(keyResultDto.getActionList(), keyResult); boolean isKeyResultImUsed = keyResultAuthorizationService.isImUsed(id, keyResult); - KeyResultWithActionList updatedKeyResult = keyResultAuthorizationService.updateEntities(id, keyResult, - actionList); + KeyResultWithActionList updatedKeyResult = keyResultAuthorizationService.updateEntities(id, + keyResult, + actionList); return ResponseEntity.status(isKeyResultImUsed ? IM_USED : OK) - .body(keyResultMapper.toDto(updatedKeyResult.keyResult(), updatedKeyResult.actionList())); + .body(keyResultMapper.toDto(updatedKeyResult.keyResult(), updatedKeyResult.actionList())); } @Operation(summary = "Delete KeyResult by Id", description = "Delete KeyResult by Id") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted KeyResult by Id"), + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted KeyResult by Id"), @ApiResponse(responseCode = "401", description = "Not authorized to delete a KeyResult", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the KeyResult with requested id") }) + @ApiResponse(responseCode = "404", description = "Did not find the KeyResult with requested id")}) @DeleteMapping("/{id}") - public void deleteKeyResultById(@PathVariable long id) { + public void deleteKeyResultById(@PathVariable + long id) { keyResultAuthorizationService.deleteEntityById(id); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/ObjectiveController.java b/backend/src/main/java/ch/puzzle/okr/controller/ObjectiveController.java index 61e0f2cab8..3a3b603e0a 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/ObjectiveController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/ObjectiveController.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.controller; +import static org.springframework.http.HttpStatus.IM_USED; +import static org.springframework.http.HttpStatus.OK; + import ch.puzzle.okr.dto.ObjectiveDto; import ch.puzzle.okr.mapper.ObjectiveMapper; import ch.puzzle.okr.models.Objective; @@ -14,9 +17,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import static org.springframework.http.HttpStatus.IM_USED; -import static org.springframework.http.HttpStatus.OK; - @RestController @RequestMapping("api/v2/objectives") public class ObjectiveController { @@ -24,7 +24,7 @@ public class ObjectiveController { private final ObjectiveMapper objectiveMapper; public ObjectiveController(ObjectiveAuthorizationService objectiveAuthorizationService, - ObjectiveMapper objectiveMapper) { + ObjectiveMapper objectiveMapper) { this.objectiveAuthorizationService = objectiveAuthorizationService; this.objectiveMapper = objectiveMapper; } @@ -32,71 +32,78 @@ public ObjectiveController(ObjectiveAuthorizationService objectiveAuthorizationS @Operation(summary = "Get Objective", description = "Get an Objective by ID") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned an Objective with a specified ID", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class))}), @ApiResponse(responseCode = "401", description = "Not authorized to read an Objective", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find an Objective with a specified ID", content = @Content) }) + @ApiResponse(responseCode = "404", description = "Did not find an Objective with a specified ID", content = @Content)}) @GetMapping("/{id}") - public ResponseEntity getObjective( - @Parameter(description = "The ID for getting an Objective.", required = true) @PathVariable Long id) { + public ResponseEntity getObjective(@Parameter(description = "The ID for getting an Objective.", required = true) + @PathVariable + Long id) { return ResponseEntity.status(HttpStatus.OK) - .body(objectiveMapper.toDto(objectiveAuthorizationService.getEntityById(id))); + .body(objectiveMapper.toDto(objectiveAuthorizationService.getEntityById(id))); } @Operation(summary = "Delete Objective by ID", description = "Delete Objective by ID") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted Objective by ID"), + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted Objective by ID"), @ApiResponse(responseCode = "401", description = "Not authorized to delete an Objective", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Objective with requested ID") }) + @ApiResponse(responseCode = "404", description = "Did not find the Objective with requested ID")}) @DeleteMapping("/{id}") - public void deleteObjectiveById( - @Parameter(description = "The ID of an Objective to delete it.", required = true) @PathVariable long id) { + public void deleteObjectiveById(@Parameter(description = "The ID of an Objective to delete it.", required = true) + @PathVariable + long id) { objectiveAuthorizationService.deleteEntityById(id); } @Operation(summary = "Create Objective", description = "Create a new Objective") @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "Created new Objective", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class))}), @ApiResponse(responseCode = "400", description = "Can't create new Objective, not allowed to give an ID", content = @Content), - @ApiResponse(responseCode = "401", description = "Not authorized to create an Objective", content = @Content) }) + @ApiResponse(responseCode = "401", description = "Not authorized to create an Objective", content = @Content)}) @PostMapping - public ResponseEntity createObjective( - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Objective as json to create a new Objective.", required = true) @RequestBody ObjectiveDto objectiveDTO) { + public ResponseEntity createObjective(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Objective as json to create a new Objective.", required = true) + @RequestBody + ObjectiveDto objectiveDTO) { Objective objective = objectiveMapper.toObjective(objectiveDTO); ObjectiveDto createdObjective = objectiveMapper.toDto(objectiveAuthorizationService.createEntity(objective)); return ResponseEntity.status(HttpStatus.CREATED).body(createdObjective); } @Operation(summary = "Duplicate Objective", description = "Duplicate a given Objective") - @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "Duplicated a given Objective", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class)) }) }) + @ApiResponses(value = {@ApiResponse(responseCode = "201", description = "Duplicated a given Objective", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class))})}) @PostMapping("/{id}") - public ResponseEntity duplicateObjective( - @Parameter(description = "The ID for duplicating an Objective.", required = true) @PathVariable Long id, - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Objective which should be duplicated as json", required = true) @RequestBody ObjectiveDto objectiveDTO) { + public ResponseEntity duplicateObjective(@Parameter(description = "The ID for duplicating an Objective.", required = true) + @PathVariable + Long id, @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Objective which should be duplicated as json", required = true) + @RequestBody + ObjectiveDto objectiveDTO) { Objective objective = objectiveMapper.toObjective(objectiveDTO); - ObjectiveDto duplicatedObjectiveDto = objectiveMapper - .toDto(objectiveAuthorizationService.duplicateEntity(id, objective)); + ObjectiveDto duplicatedObjectiveDto = objectiveMapper.toDto(objectiveAuthorizationService.duplicateEntity(id, + objective)); return ResponseEntity.status(HttpStatus.CREATED).body(duplicatedObjectiveDto); } @Operation(summary = "Update Objective", description = "Update Objective by ID") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Updated Objective in db", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class))}), @ApiResponse(responseCode = "226", description = "Updated Objective in db but quarter was not changed", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = ObjectiveDto.class))}), @ApiResponse(responseCode = "400", description = "Can't create new Objective, attributes are not set or tried to set quarter", content = @Content), @ApiResponse(responseCode = "401", description = "Not authorized to update an Objective", content = @Content), @ApiResponse(responseCode = "404", description = "Given ID of Objective wasn't found", content = @Content), - @ApiResponse(responseCode = "422", description = "Can't update Objective since Objective was updated or deleted by another user.", content = @Content) }) + @ApiResponse(responseCode = "422", description = "Can't update Objective since Objective was updated or deleted by another user.", content = @Content)}) @PutMapping("/{id}") - public ResponseEntity updateObjective( - @Parameter(description = "The ID for updating an Objective.", required = true) @PathVariable Long id, - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The objective as json to update an existing Objective.", required = true) @RequestBody ObjectiveDto objectiveDTO) { + public ResponseEntity updateObjective(@Parameter(description = "The ID for updating an Objective.", required = true) + @PathVariable + Long id, @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The objective as json to update an existing Objective.", required = true) + @RequestBody + ObjectiveDto objectiveDTO) { Objective objective = objectiveMapper.toObjective(objectiveDTO); boolean isObjectiveImUsed = objectiveAuthorizationService.isImUsed(objective); - ObjectiveDto updatedObjective = objectiveMapper - .toDto(objectiveAuthorizationService.updateEntity(id, objective)); + ObjectiveDto updatedObjective = objectiveMapper.toDto(objectiveAuthorizationService.updateEntity(id, + objective)); return ResponseEntity.status(isObjectiveImUsed ? IM_USED : OK).body(updatedObjective); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/OverviewController.java b/backend/src/main/java/ch/puzzle/okr/controller/OverviewController.java index ff8dfe009d..0fe9437c6f 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/OverviewController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/OverviewController.java @@ -8,6 +8,7 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -15,8 +16,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.util.List; - @RestController @RequestMapping("api/v2/overview") public class OverviewController { @@ -24,7 +23,7 @@ public class OverviewController { private final OverviewAuthorizationService overviewAuthorizationService; public OverviewController(OverviewMapper overviewMapper, - OverviewAuthorizationService overviewAuthorizationService) { + OverviewAuthorizationService overviewAuthorizationService) { this.overviewMapper = overviewMapper; this.overviewAuthorizationService = overviewAuthorizationService; } @@ -32,16 +31,18 @@ public OverviewController(OverviewMapper overviewMapper, @Operation(summary = "Get all teams and their objectives", description = "Get a List of teams with their objectives") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned a List of teams and their objectives", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = OverviewDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = OverviewDto.class))}), @ApiResponse(responseCode = "400", description = "Can't return list of teams with their objectives", content = @Content), @ApiResponse(responseCode = "401", description = "Not authorized to read teams with their objectives", content = @Content), - @ApiResponse(responseCode = "404", description = "The quarter or one of the teams were not found", content = @Content) }) + @ApiResponse(responseCode = "404", description = "The quarter or one of the teams were not found", content = @Content)}) @GetMapping("") - public ResponseEntity> getOverview( - @RequestParam(required = false, defaultValue = "", name = "team") List teamFilter, - @RequestParam(required = false, defaultValue = "", name = "quarter") Long quarterFilter, - @RequestParam(required = false, defaultValue = "", name = "objectiveQuery") String objectiveQuery) { - return ResponseEntity.status(HttpStatus.OK).body(overviewMapper - .toDto(overviewAuthorizationService.getFilteredOverview(quarterFilter, teamFilter, objectiveQuery))); + public ResponseEntity> getOverview(@RequestParam(required = false, defaultValue = "", name = "team") + List teamFilter, @RequestParam(required = false, defaultValue = "", name = "quarter") + Long quarterFilter, @RequestParam(required = false, defaultValue = "", name = "objectiveQuery") + String objectiveQuery) { + return ResponseEntity.status(HttpStatus.OK) + .body(overviewMapper.toDto(overviewAuthorizationService.getFilteredOverview(quarterFilter, + teamFilter, + objectiveQuery))); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/QuarterController.java b/backend/src/main/java/ch/puzzle/okr/controller/QuarterController.java index 1cc1383dbc..b06c79ca59 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/QuarterController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/QuarterController.java @@ -1,6 +1,5 @@ package ch.puzzle.okr.controller; -import ch.puzzle.okr.dto.TeamDto; import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.service.business.QuarterBusinessService; import io.swagger.v3.oas.annotations.Operation; @@ -8,14 +7,13 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.List; - @RestController @RequestMapping("api/v2/quarters") public class QuarterController { @@ -27,16 +25,16 @@ public QuarterController(QuarterBusinessService quarterBusinessService) { } @Operation(summary = "Get quarters", description = "Get a List of quarters depending on current date") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned a List of quarters", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = Quarter.class)) }) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned a List of quarters", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Quarter.class))})}) @GetMapping("") public ResponseEntity> getCurrentQuarters() { return ResponseEntity.status(HttpStatus.OK).body(this.quarterBusinessService.getQuarters()); } @Operation(summary = "Get current quarter", description = "Get the current quarter depending on current date") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned the current quarter", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = Quarter.class)) }) }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned the current quarter", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Quarter.class))})}) @GetMapping("/current") public ResponseEntity getCurrentQuarter() { return ResponseEntity.status(HttpStatus.OK).body(this.quarterBusinessService.getCurrentQuarter()); diff --git a/backend/src/main/java/ch/puzzle/okr/controller/TeamController.java b/backend/src/main/java/ch/puzzle/okr/controller/TeamController.java index ccaad22741..40da38ad7a 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/TeamController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/TeamController.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.controller; +import static org.springframework.http.HttpStatus.OK; + import ch.puzzle.okr.dto.TeamDto; import ch.puzzle.okr.dto.UserDto; import ch.puzzle.okr.mapper.TeamMapper; @@ -11,14 +13,11 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import java.util.List; - -import static org.springframework.http.HttpStatus.OK; - @RestController @RequestMapping("api/v2/teams") public class TeamController { @@ -31,8 +30,8 @@ public TeamController(TeamAuthorizationService teamAuthorizationService, TeamMap } @Operation(summary = "Get Teams", description = "Get all Teams from db") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned all Teams", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned all Teams", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDto.class))}),}) @GetMapping public List getAllTeams() { return teamAuthorizationService.getAllTeams().stream().map(teamMapper::toDto).toList(); @@ -41,12 +40,13 @@ public List getAllTeams() { @Operation(summary = "Create Team", description = "Create a new Team") @ApiResponses(value = { @ApiResponse(responseCode = "201", description = "Created new Team", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDto.class)) }), + @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDto.class))}), @ApiResponse(responseCode = "400", description = "Can't create new Team, not allowed to give an ID", content = @Content), - @ApiResponse(responseCode = "401", description = "Not authorized to create a Team", content = @Content) }) + @ApiResponse(responseCode = "401", description = "Not authorized to create a Team", content = @Content)}) @PostMapping - public ResponseEntity createTeam( - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Team as json to create a new Team.", required = true) @RequestBody TeamDto teamDto) { + public ResponseEntity createTeam(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The Team as json to create a new Team.", required = true) + @RequestBody + TeamDto teamDto) { Team createdTeam = teamAuthorizationService.createEntity(teamMapper.toTeam(teamDto)); return ResponseEntity.status(HttpStatus.CREATED).body(teamMapper.toDto(createdTeam)); } @@ -54,61 +54,69 @@ public ResponseEntity createTeam( @Operation(summary = "Update Team", description = "Update a Team by ID.") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Updated Team in db.", content = { - @Content(mediaType = "application/json", schema = @Schema(allOf = { TeamDto.class })) }), + @Content(mediaType = "application/json", schema = @Schema(allOf = {TeamDto.class}))}), @ApiResponse(responseCode = "401", description = "Not authorized to update a Team", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find a Team with a specified ID to update.", content = @Content), - @ApiResponse(responseCode = "422", description = "Can't update Team since Team was updated or deleted by another user.", content = @Content) }) + @ApiResponse(responseCode = "422", description = "Can't update Team since Team was updated or deleted by another user.", content = @Content)}) @PutMapping("/{id}") - public ResponseEntity updateTeam( - @Parameter(description = "The ID for updating a Team.", required = true) @PathVariable long id, - @RequestBody TeamDto teamDto) { + public ResponseEntity updateTeam(@Parameter(description = "The ID for updating a Team.", required = true) + @PathVariable + long id, @RequestBody + TeamDto teamDto) { Team updatedTeam = teamAuthorizationService.updateEntity(teamMapper.toTeam(teamDto), id); return ResponseEntity.status(OK).body(teamMapper.toDto(updatedTeam)); } @Operation(summary = "Delete Team by ID", description = "Delete Team by ID") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted Team by ID"), + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted Team by ID"), @ApiResponse(responseCode = "401", description = "Not authorized to delete an Team", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID") }) + @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID")}) @DeleteMapping("/{id}") - public void deleteTeamById( - @Parameter(description = "The ID of an Team to delete it.", required = true) @PathVariable long id) { + public void deleteTeamById(@Parameter(description = "The ID of an Team to delete it.", required = true) + @PathVariable + long id) { teamAuthorizationService.deleteEntity(id); } @Operation(summary = "Add users to a team", description = "Add users to a team") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Added users to team"), + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Added users to team"), @ApiResponse(responseCode = "401", description = "Not authorized to add users to the team", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID") }) + @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID")}) @PutMapping("/{id}/addusers") - public void addUsersToTeam( - @Parameter(description = "The ID of an Team to add to users to it.", required = true) @PathVariable long id, - @RequestBody List userDtoList) { + public void addUsersToTeam(@Parameter(description = "The ID of an Team to add to users to it.", required = true) + @PathVariable + long id, @RequestBody + List userDtoList) { var userIds = userDtoList.stream().map(UserDto::id).toList(); teamAuthorizationService.addUsersToTeam(id, userIds); } @Operation(summary = "Remove User from Team", description = "Remove User with given UserID from Team") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Removed User from Team"), + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Removed User from Team"), @ApiResponse(responseCode = "401", description = "Not authorized to remove user from team", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID") }) + @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID")}) @PutMapping("/{id}/user/{userId}/removeuser") - public void removeUserFromTeam( - @Parameter(description = "The ID of an team to remove the user from it.", required = true) @PathVariable long id, - @Parameter(description = "The User ID to remove from the team.", required = true) @PathVariable long userId) { + public void removeUserFromTeam(@Parameter(description = "The ID of an team to remove the user from it.", required = true) + @PathVariable + long id, @Parameter(description = "The User ID to remove from the team.", required = true) + @PathVariable + long userId) { teamAuthorizationService.removeUserFromTeam(id, userId); } @Operation(summary = "Update or add team membership", description = "If user is already member of this team, isAdmin is set. otherwise new team membership " - + "is added with isAdmin true or false") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Update or add team membership"), + + "is added with isAdmin true or false") + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Update or add team membership"), @ApiResponse(responseCode = "401", description = "Not authorized to update or add team membership", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID") }) + @ApiResponse(responseCode = "404", description = "Did not find the Team with requested ID")}) @PutMapping("/{id}/user/{userId}/updateaddteammembership/{isAdmin}") - public void updateOrAddTeamMembership( - @Parameter(description = "The ID of an team to update or add membership", required = true) @PathVariable long id, - @Parameter(description = "The User ID to update or add membership", required = true) @PathVariable long userId, - @Parameter(description = "The parameter if user should be admin or not", required = true) @PathVariable boolean isAdmin) { + public void updateOrAddTeamMembership(@Parameter(description = "The ID of an team to update or add membership", required = true) + @PathVariable + long id, @Parameter(description = "The User ID to update or add membership", required = true) + @PathVariable + long userId, @Parameter(description = "The parameter if user should be admin or not", required = true) + @PathVariable + boolean isAdmin) { teamAuthorizationService.updateOrAddTeamMembership(id, userId, isAdmin); } } diff --git a/backend/src/main/java/ch/puzzle/okr/controller/UserController.java b/backend/src/main/java/ch/puzzle/okr/controller/UserController.java index 961adb7c1c..089b536f73 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/UserController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/UserController.java @@ -12,9 +12,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; -import org.springframework.web.bind.annotation.*; - import java.util.List; +import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("api/v1/users") @@ -25,15 +24,15 @@ public class UserController { private final UserMapper userMapper; public UserController(UserAuthorizationService userAuthorizationService, AuthorizationService authorizationService, - UserMapper userMapper) { + UserMapper userMapper) { this.userAuthorizationService = userAuthorizationService; this.authorizationService = authorizationService; this.userMapper = userMapper; } @Operation(summary = "Get Users", description = "Get all Users from db.") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned all Users.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned all Users.", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class))}),}) @GetMapping public List getAllUsers() { return userAuthorizationService.getAllUsers().stream().map(userMapper::toDto).toList(); @@ -42,7 +41,7 @@ public List getAllUsers() { @Operation(summary = "Get Current User", description = "Get all current logged in user.") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned current logged in user.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }), }) + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class))}),}) @GetMapping(path = "/current") public UserDto getCurrentUser() { var currentUser = this.authorizationService.updateOrAddAuthorizationUser().user(); @@ -50,32 +49,36 @@ public UserDto getCurrentUser() { } @Operation(summary = "Get User by ID", description = "Get user by given ID.") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned user", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned user", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class))}),}) @GetMapping(path = "/{id}") - public UserDto getUserById( - @Parameter(description = "The ID for requested user.", required = true) @PathVariable long id) { + public UserDto getUserById(@Parameter(description = "The ID for requested user.", required = true) + @PathVariable + long id) { var user = this.userAuthorizationService.getById(id); return userMapper.toDto(user); } @Operation(summary = "Set OKR Champion property for user", description = "Sets the property okrChampion of user to true or false") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned user", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned user", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class))}),}) @PutMapping(path = "/{id}/isokrchampion/{isOkrChampion}") - public UserDto setOkrChampion( - @Parameter(description = "The ID for requested user.", required = true) @PathVariable long id, - @Parameter(description = "okrChampion property of user is set to this flag.", required = true) @PathVariable boolean isOkrChampion) { + public UserDto setOkrChampion(@Parameter(description = "The ID for requested user.", required = true) + @PathVariable + long id, @Parameter(description = "okrChampion property of user is set to this flag.", required = true) + @PathVariable + boolean isOkrChampion) { var user = this.userAuthorizationService.setIsOkrChampion(id, isOkrChampion); return userMapper.toDto(user); } @Operation(summary = "Create users", description = "Creates a user entity for every user in the method body") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned users", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned users", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserDto.class))}),}) @PostMapping(path = "/createall") - public List createUsers( - @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The users to create", required = true) @RequestBody List newUserDtoList) { + public List createUsers(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "The users to create", required = true) + @RequestBody + List newUserDtoList) { var createdUsers = this.userAuthorizationService.createUsers(userMapper.toUserList(newUserDtoList)); return userMapper.toDtos(createdUsers); } @@ -83,29 +86,32 @@ public List createUsers( @Operation(summary = "Check if User is member of Teams", description = "Check if User is member of any Team.") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "true if user is member of a Team", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = Boolean.class)) }), }) + @Content(mediaType = "application/json", schema = @Schema(implementation = Boolean.class))}),}) @GetMapping(path = "/{id}/ismemberofteams") - public Boolean isUserMemberOfTeams( - @Parameter(description = "The ID of the user.", required = true) @PathVariable long id) { + public Boolean isUserMemberOfTeams(@Parameter(description = "The ID of the user.", required = true) + @PathVariable + long id) { return this.userAuthorizationService.isUserMemberOfTeams(id); } @Operation(summary = "Get User OKR Data", description = "Get User OKR Data") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Returned User OKR Data.", content = { - @Content(mediaType = "application/json", schema = @Schema(implementation = UserOkrDataDto.class)) }), }) + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Returned User OKR Data.", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = UserOkrDataDto.class))}),}) @GetMapping(path = "/{id}/userokrdata") - public UserOkrDataDto getUserOkrData(@PathVariable long id) { + public UserOkrDataDto getUserOkrData(@PathVariable + long id) { return this.userAuthorizationService.getUserOkrData(id); } @Operation(summary = "Delete User by Id", description = "Delete User by Id") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Deleted User by Id"), + @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Deleted User by Id"), @ApiResponse(responseCode = "401", description = "Not authorized to delete a User", content = @Content), - @ApiResponse(responseCode = "404", description = "Did not find the User with requested id") }) + @ApiResponse(responseCode = "404", description = "Did not find the User with requested id")}) @DeleteMapping(path = "/{id}") - public void deleteUserById(@PathVariable long id) { + public void deleteUserById(@PathVariable + long id) { this.userAuthorizationService.deleteEntityById(id); } diff --git a/backend/src/main/java/ch/puzzle/okr/deserializer/CheckInDeserializer.java b/backend/src/main/java/ch/puzzle/okr/deserializer/CheckInDeserializer.java index f7442819cb..95694ed33c 100644 --- a/backend/src/main/java/ch/puzzle/okr/deserializer/CheckInDeserializer.java +++ b/backend/src/main/java/ch/puzzle/okr/deserializer/CheckInDeserializer.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.deserializer; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; + import ch.puzzle.okr.dto.checkin.CheckInDto; import ch.puzzle.okr.dto.checkin.CheckInMetricDto; import ch.puzzle.okr.dto.checkin.CheckInOrdinalDto; @@ -11,15 +14,11 @@ import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ResponseStatusException; -import java.io.IOException; - -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; - @Component public class CheckInDeserializer extends JsonDeserializer { @@ -45,7 +44,7 @@ public CheckInDto deserialize(JsonParser jsonParser, DeserializationContext dese } } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, - "missing keyResult ID to deserialize checkIn DTO"); + "missing keyResult ID to deserialize checkIn DTO"); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/deserializer/KeyResultDeserializer.java b/backend/src/main/java/ch/puzzle/okr/deserializer/KeyResultDeserializer.java index d873168391..61200ab9ee 100644 --- a/backend/src/main/java/ch/puzzle/okr/deserializer/KeyResultDeserializer.java +++ b/backend/src/main/java/ch/puzzle/okr/deserializer/KeyResultDeserializer.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.deserializer; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultMetricDto; import ch.puzzle.okr.dto.keyresult.KeyResultOrdinalDto; @@ -9,14 +12,10 @@ import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.io.IOException; - -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; - public class KeyResultDeserializer extends JsonDeserializer { @Override public KeyResultDto deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) @@ -27,7 +26,7 @@ public KeyResultDto deserialize(JsonParser jsonParser, DeserializationContext de if (root.has(keyResultAttribute) && root.get(keyResultAttribute).asText().equals(KEY_RESULT_TYPE_METRIC)) { return mapper.readValue(root.toString(), KeyResultMetricDto.class); } else if (root.has(keyResultAttribute) - && root.get(keyResultAttribute).asText().equals(KEY_RESULT_TYPE_ORDINAL)) { + && root.get(keyResultAttribute).asText().equals(KEY_RESULT_TYPE_ORDINAL)) { return mapper.readValue(root.toString(), KeyResultOrdinalDto.class); } throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "unsupported keyResult DTO to deserialize"); diff --git a/backend/src/main/java/ch/puzzle/okr/dto/ErrorDto.java b/backend/src/main/java/ch/puzzle/okr/dto/ErrorDto.java index 07ad03f1ae..4bd033c425 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/ErrorDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/ErrorDto.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.dto; import ch.puzzle.okr.ErrorKey; - import java.util.List; public record ErrorDto(String errorKey, List params) { diff --git a/backend/src/main/java/ch/puzzle/okr/dto/ObjectiveDto.java b/backend/src/main/java/ch/puzzle/okr/dto/ObjectiveDto.java index bf230fdcc8..9de9d8fafa 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/ObjectiveDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/ObjectiveDto.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.dto; import ch.puzzle.okr.models.State; - import java.time.LocalDateTime; public record ObjectiveDto(Long id, int version, String title, Long teamId, Long quarterId, String quarterLabel, diff --git a/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInMetricDto.java b/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInMetricDto.java index 03036b4cdd..190627334e 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInMetricDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInMetricDto.java @@ -1,11 +1,10 @@ package ch.puzzle.okr.dto.checkin; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - import java.time.LocalDateTime; @JsonDeserialize(as = CheckInMetricDto.class) public record CheckInMetricDto(Long id, int version, String changeInfo, String initiatives, Integer confidence, - Long keyResultId, LocalDateTime createdOn, LocalDateTime modifiedOn, Double value, boolean writeable) - implements CheckInDto { + Long keyResultId, LocalDateTime createdOn, LocalDateTime modifiedOn, Double value, + boolean writeable) implements CheckInDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInOrdinalDto.java b/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInOrdinalDto.java index 118fe55179..7379631eec 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInOrdinalDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/checkin/CheckInOrdinalDto.java @@ -2,11 +2,10 @@ import ch.puzzle.okr.models.checkin.Zone; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - import java.time.LocalDateTime; @JsonDeserialize(as = CheckInOrdinalDto.class) public record CheckInOrdinalDto(Long id, int version, String changeInfo, String initiatives, Integer confidence, - Long keyResultId, LocalDateTime createdOn, LocalDateTime modifiedOn, Zone value, boolean writeable) - implements CheckInDto { + Long keyResultId, LocalDateTime createdOn, LocalDateTime modifiedOn, Zone value, + boolean writeable) implements CheckInDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultDto.java b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultDto.java index b461737716..95cfbc164e 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultDto.java @@ -3,7 +3,6 @@ import ch.puzzle.okr.deserializer.KeyResultDeserializer; import ch.puzzle.okr.dto.ActionDto; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - import java.util.List; @JsonDeserialize(using = KeyResultDeserializer.class) diff --git a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInOrdinalDto.java b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInOrdinalDto.java index ad67cf798a..5e6122e0eb 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInOrdinalDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultLastCheckInOrdinalDto.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.dto.keyresult; import ch.puzzle.okr.models.checkin.Zone; - import java.time.LocalDateTime; public record KeyResultLastCheckInOrdinalDto(Long id, int version, Zone value, Integer confidence, diff --git a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultMetricDto.java b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultMetricDto.java index b69b360f1d..69c0d18153 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultMetricDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultMetricDto.java @@ -3,7 +3,6 @@ import ch.puzzle.okr.dto.ActionDto; import ch.puzzle.okr.models.Unit; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - import java.time.LocalDateTime; import java.util.List; diff --git a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultOrdinalDto.java b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultOrdinalDto.java index 4f0365b947..44d622ea35 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultOrdinalDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/keyresult/KeyResultOrdinalDto.java @@ -2,7 +2,6 @@ import ch.puzzle.okr.dto.ActionDto; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - import java.time.LocalDateTime; import java.util.List; diff --git a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultOrdinalDto.java b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultOrdinalDto.java index 6097da2724..553fd0cbed 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultOrdinalDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewKeyResultOrdinalDto.java @@ -1,6 +1,6 @@ package ch.puzzle.okr.dto.overview; public record OverviewKeyResultOrdinalDto(Long id, String title, String keyResultType, String commitZone, - String targetZone, String stretchZone, OverviewLastCheckInOrdinalDto lastCheckIn) - implements OverviewKeyResultDto { + String targetZone, String stretchZone, + OverviewLastCheckInOrdinalDto lastCheckIn) implements OverviewKeyResultDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInMetricDto.java b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInMetricDto.java index 94e15589d8..2338903704 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInMetricDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInMetricDto.java @@ -2,6 +2,6 @@ import java.time.LocalDateTime; -public record OverviewLastCheckInMetricDto(Long id, Double value, Integer confidence, LocalDateTime createdOn) - implements OverviewLastCheckInDto { +public record OverviewLastCheckInMetricDto(Long id, Double value, Integer confidence, + LocalDateTime createdOn) implements OverviewLastCheckInDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInOrdinalDto.java b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInOrdinalDto.java index 9ea12ae0ac..28d0219055 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInOrdinalDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewLastCheckInOrdinalDto.java @@ -2,6 +2,6 @@ import java.time.LocalDateTime; -public record OverviewLastCheckInOrdinalDto(Long id, String value, Integer confidence, LocalDateTime createdOn) - implements OverviewLastCheckInDto { +public record OverviewLastCheckInOrdinalDto(Long id, String value, Integer confidence, + LocalDateTime createdOn) implements OverviewLastCheckInDto { } diff --git a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewObjectiveDto.java b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewObjectiveDto.java index 403a7073b6..e0f6ccc078 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewObjectiveDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/overview/OverviewObjectiveDto.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.dto.overview; import ch.puzzle.okr.models.State; - import java.util.List; public record OverviewObjectiveDto(Long id, String title, State state, OverviewQuarterDto quarter, diff --git a/backend/src/main/java/ch/puzzle/okr/exception/OkrResponseStatusException.java b/backend/src/main/java/ch/puzzle/okr/exception/OkrResponseStatusException.java index 11f666040e..712b292ecd 100644 --- a/backend/src/main/java/ch/puzzle/okr/exception/OkrResponseStatusException.java +++ b/backend/src/main/java/ch/puzzle/okr/exception/OkrResponseStatusException.java @@ -1,14 +1,13 @@ package ch.puzzle.okr.exception; +import static org.springframework.http.HttpStatus.UNAUTHORIZED; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.dto.ErrorDto; +import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static org.springframework.http.HttpStatus.UNAUTHORIZED; - public class OkrResponseStatusException extends ResponseStatusException { private final List errors; diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/ActionMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/ActionMapper.java index 67d6d97e40..e3389e1a3f 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/ActionMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/ActionMapper.java @@ -4,9 +4,8 @@ import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.service.business.KeyResultBusinessService; -import org.springframework.stereotype.Component; - import java.util.List; +import org.springframework.stereotype.Component; @Component public class ActionMapper { @@ -18,8 +17,13 @@ public ActionMapper(KeyResultBusinessService keyResultBusinessService) { } public ActionDto toDto(Action action) { - return new ActionDto(action.getId(), action.getVersion(), action.getAction(), action.getPriority(), - action.isChecked(), action.getKeyResult().getId(), action.isWriteable()); + return new ActionDto(action.getId(), + action.getVersion(), + action.getAction(), + action.getPriority(), + action.isChecked(), + action.getKeyResult().getId(), + action.isWriteable()); } public List toActions(List actionDtos, KeyResult keyResult) { @@ -28,13 +32,19 @@ public List toActions(List actionDtos, KeyResult keyResult) { public List toActions(List actionDtos) { return actionDtos.stream() - .map(actionDto -> toAction(actionDto, keyResultBusinessService.getEntityById(actionDto.keyResultId()))) - .toList(); + .map(actionDto -> toAction(actionDto, + keyResultBusinessService.getEntityById(actionDto.keyResultId()))) + .toList(); } private Action toAction(ActionDto actionDto, KeyResult keyResult) { - return Action.Builder.builder().withId(actionDto.id()).withVersion(actionDto.version()) - .withAction(actionDto.action()).withPriority(actionDto.priority()).withIsChecked(actionDto.isChecked()) - .withKeyResult(keyResult).build(); + return Action.Builder.builder() + .withId(actionDto.id()) + .withVersion(actionDto.version()) + .withAction(actionDto.action()) + .withPriority(actionDto.priority()) + .withIsChecked(actionDto.isChecked()) + .withKeyResult(keyResult) + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/AlignmentSelectionMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/AlignmentSelectionMapper.java index 547181b95e..02516aec82 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/AlignmentSelectionMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/AlignmentSelectionMapper.java @@ -3,12 +3,11 @@ import ch.puzzle.okr.dto.alignment.AlignmentKeyResultDto; import ch.puzzle.okr.dto.alignment.AlignmentObjectiveDto; import ch.puzzle.okr.models.alignment.AlignmentSelection; -import org.springframework.stereotype.Component; - import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; +import org.springframework.stereotype.Component; @Component public class AlignmentSelectionMapper { @@ -20,13 +19,14 @@ public List toDto(List alignments) { } private Optional getMatchingObjectiveDto(Long objectiveId, - List objectives) { + List objectives) { return objectives.stream().filter(objectiveDto -> Objects.equals(objectiveId, objectiveDto.id())).findFirst(); } private void processObjectives(List objectiveDtos, AlignmentSelection alignment) { - Optional objectiveDto = getMatchingObjectiveDto( - alignment.getAlignmentSelectionId().getObjectiveId(), objectiveDtos); + Optional objectiveDto = getMatchingObjectiveDto(alignment.getAlignmentSelectionId() + .getObjectiveId(), + objectiveDtos); if (objectiveDto.isPresent()) { processKeyResults(objectiveDto.get(), alignment); } else { @@ -44,12 +44,13 @@ private void processKeyResults(AlignmentObjectiveDto objectiveDto, AlignmentSele private AlignmentObjectiveDto createObjectiveDto(AlignmentSelection alignment) { return new AlignmentObjectiveDto(alignment.getAlignmentSelectionId().getObjectiveId(), - alignment.getObjectiveTitle(), new ArrayList<>()); + alignment.getObjectiveTitle(), + new ArrayList<>()); } private AlignmentKeyResultDto createKeyResultDto(AlignmentSelection alignment) { return new AlignmentKeyResultDto(alignment.getAlignmentSelectionId().getKeyResultId(), - alignment.getKeyResultTitle()); + alignment.getKeyResultTitle()); } private boolean isValidId(Long id) { diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/CompletedMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/CompletedMapper.java index fec0b71b93..018a7358c3 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/CompletedMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/CompletedMapper.java @@ -15,16 +15,16 @@ public CompletedMapper(ObjectiveMapper objectiveMapper) { public CompletedDto toDto(Completed completed) { return new CompletedDto( // - completed.getId(), // - objectiveMapper.toDto(completed.getObjective()), // - completed.getComment()); + completed.getId(), // + objectiveMapper.toDto(completed.getObjective()), // + completed.getComment()); } public Completed toCompleted(CompletedDto completedDto) { return Completed.Builder.builder() // - .withId(completedDto.id()) // - .withObjective(objectiveMapper.toObjective(completedDto.objective())) // - .withComment(completedDto.comment()) // - .build(); + .withId(completedDto.id()) // + .withObjective(objectiveMapper.toObjective(completedDto.objective())) // + .withComment(completedDto.comment()) // + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/ObjectiveMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/ObjectiveMapper.java index a65574c408..611c7690b0 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/ObjectiveMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/ObjectiveMapper.java @@ -4,9 +4,8 @@ import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.service.business.QuarterBusinessService; import ch.puzzle.okr.service.business.TeamBusinessService; -import org.springframework.stereotype.Component; - import java.time.LocalDateTime; +import org.springframework.stereotype.Component; @Component public class ObjectiveMapper { @@ -20,17 +19,30 @@ public ObjectiveMapper(TeamBusinessService teamBusinessService, QuarterBusinessS } public ObjectiveDto toDto(Objective objective) { - return new ObjectiveDto(objective.getId(), objective.getVersion(), objective.getTitle(), - objective.getTeam().getId(), objective.getQuarter().getId(), objective.getQuarter().getLabel(), - objective.getDescription(), objective.getState(), objective.getCreatedOn(), objective.getModifiedOn(), - objective.isWriteable()); + return new ObjectiveDto(objective.getId(), + objective.getVersion(), + objective.getTitle(), + objective.getTeam().getId(), + objective.getQuarter().getId(), + objective.getQuarter().getLabel(), + objective.getDescription(), + objective.getState(), + objective.getCreatedOn(), + objective.getModifiedOn(), + objective.isWriteable()); } public Objective toObjective(ObjectiveDto objectiveDto) { - return Objective.Builder.builder().withId(objectiveDto.id()).withVersion(objectiveDto.version()) - .withTitle(objectiveDto.title()).withTeam(teamBusinessService.getTeamById(objectiveDto.teamId())) - .withDescription(objectiveDto.description()).withModifiedOn(LocalDateTime.now()) - .withState(objectiveDto.state()).withCreatedOn(objectiveDto.createdOn()) - .withQuarter(quarterBusinessService.getQuarterById(objectiveDto.quarterId())).build(); + return Objective.Builder.builder() + .withId(objectiveDto.id()) + .withVersion(objectiveDto.version()) + .withTitle(objectiveDto.title()) + .withTeam(teamBusinessService.getTeamById(objectiveDto.teamId())) + .withDescription(objectiveDto.description()) + .withModifiedOn(LocalDateTime.now()) + .withState(objectiveDto.state()) + .withCreatedOn(objectiveDto.createdOn()) + .withQuarter(quarterBusinessService.getQuarterById(objectiveDto.quarterId())) + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/OverviewMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/OverviewMapper.java index 2051b17b89..2a3269d219 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/OverviewMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/OverviewMapper.java @@ -1,19 +1,18 @@ package ch.puzzle.okr.mapper; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.dto.overview.*; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.overview.Overview; -import org.springframework.stereotype.Component; - import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; - -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; -import static org.springframework.http.HttpStatus.BAD_REQUEST; +import org.springframework.stereotype.Component; @Component public class OverviewMapper { @@ -31,7 +30,7 @@ private Optional getMatchingOverviewDto(Long teamId, List getMatchingObjectiveDto(Long objectiveId, - List objectives) { + List objectives) { return objectives.stream().filter(objectiveDto -> Objects.equals(objectiveId, objectiveDto.id())).findFirst(); } @@ -45,8 +44,9 @@ private void processTeams(List overviewDtos, Overview overview) { } private void processObjectives(OverviewDto overviewDto, Overview overview) { - Optional overviewObjectiveDto = getMatchingObjectiveDto( - overview.getOverviewId().getObjectiveId(), overviewDto.objectives()); + Optional overviewObjectiveDto = getMatchingObjectiveDto(overview.getOverviewId() + .getObjectiveId(), + overviewDto.objectives()); if (overviewObjectiveDto.isPresent()) { processKeyResults(overviewObjectiveDto.get(), overview); } else { @@ -64,7 +64,8 @@ private OverviewDto createOverviewDto(Overview overview) { objectives.add(createObjectiveDto(overview)); } return new OverviewDto(new OverviewTeamDto(overview.getOverviewId().getTeamId(), overview.getTeamName()), - objectives, overview.isWriteable()); + objectives, + overview.isWriteable()); } private OverviewObjectiveDto createObjectiveDto(Overview overview) { @@ -72,9 +73,11 @@ private OverviewObjectiveDto createObjectiveDto(Overview overview) { if (isValidId(overview.getOverviewId().getKeyResultId())) { keyResults.add(createKeyResultDto(overview)); } - return new OverviewObjectiveDto(overview.getOverviewId().getObjectiveId(), overview.getObjectiveTitle(), - overview.getObjectiveState(), - new OverviewQuarterDto(overview.getQuarterId(), overview.getQuarterLabel()), keyResults); + return new OverviewObjectiveDto(overview.getOverviewId().getObjectiveId(), + overview.getObjectiveTitle(), + overview.getObjectiveState(), + new OverviewQuarterDto(overview.getQuarterId(), overview.getQuarterLabel()), + keyResults); } private OverviewKeyResultDto createKeyResultDto(Overview overview) { @@ -83,8 +86,9 @@ private OverviewKeyResultDto createKeyResultDto(Overview overview) { } else if (Objects.equals(overview.getKeyResultType(), KEY_RESULT_TYPE_ORDINAL)) { return createKeyResultOrdinalDto(overview); } else { - throw new OkrResponseStatusException(BAD_REQUEST, ErrorKey.KEY_RESULT_CONVERSION, - overview.getKeyResultType()); + throw new OkrResponseStatusException(BAD_REQUEST, + ErrorKey.KEY_RESULT_CONVERSION, + overview.getKeyResultType()); } } @@ -92,22 +96,34 @@ private OverviewKeyResultMetricDto createKeyResultMetricDto(Overview overview) { OverviewLastCheckInMetricDto lastCheckIn = null; if (isValidId(overview.getOverviewId().getCheckInId())) { lastCheckIn = new OverviewLastCheckInMetricDto(overview.getOverviewId().getCheckInId(), - overview.getCheckInValue(), overview.getConfidence(), overview.getCheckInCreatedOn()); + overview.getCheckInValue(), + overview.getConfidence(), + overview.getCheckInCreatedOn()); } - return new OverviewKeyResultMetricDto(overview.getOverviewId().getKeyResultId(), overview.getKeyResultTitle(), - overview.getKeyResultType(), overview.getUnit(), overview.getBaseline(), overview.getStretchGoal(), - lastCheckIn); + return new OverviewKeyResultMetricDto(overview.getOverviewId().getKeyResultId(), + overview.getKeyResultTitle(), + overview.getKeyResultType(), + overview.getUnit(), + overview.getBaseline(), + overview.getStretchGoal(), + lastCheckIn); } private OverviewKeyResultOrdinalDto createKeyResultOrdinalDto(Overview overview) { OverviewLastCheckInOrdinalDto lastCheckIn = null; if (isValidId(overview.getOverviewId().getCheckInId())) { lastCheckIn = new OverviewLastCheckInOrdinalDto(overview.getOverviewId().getCheckInId(), - overview.getCheckInZone(), overview.getConfidence(), overview.getCheckInCreatedOn()); + overview.getCheckInZone(), + overview.getConfidence(), + overview.getCheckInCreatedOn()); } - return new OverviewKeyResultOrdinalDto(overview.getOverviewId().getKeyResultId(), overview.getKeyResultTitle(), - overview.getKeyResultType(), overview.getCommitZone(), overview.getTargetZone(), - overview.getStretchZone(), lastCheckIn); + return new OverviewKeyResultOrdinalDto(overview.getOverviewId().getKeyResultId(), + overview.getKeyResultTitle(), + overview.getKeyResultType(), + overview.getCommitZone(), + overview.getTargetZone(), + overview.getStretchZone(), + lastCheckIn); } private boolean isValidId(Long id) { diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/TeamMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/TeamMapper.java index 792bc027e6..9638aeb465 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/TeamMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/TeamMapper.java @@ -15,7 +15,10 @@ public TeamDto toDto(Team team) { } public Team toTeam(TeamDto teamDto) { - return Team.Builder.builder().withId(teamDto.id()).withVersion(teamDto.version()).withName(teamDto.name()) - .build(); + return Team.Builder.builder() + .withId(teamDto.id()) + .withVersion(teamDto.version()) + .withName(teamDto.name()) + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/UserMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/UserMapper.java index 8d2f3c1892..07642b94eb 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/UserMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/UserMapper.java @@ -4,10 +4,9 @@ import ch.puzzle.okr.dto.UserDto; import ch.puzzle.okr.dto.UserTeamDto; import ch.puzzle.okr.models.User; -import org.springframework.stereotype.Component; - import java.util.List; import java.util.stream.Collectors; +import org.springframework.stereotype.Component; @Component public class UserMapper { @@ -23,12 +22,21 @@ public List toDtos(List userList) { } public UserDto toDto(User user) { - var userTeams = user.getUserTeamList().stream().map( - ut -> new UserTeamDto(ut.getId(), user.getVersion(), teamMapper.toDto(ut.getTeam()), ut.isTeamAdmin())) - .collect(Collectors.toList()); - - return new UserDto(user.getId(), user.getVersion(), user.getFirstname(), user.getLastname(), user.getEmail(), - userTeams, user.isOkrChampion()); + var userTeams = user.getUserTeamList() + .stream() + .map(ut -> new UserTeamDto(ut.getId(), + user.getVersion(), + teamMapper.toDto(ut.getTeam()), + ut.isTeamAdmin())) + .collect(Collectors.toList()); + + return new UserDto(user.getId(), + user.getVersion(), + user.getFirstname(), + user.getLastname(), + user.getEmail(), + userTeams, + user.isOkrChampion()); } public List toUserList(List newUserList) { diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/UserOkrDataMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/UserOkrDataMapper.java index 88fc383bf2..a0e16d8820 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/UserOkrDataMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/UserOkrDataMapper.java @@ -3,9 +3,8 @@ import ch.puzzle.okr.dto.userOkrData.UserKeyResultDataDto; import ch.puzzle.okr.dto.userOkrData.UserOkrDataDto; import ch.puzzle.okr.models.keyresult.KeyResult; -import org.springframework.stereotype.Component; - import java.util.List; +import org.springframework.stereotype.Component; @Component public class UserOkrDataMapper { @@ -16,10 +15,12 @@ public UserOkrDataDto toDto(List keyResults) { private List toUserKeyResultDataDtos(List keyResults) { return keyResults.stream() // - .map(keyResult -> new UserKeyResultDataDto( // - keyResult.getId(), keyResult.getTitle(), // - keyResult.getObjective().getId(), keyResult.getObjective().getTitle() // - )) // - .toList(); + .map(keyResult -> new UserKeyResultDataDto( // + keyResult.getId(), + keyResult.getTitle(), // + keyResult.getObjective().getId(), + keyResult.getObjective().getTitle() // + )) // + .toList(); } } \ No newline at end of file diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMapper.java index 34ab137035..0d839e407b 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMapper.java @@ -27,7 +27,8 @@ public CheckInDto toDto(CheckIn checkIn) { return checkInOrdinalMapper.toDto(checkInOrdinal); } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, - String.format("The CheckIn %s can't be converted to a metric or ordinal CheckIn", checkIn)); + String.format("The CheckIn %s can't be converted to a metric or ordinal CheckIn", + checkIn)); } } @@ -38,7 +39,8 @@ public CheckIn toCheckIn(CheckInDto checkInDto) { return checkInOrdinalMapper.toCheckInOrdinal((CheckInOrdinalDto) checkInDto); } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, - String.format("The provided CheckInDto %s is neither metric nor ordinal", checkInDto)); + String.format("The provided CheckInDto %s is neither metric nor ordinal", + checkInDto)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapper.java index 814adc85f2..8c0e2e023c 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapper.java @@ -16,28 +16,28 @@ public CheckInMetricMapper(KeyResultBusinessService keyResultBusinessService) { public CheckInMetricDto toDto(CheckInMetric checkInMetric) { return new CheckInMetricDto(checkInMetric.getId(), // - checkInMetric.getVersion(), // - checkInMetric.getChangeInfo(), // - checkInMetric.getInitiatives(), // - checkInMetric.getConfidence(), // - checkInMetric.getKeyResult().getId(), // - checkInMetric.getCreatedOn(), // - checkInMetric.getModifiedOn(), // - checkInMetric.getValue(), // - checkInMetric.isWriteable()); + checkInMetric.getVersion(), // + checkInMetric.getChangeInfo(), // + checkInMetric.getInitiatives(), // + checkInMetric.getConfidence(), // + checkInMetric.getKeyResult().getId(), // + checkInMetric.getCreatedOn(), // + checkInMetric.getModifiedOn(), // + checkInMetric.getValue(), // + checkInMetric.isWriteable()); } public CheckIn toCheckInMetric(CheckInMetricDto checkInMetricDto) { return CheckInMetric.Builder.builder() // - .withValue(checkInMetricDto.value()) // - .withId(checkInMetricDto.id()) // - .withVersion(checkInMetricDto.version()) // - .withChangeInfo(checkInMetricDto.changeInfo()) // - .withInitiatives(checkInMetricDto.initiatives()) // - .withConfidence(checkInMetricDto.confidence()) // - .withCreatedOn(checkInMetricDto.createdOn()) // - .withModifiedOn(checkInMetricDto.modifiedOn()) // - .withKeyResult(keyResultBusinessService.getEntityById(checkInMetricDto.keyResultId())) // - .build(); + .withValue(checkInMetricDto.value()) // + .withId(checkInMetricDto.id()) // + .withVersion(checkInMetricDto.version()) // + .withChangeInfo(checkInMetricDto.changeInfo()) // + .withInitiatives(checkInMetricDto.initiatives()) // + .withConfidence(checkInMetricDto.confidence()) // + .withCreatedOn(checkInMetricDto.createdOn()) // + .withModifiedOn(checkInMetricDto.modifiedOn()) // + .withKeyResult(keyResultBusinessService.getEntityById(checkInMetricDto.keyResultId())) // + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapper.java index f64b9c81c4..5b9676a074 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapper.java @@ -15,28 +15,29 @@ public CheckInOrdinalMapper(KeyResultBusinessService keyResultBusinessService) { } public CheckInOrdinalDto toDto(CheckInOrdinal checkInOrdinal) { - return new CheckInOrdinalDto(checkInOrdinal.getId(), checkInOrdinal.getVersion(), // - checkInOrdinal.getChangeInfo(), // - checkInOrdinal.getInitiatives(), // - checkInOrdinal.getConfidence(), // - checkInOrdinal.getKeyResult().getId(), // - checkInOrdinal.getCreatedOn(), // - checkInOrdinal.getModifiedOn(), // - checkInOrdinal.getZone(), // - checkInOrdinal.isWriteable()); + return new CheckInOrdinalDto(checkInOrdinal.getId(), + checkInOrdinal.getVersion(), // + checkInOrdinal.getChangeInfo(), // + checkInOrdinal.getInitiatives(), // + checkInOrdinal.getConfidence(), // + checkInOrdinal.getKeyResult().getId(), // + checkInOrdinal.getCreatedOn(), // + checkInOrdinal.getModifiedOn(), // + checkInOrdinal.getZone(), // + checkInOrdinal.isWriteable()); } public CheckIn toCheckInOrdinal(CheckInOrdinalDto checkInOrdinalDto) { return CheckInOrdinal.Builder.builder() // - .withZone(checkInOrdinalDto.value()) // - .withId(checkInOrdinalDto.id()) // - .withVersion(checkInOrdinalDto.version()) // - .withChangeInfo(checkInOrdinalDto.changeInfo()) // - .withInitiatives(checkInOrdinalDto.initiatives()) // - .withConfidence(checkInOrdinalDto.confidence()) // - .withCreatedOn(checkInOrdinalDto.createdOn()) // - .withModifiedOn(checkInOrdinalDto.modifiedOn()) // - .withKeyResult(keyResultBusinessService.getEntityById(checkInOrdinalDto.keyResultId())) // - .build(); + .withZone(checkInOrdinalDto.value()) // + .withId(checkInOrdinalDto.id()) // + .withVersion(checkInOrdinalDto.version()) // + .withChangeInfo(checkInOrdinalDto.changeInfo()) // + .withInitiatives(checkInOrdinalDto.initiatives()) // + .withConfidence(checkInOrdinalDto.confidence()) // + .withCreatedOn(checkInOrdinalDto.createdOn()) // + .withModifiedOn(checkInOrdinalDto.modifiedOn()) // + .withKeyResult(keyResultBusinessService.getEntityById(checkInOrdinalDto.keyResultId())) // + .build(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapper.java index 9078dbd04d..286671f14f 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapper.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper.keyresult; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultMetricDto; import ch.puzzle.okr.dto.keyresult.KeyResultOrdinalDto; @@ -7,13 +9,10 @@ import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; +import java.util.List; import org.springframework.stereotype.Component; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static org.springframework.http.HttpStatus.BAD_REQUEST; - @Component public class KeyResultMapper { @@ -32,7 +31,8 @@ public KeyResultDto toDto(KeyResult keyResult, List actionList) { return keyResultOrdinalMapper.toDto(keyResultOrdinal, actionList); } else { throw new ResponseStatusException(BAD_REQUEST, - String.format("The KeyResult %s can't be converted to a metric or ordinal KeyResult", keyResult)); + String.format("The KeyResult %s can't be converted to a metric or ordinal KeyResult", + keyResult)); } } @@ -43,7 +43,8 @@ public KeyResult toKeyResult(KeyResultDto keyResultDto) { return keyResultOrdinalMapper.toKeyResultOrdinal((KeyResultOrdinalDto) keyResultDto); } else { throw new ResponseStatusException(BAD_REQUEST, - String.format("The provided KeyResultDto %s is neither metric nor ordinal", keyResultDto)); + String.format("The provided KeyResultDto %s is neither metric nor ordinal", + keyResultDto)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapper.java index e285304f06..49714b3e0c 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapper.java @@ -10,9 +10,8 @@ import ch.puzzle.okr.service.business.CheckInBusinessService; import ch.puzzle.okr.service.business.ObjectiveBusinessService; import ch.puzzle.okr.service.business.UserBusinessService; -import org.springframework.stereotype.Component; - import java.util.List; +import org.springframework.stereotype.Component; @Component public class KeyResultMetricMapper { @@ -23,8 +22,8 @@ public class KeyResultMetricMapper { private final ActionMapper actionMapper; public KeyResultMetricMapper(UserBusinessService userBusinessService, - ObjectiveBusinessService objectiveBusinessService, CheckInBusinessService checkInBusinessService, - ActionMapper actionMapper) { + ObjectiveBusinessService objectiveBusinessService, + CheckInBusinessService checkInBusinessService, ActionMapper actionMapper) { this.userBusinessService = userBusinessService; this.objectiveBusinessService = objectiveBusinessService; this.checkInBusinessService = checkInBusinessService; @@ -33,54 +32,56 @@ public KeyResultMetricMapper(UserBusinessService userBusinessService, public KeyResultDto toDto(KeyResultMetric keyResult, List actionList) { KeyResultUserDto ownerDto = new KeyResultUserDto( // - keyResult.getOwner().getId(), // - keyResult.getOwner().getFirstname(), // - keyResult.getOwner().getLastname()); + keyResult.getOwner().getId(), // + keyResult.getOwner().getFirstname(), // + keyResult.getOwner().getLastname()); KeyResultQuarterDto quarterDto = new KeyResultQuarterDto( // - keyResult.getObjective().getQuarter().getId(), // - keyResult.getObjective().getQuarter().getLabel(), // - keyResult.getObjective().getQuarter().getStartDate(), // - keyResult.getObjective().getQuarter().getEndDate()); + keyResult.getObjective().getQuarter().getId(), // + keyResult.getObjective().getQuarter().getLabel(), // + keyResult.getObjective().getQuarter().getStartDate(), // + keyResult.getObjective().getQuarter().getEndDate()); KeyResultObjectiveDto objectiveDto = new KeyResultObjectiveDto( // - keyResult.getObjective().getId(), // - keyResult.getObjective().getState().toString(), // - quarterDto); + keyResult.getObjective().getId(), // + keyResult.getObjective().getState().toString(), // + quarterDto); KeyResultLastCheckInMetricDto lastCheckInDto = getLastCheckInDto(keyResult.getId()); return new KeyResultMetricDto( // - keyResult.getId(), // - keyResult.getVersion(), // - keyResult.getKeyResultType(), // - keyResult.getTitle(), // - keyResult.getDescription(), // - keyResult.getBaseline(), // - keyResult.getStretchGoal(), // - keyResult.getUnit(), // - ownerDto, objectiveDto, // - lastCheckInDto, // - keyResult.getCreatedOn(), // - keyResult.getModifiedOn(), // - keyResult.isWriteable(), // - actionList.stream().map(actionMapper::toDto).toList()); + keyResult.getId(), // + keyResult.getVersion(), // + keyResult.getKeyResultType(), // + keyResult.getTitle(), // + keyResult.getDescription(), // + keyResult.getBaseline(), // + keyResult.getStretchGoal(), // + keyResult.getUnit(), // + ownerDto, + objectiveDto, // + lastCheckInDto, // + keyResult.getCreatedOn(), // + keyResult.getModifiedOn(), // + keyResult.isWriteable(), // + actionList.stream().map(actionMapper::toDto).toList()); } public KeyResult toKeyResultMetric(KeyResultMetricDto keyResultMetricDto) { return KeyResultMetric.Builder.builder() // - .withBaseline(keyResultMetricDto.baseline()) // - .withStretchGoal(keyResultMetricDto.stretchGoal()) // - .withUnit(keyResultMetricDto.unit()) // - .withId(keyResultMetricDto.id()) // - .withVersion(keyResultMetricDto.version()) // - .withObjective(objectiveBusinessService.getEntityById(keyResultMetricDto.objective().id())) // - .withTitle(keyResultMetricDto.title()) // - .withDescription(keyResultMetricDto.description()) // - .withOwner(userBusinessService.getUserById(keyResultMetricDto.owner().id())) // - .withCreatedOn(keyResultMetricDto.createdOn()) // - .withModifiedOn(keyResultMetricDto.modifiedOn()) // - .build(); + .withBaseline(keyResultMetricDto.baseline()) // + .withStretchGoal(keyResultMetricDto.stretchGoal()) // + .withUnit(keyResultMetricDto.unit()) // + .withId(keyResultMetricDto.id()) // + .withVersion(keyResultMetricDto.version()) // + .withObjective(objectiveBusinessService.getEntityById(keyResultMetricDto.objective() + .id())) // + .withTitle(keyResultMetricDto.title()) // + .withDescription(keyResultMetricDto.description()) // + .withOwner(userBusinessService.getUserById(keyResultMetricDto.owner().id())) // + .withCreatedOn(keyResultMetricDto.createdOn()) // + .withModifiedOn(keyResultMetricDto.modifiedOn()) // + .build(); } public KeyResultLastCheckInMetricDto getLastCheckInDto(Long keyResultId) { @@ -88,8 +89,12 @@ public KeyResultLastCheckInMetricDto getLastCheckInDto(Long keyResultId) { if (lastCheckIn == null) { return null; } - return new KeyResultLastCheckInMetricDto(lastCheckIn.getId(), lastCheckIn.getVersion(), - ((CheckInMetric) lastCheckIn).getValue(), lastCheckIn.getConfidence(), lastCheckIn.getCreatedOn(), - lastCheckIn.getChangeInfo(), lastCheckIn.getInitiatives()); + return new KeyResultLastCheckInMetricDto(lastCheckIn.getId(), + lastCheckIn.getVersion(), + ((CheckInMetric) lastCheckIn).getValue(), + lastCheckIn.getConfidence(), + lastCheckIn.getCreatedOn(), + lastCheckIn.getChangeInfo(), + lastCheckIn.getInitiatives()); } } diff --git a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapper.java b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapper.java index e62c93b482..74287326d4 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapper.java @@ -10,9 +10,8 @@ import ch.puzzle.okr.service.business.CheckInBusinessService; import ch.puzzle.okr.service.business.ObjectiveBusinessService; import ch.puzzle.okr.service.business.UserBusinessService; -import org.springframework.stereotype.Component; - import java.util.List; +import org.springframework.stereotype.Component; @Component public class KeyResultOrdinalMapper { @@ -23,8 +22,8 @@ public class KeyResultOrdinalMapper { private final ActionMapper actionMapper; public KeyResultOrdinalMapper(UserBusinessService userBusinessService, - ObjectiveBusinessService objectiveBusinessService, CheckInBusinessService checkInBusinessService, - ActionMapper actionMapper) { + ObjectiveBusinessService objectiveBusinessService, + CheckInBusinessService checkInBusinessService, ActionMapper actionMapper) { this.userBusinessService = userBusinessService; this.objectiveBusinessService = objectiveBusinessService; this.checkInBusinessService = checkInBusinessService; @@ -33,55 +32,56 @@ public KeyResultOrdinalMapper(UserBusinessService userBusinessService, public KeyResultDto toDto(KeyResultOrdinal keyResult, List actionList) { KeyResultUserDto ownerDto = new KeyResultUserDto( // - keyResult.getOwner().getId(), // - keyResult.getOwner().getFirstname(), // - keyResult.getOwner().getLastname()); + keyResult.getOwner().getId(), // + keyResult.getOwner().getFirstname(), // + keyResult.getOwner().getLastname()); KeyResultQuarterDto quarterDto = new KeyResultQuarterDto( // - keyResult.getObjective().getQuarter().getId(), // - keyResult.getObjective().getQuarter().getLabel(), // - keyResult.getObjective().getQuarter().getStartDate(), // - keyResult.getObjective().getQuarter().getEndDate()); + keyResult.getObjective().getQuarter().getId(), // + keyResult.getObjective().getQuarter().getLabel(), // + keyResult.getObjective().getQuarter().getStartDate(), // + keyResult.getObjective().getQuarter().getEndDate()); KeyResultObjectiveDto objectiveDto = new KeyResultObjectiveDto( // - keyResult.getObjective().getId(), // - keyResult.getObjective().getState().toString(), // - quarterDto); + keyResult.getObjective().getId(), // + keyResult.getObjective().getState().toString(), // + quarterDto); KeyResultLastCheckInOrdinalDto lastCheckInDto = getLastCheckInDto(keyResult.getId()); return new KeyResultOrdinalDto( // - keyResult.getId(), // - keyResult.getVersion(), // - keyResult.getKeyResultType(), // - keyResult.getTitle(), // - keyResult.getDescription(), // - keyResult.getCommitZone(), // - keyResult.getTargetZone(), // - keyResult.getStretchZone(), // - ownerDto, // - objectiveDto, // - lastCheckInDto, // - keyResult.getCreatedOn(), // - keyResult.getModifiedOn(), // - keyResult.isWriteable(), // - actionList.stream().map(actionMapper::toDto).toList()); + keyResult.getId(), // + keyResult.getVersion(), // + keyResult.getKeyResultType(), // + keyResult.getTitle(), // + keyResult.getDescription(), // + keyResult.getCommitZone(), // + keyResult.getTargetZone(), // + keyResult.getStretchZone(), // + ownerDto, // + objectiveDto, // + lastCheckInDto, // + keyResult.getCreatedOn(), // + keyResult.getModifiedOn(), // + keyResult.isWriteable(), // + actionList.stream().map(actionMapper::toDto).toList()); } public KeyResult toKeyResultOrdinal(KeyResultOrdinalDto keyResultOrdinalDto) { return KeyResultOrdinal.Builder.builder() // - .withCommitZone(keyResultOrdinalDto.commitZone()) // - .withTargetZone(keyResultOrdinalDto.targetZone()) // - .withStretchZone(keyResultOrdinalDto.stretchZone()) // - .withId(keyResultOrdinalDto.id()) // - .withVersion(keyResultOrdinalDto.version()) // - .withObjective(objectiveBusinessService.getEntityById(keyResultOrdinalDto.objective().id())) // - .withTitle(keyResultOrdinalDto.title()) // - .withDescription(keyResultOrdinalDto.description()) // - .withOwner(userBusinessService.getUserById(keyResultOrdinalDto.owner().id())) // - .withCreatedOn(keyResultOrdinalDto.createdOn()) // - .withModifiedOn(keyResultOrdinalDto.modifiedOn()) // - .build(); + .withCommitZone(keyResultOrdinalDto.commitZone()) // + .withTargetZone(keyResultOrdinalDto.targetZone()) // + .withStretchZone(keyResultOrdinalDto.stretchZone()) // + .withId(keyResultOrdinalDto.id()) // + .withVersion(keyResultOrdinalDto.version()) // + .withObjective(objectiveBusinessService.getEntityById(keyResultOrdinalDto.objective() + .id())) // + .withTitle(keyResultOrdinalDto.title()) // + .withDescription(keyResultOrdinalDto.description()) // + .withOwner(userBusinessService.getUserById(keyResultOrdinalDto.owner().id())) // + .withCreatedOn(keyResultOrdinalDto.createdOn()) // + .withModifiedOn(keyResultOrdinalDto.modifiedOn()) // + .build(); } public KeyResultLastCheckInOrdinalDto getLastCheckInDto(Long keyResultId) { @@ -89,8 +89,12 @@ public KeyResultLastCheckInOrdinalDto getLastCheckInDto(Long keyResultId) { if (lastCheckIn == null) { return null; } - return new KeyResultLastCheckInOrdinalDto(lastCheckIn.getId(), lastCheckIn.getVersion(), - ((CheckInOrdinal) lastCheckIn).getZone(), lastCheckIn.getConfidence(), lastCheckIn.getCreatedOn(), - lastCheckIn.getChangeInfo(), lastCheckIn.getInitiatives()); + return new KeyResultLastCheckInOrdinalDto(lastCheckIn.getId(), + lastCheckIn.getVersion(), + ((CheckInOrdinal) lastCheckIn).getZone(), + lastCheckIn.getConfidence(), + lastCheckIn.getCreatedOn(), + lastCheckIn.getChangeInfo(), + lastCheckIn.getInitiatives()); } } diff --git a/backend/src/main/java/ch/puzzle/okr/models/Action.java b/backend/src/main/java/ch/puzzle/okr/models/Action.java index eabed114da..793f7ec297 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Action.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Action.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.models; import ch.puzzle.okr.models.keyresult.KeyResult; - import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; @@ -106,7 +105,7 @@ public void setWriteable(boolean writeable) { @Override public String toString() { return "Action{" + "id=" + id + ", version=" + version + ", action='" + action + '\'' + ", priority=" + priority - + ", isChecked=" + isChecked + ", keyResult=" + keyResult + ", writeable=" + writeable + '}'; + + ", isChecked=" + isChecked + ", keyResult=" + keyResult + ", writeable=" + writeable + '}'; } @Override @@ -117,8 +116,8 @@ public boolean equals(Object o) { return false; Action action1 = (Action) o; return version == action1.version && priority == action1.priority && isChecked == action1.isChecked - && writeable == action1.writeable && Objects.equals(id, action1.id) - && Objects.equals(action, action1.action) && Objects.equals(keyResult, action1.keyResult); + && writeable == action1.writeable && Objects.equals(id, action1.id) + && Objects.equals(action, action1.action) && Objects.equals(keyResult, action1.keyResult); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/Completed.java b/backend/src/main/java/ch/puzzle/okr/models/Completed.java index 7900c2910e..ea77c1d780 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Completed.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Completed.java @@ -59,7 +59,7 @@ public void setComment(String comment) { @Override public String toString() { return "Completed{" + "id=" + id + ", version=" + version + ", objective=" + objective + ", comment='" + comment - + '\'' + '}'; + + '\'' + '}'; } @Override @@ -70,7 +70,7 @@ public boolean equals(Object o) { return false; Completed completed = (Completed) o; return Objects.equals(id, completed.id) && version == completed.version - && Objects.equals(objective, completed.objective) && Objects.equals(comment, completed.comment); + && Objects.equals(objective, completed.objective) && Objects.equals(comment, completed.comment); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/Quarter.java b/backend/src/main/java/ch/puzzle/okr/models/Quarter.java index 537e0aa955..87b3abaf2b 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Quarter.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Quarter.java @@ -2,7 +2,6 @@ import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; - import java.time.LocalDate; import java.util.Objects; @@ -62,7 +61,7 @@ public void setEndDate(LocalDate endDate) { @Override public String toString() { return "Quarter{" + "id=" + id + ", label='" + label + '\'' + ", startDate=" + startDate + ", endDate=" - + endDate + '}'; + + endDate + '}'; } @Override @@ -73,7 +72,7 @@ public boolean equals(Object o) { return false; Quarter quarter = (Quarter) o; return Objects.equals(id, quarter.id) && Objects.equals(label, quarter.label) - && Objects.equals(startDate, quarter.startDate) && Objects.equals(endDate, quarter.endDate); + && Objects.equals(startDate, quarter.startDate) && Objects.equals(endDate, quarter.endDate); } @Override @@ -94,7 +93,8 @@ public static Builder builder() { return new Builder(); } - public Builder withId(@NotNull Long id) { + public Builder withId(@NotNull + Long id) { this.id = id; return this; } diff --git a/backend/src/main/java/ch/puzzle/okr/models/State.java b/backend/src/main/java/ch/puzzle/okr/models/State.java index 0099fcec97..5c12201a7e 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/State.java +++ b/backend/src/main/java/ch/puzzle/okr/models/State.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.models; public enum State { - SUCCESSFUL, NOTSUCCESSFUL, ONGOING, DRAFT + SUCCESSFUL, + NOTSUCCESSFUL, + ONGOING, + DRAFT } diff --git a/backend/src/main/java/ch/puzzle/okr/models/Team.java b/backend/src/main/java/ch/puzzle/okr/models/Team.java index 0099a9ba43..dd81ba7f35 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Team.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Team.java @@ -4,7 +4,6 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; - import java.util.List; import java.util.Objects; @@ -85,7 +84,7 @@ public boolean equals(Object o) { return false; Team team = (Team) o; return Objects.equals(id, team.id) && Objects.equals(version, team.version) && Objects.equals(name, team.name) - && Objects.equals(writeable, team.writeable); + && Objects.equals(writeable, team.writeable); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/Unit.java b/backend/src/main/java/ch/puzzle/okr/models/Unit.java index 13aff3bb47..941fb85f43 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Unit.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Unit.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.models; public enum Unit { - PERCENT, CHF, EUR, FTE, NUMBER + PERCENT, + CHF, + EUR, + FTE, + NUMBER } diff --git a/backend/src/main/java/ch/puzzle/okr/models/User.java b/backend/src/main/java/ch/puzzle/okr/models/User.java index 5bfa5e425b..e92d9b2e3d 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/User.java +++ b/backend/src/main/java/ch/puzzle/okr/models/User.java @@ -5,7 +5,6 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; - import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -109,7 +108,7 @@ public void setOkrChampion(boolean okrChampion) { @Override public String toString() { return "User{" + "id=" + id + ", version=" + version + ", firstname='" + firstname + '\'' + ", lastname='" - + lastname + '\'' + ", email='" + email + '\'' + ", isOkrChampion='" + isOkrChampion + '\'' + '}'; + + lastname + '\'' + ", email='" + email + '\'' + ", isOkrChampion='" + isOkrChampion + '\'' + '}'; } @Override @@ -120,8 +119,8 @@ public boolean equals(Object o) { return false; User user = (User) o; return Objects.equals(id, user.id) && Objects.equals(version, user.version) - && Objects.equals(firstname, user.firstname) && Objects.equals(lastname, user.lastname) - && Objects.equals(email, user.email) && Objects.equals(isOkrChampion, user.isOkrChampion); + && Objects.equals(firstname, user.firstname) && Objects.equals(lastname, user.lastname) + && Objects.equals(email, user.email) && Objects.equals(isOkrChampion, user.isOkrChampion); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/UserTeam.java b/backend/src/main/java/ch/puzzle/okr/models/UserTeam.java index 3f14e7c811..281f02faf6 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/UserTeam.java +++ b/backend/src/main/java/ch/puzzle/okr/models/UserTeam.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.models; import jakarta.persistence.*; - import java.util.Objects; @Entity @@ -88,7 +87,7 @@ public boolean equals(Object o) { } UserTeam userTeam = (UserTeam) o; return version == userTeam.version && isTeamAdmin == userTeam.isTeamAdmin && Objects.equals(id, userTeam.id) - && Objects.equals(user, userTeam.user) && Objects.equals(team, userTeam.team); + && Objects.equals(user, userTeam.user) && Objects.equals(team, userTeam.team); } @Override @@ -99,7 +98,7 @@ public int hashCode() { @Override public String toString() { return "UserTeam{" + "id=" + id + ", version=" + version + ", user=" + user + ", team=" + team - + ", isTeamAdmin=" + isTeamAdmin + '}'; + + ", isTeamAdmin=" + isTeamAdmin + '}'; } public static class Builder { diff --git a/backend/src/main/java/ch/puzzle/okr/models/alignment/Alignment.java b/backend/src/main/java/ch/puzzle/okr/models/alignment/Alignment.java index cf3a64f7fc..2c6ae48992 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/alignment/Alignment.java +++ b/backend/src/main/java/ch/puzzle/okr/models/alignment/Alignment.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.models.alignment; import ch.puzzle.okr.models.Objective; - import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; import java.util.Objects; @@ -59,7 +58,7 @@ public boolean equals(Object o) { return false; Alignment alignment = (Alignment) o; return Objects.equals(id, alignment.id) && version == alignment.version - && Objects.equals(alignedObjective, alignment.alignedObjective); + && Objects.equals(alignedObjective, alignment.alignedObjective); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelection.java b/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelection.java index 0246817184..562b5a4fc0 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelection.java +++ b/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelection.java @@ -2,9 +2,8 @@ import jakarta.persistence.EmbeddedId; import jakarta.persistence.Entity; -import org.hibernate.annotations.Immutable; - import java.util.Objects; +import org.hibernate.annotations.Immutable; @Entity @Immutable @@ -61,10 +60,10 @@ public boolean equals(Object o) { return false; AlignmentSelection alignmentSelection = (AlignmentSelection) o; return Objects.equals(alignmentSelectionId, alignmentSelection.alignmentSelectionId) - && Objects.equals(teamId, alignmentSelection.teamId) - && Objects.equals(objectiveTitle, alignmentSelection.objectiveTitle) - && Objects.equals(quarterId, alignmentSelection.quarterId) - && Objects.equals(keyResultTitle, alignmentSelection.keyResultTitle); + && Objects.equals(teamId, alignmentSelection.teamId) + && Objects.equals(objectiveTitle, alignmentSelection.objectiveTitle) + && Objects.equals(quarterId, alignmentSelection.quarterId) + && Objects.equals(keyResultTitle, alignmentSelection.keyResultTitle); } @Override @@ -75,9 +74,9 @@ public int hashCode() { @Override public String toString() { return "AlignmentSelection{" + "alignmentSelectionId=" + alignmentSelectionId + ", teamId='" + teamId - + ", teamName='" + teamName + '\'' + ", objectiveTitle='" + objectiveTitle + '\'' + ", quarterId=" - + quarterId + ", quarterLabel='" + quarterLabel + '\'' + ", keyResultTitle='" + keyResultTitle + '\'' - + '}'; + + ", teamName='" + teamName + '\'' + ", objectiveTitle='" + objectiveTitle + '\'' + ", quarterId=" + + quarterId + ", quarterLabel='" + quarterLabel + '\'' + ", keyResultTitle='" + keyResultTitle + '\'' + + '}'; } public static final class Builder { diff --git a/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelectionId.java b/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelectionId.java index 75c52cf2b8..e99a7c5611 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelectionId.java +++ b/backend/src/main/java/ch/puzzle/okr/models/alignment/AlignmentSelectionId.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.models.alignment; import jakarta.persistence.Embeddable; - import java.io.Serializable; import java.util.Objects; diff --git a/backend/src/main/java/ch/puzzle/okr/models/alignment/KeyResultAlignment.java b/backend/src/main/java/ch/puzzle/okr/models/alignment/KeyResultAlignment.java index 1797ca005b..72ef8f21d7 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/alignment/KeyResultAlignment.java +++ b/backend/src/main/java/ch/puzzle/okr/models/alignment/KeyResultAlignment.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.models.alignment; import ch.puzzle.okr.models.keyresult.KeyResult; - import jakarta.persistence.*; import java.util.Objects; diff --git a/backend/src/main/java/ch/puzzle/okr/models/alignment/ObjectiveAlignment.java b/backend/src/main/java/ch/puzzle/okr/models/alignment/ObjectiveAlignment.java index f15422894f..7225c08176 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/alignment/ObjectiveAlignment.java +++ b/backend/src/main/java/ch/puzzle/okr/models/alignment/ObjectiveAlignment.java @@ -4,7 +4,6 @@ import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import jakarta.persistence.ManyToOne; - import java.util.Objects; @Entity diff --git a/backend/src/main/java/ch/puzzle/okr/models/authorization/AuthorizationUser.java b/backend/src/main/java/ch/puzzle/okr/models/authorization/AuthorizationUser.java index 829ba69765..388bfa7632 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/authorization/AuthorizationUser.java +++ b/backend/src/main/java/ch/puzzle/okr/models/authorization/AuthorizationUser.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.models.authorization; import ch.puzzle.okr.models.User; - import java.util.List; public record AuthorizationUser(User user) { @@ -14,7 +13,8 @@ public boolean isUserMemberInTeam(Long teamId) { } public boolean isUserAdminInTeam(Long teamId) { - return this.user.getUserTeamList().stream() - .anyMatch(ut -> ut.isTeamAdmin() && ut.getTeam().getId().equals(teamId)); + return this.user.getUserTeamList() + .stream() + .anyMatch(ut -> ut.isTeamAdmin() && ut.getTeam().getId().equals(teamId)); } } diff --git a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckIn.java b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckIn.java index 7105ca5950..13f6804c99 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckIn.java +++ b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckIn.java @@ -4,10 +4,8 @@ import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.WriteableInterface; import ch.puzzle.okr.models.keyresult.KeyResult; - import jakarta.persistence.*; import jakarta.validation.constraints.*; - import java.time.LocalDateTime; import java.util.Objects; @@ -134,9 +132,9 @@ public void setWriteable(boolean writeable) { @Override public String toString() { return "CheckIn{" + "id=" + id + ", version=" + version + ", changeInfo='" + changeInfo + '\'' - + ", initiatives='" + initiatives + '\'' + ", confidence=" + confidence + ", keyResult=" + keyResult - + ", createdBy=" + createdBy + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn - + ", checkInType='" + checkInType + '\'' + ", writeable=" + writeable + '\'' + '}'; + + ", initiatives='" + initiatives + '\'' + ", confidence=" + confidence + ", keyResult=" + keyResult + + ", createdBy=" + createdBy + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn + + ", checkInType='" + checkInType + '\'' + ", writeable=" + writeable + '\'' + '}'; } @Override @@ -147,16 +145,24 @@ public boolean equals(Object o) { return false; CheckIn checkIn = (CheckIn) o; return Objects.equals(id, checkIn.id) && version == checkIn.version - && Objects.equals(changeInfo, checkIn.changeInfo) && Objects.equals(initiatives, checkIn.initiatives) - && Objects.equals(confidence, checkIn.confidence) && Objects.equals(keyResult, checkIn.keyResult) - && Objects.equals(createdBy, checkIn.createdBy) && Objects.equals(createdOn, checkIn.createdOn) - && Objects.equals(modifiedOn, checkIn.modifiedOn) && Objects.equals(checkInType, checkIn.checkInType); + && Objects.equals(changeInfo, checkIn.changeInfo) && Objects.equals(initiatives, checkIn.initiatives) + && Objects.equals(confidence, checkIn.confidence) && Objects.equals(keyResult, checkIn.keyResult) + && Objects.equals(createdBy, checkIn.createdBy) && Objects.equals(createdOn, checkIn.createdOn) + && Objects.equals(modifiedOn, checkIn.modifiedOn) && Objects.equals(checkInType, checkIn.checkInType); } @Override public int hashCode() { - return Objects.hash(id, version, changeInfo, initiatives, confidence, keyResult, createdBy, createdOn, - modifiedOn, checkInType); + return Objects.hash(id, + version, + changeInfo, + initiatives, + confidence, + keyResult, + createdBy, + createdOn, + modifiedOn, + checkInType); } /* Constructor */ diff --git a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInMetric.java b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInMetric.java index 25faccff0e..b26834e455 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInMetric.java +++ b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInMetric.java @@ -1,14 +1,13 @@ package ch.puzzle.okr.models.checkin; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; + import ch.puzzle.okr.models.MessageKey; import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import jakarta.validation.constraints.NotNull; - import java.util.Objects; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; - @Entity @DiscriminatorValue(KEY_RESULT_TYPE_METRIC) public class CheckInMetric extends CheckIn { diff --git a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInOrdinal.java b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInOrdinal.java index 62485b5101..be7deba8e6 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInOrdinal.java +++ b/backend/src/main/java/ch/puzzle/okr/models/checkin/CheckInOrdinal.java @@ -1,16 +1,15 @@ package ch.puzzle.okr.models.checkin; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; + import ch.puzzle.okr.models.MessageKey; import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.validation.constraints.NotNull; - import java.util.Objects; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; - @Entity @DiscriminatorValue(KEY_RESULT_TYPE_ORDINAL) public class CheckInOrdinal extends CheckIn { diff --git a/backend/src/main/java/ch/puzzle/okr/models/checkin/Zone.java b/backend/src/main/java/ch/puzzle/okr/models/checkin/Zone.java index 79eec69420..4424418197 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/checkin/Zone.java +++ b/backend/src/main/java/ch/puzzle/okr/models/checkin/Zone.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.models.checkin; public enum Zone { - FAIL, COMMIT, TARGET, STRETCH + FAIL, + COMMIT, + TARGET, + STRETCH } diff --git a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResult.java b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResult.java index 2db94c8b9e..a761d5b099 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResult.java +++ b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResult.java @@ -4,7 +4,6 @@ import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.WriteableInterface; - import jakarta.persistence.*; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; @@ -139,9 +138,9 @@ public void setWriteable(boolean writeable) { @Override public String toString() { return "KeyResult{" + "id=" + id + ", version=" + version + ", objective=" + objective + ", title='" + title - + '\'' + ", description='" + description + '\'' + ", owner=" + owner + ", createdBy=" + createdBy - + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn + ", keyResultType='" + keyResultType - + ", writeable=" + writeable + '\'' + '}'; + + '\'' + ", description='" + description + '\'' + ", owner=" + owner + ", createdBy=" + createdBy + + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn + ", keyResultType='" + keyResultType + + ", writeable=" + writeable + '\'' + '}'; } @Override @@ -152,17 +151,25 @@ public boolean equals(Object o) { return false; KeyResult keyResult = (KeyResult) o; return Objects.equals(id, keyResult.id) && version == keyResult.version - && Objects.equals(objective, keyResult.objective) && Objects.equals(title, keyResult.title) - && Objects.equals(description, keyResult.description) && Objects.equals(owner, keyResult.owner) - && Objects.equals(createdBy, keyResult.createdBy) && Objects.equals(createdOn, keyResult.createdOn) - && Objects.equals(modifiedOn, keyResult.modifiedOn) - && Objects.equals(keyResultType, keyResult.keyResultType); + && Objects.equals(objective, keyResult.objective) && Objects.equals(title, keyResult.title) + && Objects.equals(description, keyResult.description) && Objects.equals(owner, keyResult.owner) + && Objects.equals(createdBy, keyResult.createdBy) && Objects.equals(createdOn, keyResult.createdOn) + && Objects.equals(modifiedOn, keyResult.modifiedOn) + && Objects.equals(keyResultType, keyResult.keyResultType); } @Override public int hashCode() { - return Objects.hash(id, version, objective, title, description, owner, createdBy, createdOn, modifiedOn, - keyResultType); + return Objects.hash(id, + version, + objective, + title, + description, + owner, + createdBy, + createdOn, + modifiedOn, + keyResultType); } protected KeyResult() { diff --git a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultMetric.java b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultMetric.java index 773501abc4..ece94d53f9 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultMetric.java +++ b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultMetric.java @@ -1,14 +1,13 @@ package ch.puzzle.okr.models.keyresult; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; + import ch.puzzle.okr.models.MessageKey; import ch.puzzle.okr.models.Unit; - import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; import java.util.Objects; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; - @Entity @DiscriminatorValue(KEY_RESULT_TYPE_METRIC) public class KeyResultMetric extends KeyResult { @@ -54,8 +53,8 @@ public KeyResultMetric() { public boolean equals(Object o) { if (o instanceof KeyResultMetric) { return super.equals(o) && Objects.equals(baseline, ((KeyResultMetric) o).baseline) - && Objects.equals(stretchGoal, ((KeyResultMetric) o).stretchGoal) - && Objects.equals(unit, ((KeyResultMetric) o).unit); + && Objects.equals(stretchGoal, ((KeyResultMetric) o).stretchGoal) + && Objects.equals(unit, ((KeyResultMetric) o).unit); } return false; } @@ -68,7 +67,7 @@ public int hashCode() { @Override public String toString() { return super.toString() + "KeyResultMetric{" + "baseline=" + baseline + ", stretchGoal=" + stretchGoal - + ", unit='" + unit + '\'' + '}'; + + ", unit='" + unit + '\'' + '}'; } private KeyResultMetric(Builder builder) { diff --git a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultOrdinal.java b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultOrdinal.java index d95f92a302..2f98b0e962 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultOrdinal.java +++ b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultOrdinal.java @@ -1,14 +1,13 @@ package ch.puzzle.okr.models.keyresult; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; + import jakarta.persistence.DiscriminatorValue; import jakarta.persistence.Entity; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; - import java.util.Objects; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; - @Entity @DiscriminatorValue(KEY_RESULT_TYPE_ORDINAL) public class KeyResultOrdinal extends KeyResult { @@ -56,8 +55,8 @@ public KeyResultOrdinal() { public boolean equals(Object o) { if (o instanceof KeyResultOrdinal) { return super.equals(o) && Objects.equals(commitZone, ((KeyResultOrdinal) o).commitZone) - && Objects.equals(targetZone, ((KeyResultOrdinal) o).targetZone) - && Objects.equals(stretchZone, ((KeyResultOrdinal) o).stretchZone); + && Objects.equals(targetZone, ((KeyResultOrdinal) o).targetZone) + && Objects.equals(stretchZone, ((KeyResultOrdinal) o).stretchZone); } return false; } @@ -70,7 +69,7 @@ public int hashCode() { @Override public String toString() { return super.toString() + "KeyResultOrdinal{" + "commitZone='" + commitZone + '\'' + ", targetZone='" - + targetZone + '\'' + ", stretchZone='" + stretchZone + '\'' + '}'; + + targetZone + '\'' + ", stretchZone='" + stretchZone + '\'' + '}'; } private KeyResultOrdinal(Builder builder) { diff --git a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultWithActionList.java b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultWithActionList.java index 1fae579ab3..2b0f367d53 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultWithActionList.java +++ b/backend/src/main/java/ch/puzzle/okr/models/keyresult/KeyResultWithActionList.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.models.keyresult; import ch.puzzle.okr.models.Action; - import java.util.List; public record KeyResultWithActionList(KeyResult keyResult, List actionList) { diff --git a/backend/src/main/java/ch/puzzle/okr/models/overview/Overview.java b/backend/src/main/java/ch/puzzle/okr/models/overview/Overview.java index b2b3eb6d79..303f400e81 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/overview/Overview.java +++ b/backend/src/main/java/ch/puzzle/okr/models/overview/Overview.java @@ -6,9 +6,8 @@ import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; -import org.hibernate.annotations.Immutable; - import java.time.LocalDateTime; +import org.hibernate.annotations.Immutable; @Entity @Immutable @@ -158,14 +157,14 @@ public void setWriteable(boolean writeable) { @Override public String toString() { return "Overview{" + "overviewId=" + overviewId + ", teamVersion='" + teamVersion + ", teamName='" + teamName - + '\'' + ", objectiveTitle='" + objectiveTitle + '\'' + ", objectiveState=" + objectiveState - + ", objectiveCreatedOn=" + objectiveCreatedOn + ", quarterId=" + quarterId + ", quarterLabel='" - + quarterLabel + '\'' + ", keyResultTitle='" + keyResultTitle + '\'' + ", keyResultType='" - + keyResultType + '\'' + ", baseline=" + baseline + ", stretchGoal=" + stretchGoal + ", unit='" + unit - + '\'' + ", commitZone='" + commitZone + '\'' + ", targetZone='" + targetZone + '\'' + ", stretchZone='" - + stretchZone + '\'' + ", checkInValue=" + checkInValue + ", checkInZone='" + checkInZone + '\'' - + ", confidence=" + confidence + ", createdOn=" + checkInCreatedOn + ", writeable=" + writeable + '\'' - + '}'; + + '\'' + ", objectiveTitle='" + objectiveTitle + '\'' + ", objectiveState=" + objectiveState + + ", objectiveCreatedOn=" + objectiveCreatedOn + ", quarterId=" + quarterId + ", quarterLabel='" + + quarterLabel + '\'' + ", keyResultTitle='" + keyResultTitle + '\'' + ", keyResultType='" + + keyResultType + '\'' + ", baseline=" + baseline + ", stretchGoal=" + stretchGoal + ", unit='" + unit + + '\'' + ", commitZone='" + commitZone + '\'' + ", targetZone='" + targetZone + '\'' + ", stretchZone='" + + stretchZone + '\'' + ", checkInValue=" + checkInValue + ", checkInZone='" + checkInZone + '\'' + + ", confidence=" + confidence + ", createdOn=" + checkInCreatedOn + ", writeable=" + writeable + '\'' + + '}'; } public static final class Builder { diff --git a/backend/src/main/java/ch/puzzle/okr/models/overview/OverviewId.java b/backend/src/main/java/ch/puzzle/okr/models/overview/OverviewId.java index 62bfb85e60..5923ba1808 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/overview/OverviewId.java +++ b/backend/src/main/java/ch/puzzle/okr/models/overview/OverviewId.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.models.overview; import jakarta.persistence.Embeddable; - import java.io.Serializable; import java.util.Objects; @@ -50,7 +49,7 @@ public Long getCheckInId() { @Override public String toString() { return "OverviewId{" + "teamId=" + teamId + ", objectiveId=" + objectiveId + ", keyResultId=" + keyResultId - + ", checkInId=" + checkInId + '}'; + + ", checkInId=" + checkInId + '}'; } @Override @@ -61,7 +60,7 @@ public boolean equals(Object o) { return false; OverviewId that = (OverviewId) o; return Objects.equals(teamId, that.teamId) && Objects.equals(objectiveId, that.objectiveId) - && Objects.equals(keyResultId, that.keyResultId) && Objects.equals(checkInId, that.checkInId); + && Objects.equals(keyResultId, that.keyResultId) && Objects.equals(checkInId, that.checkInId); } @Override diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializer.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializer.java index d58c195c77..35c8ea6ea8 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializer.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializer.java @@ -11,24 +11,26 @@ public class FlywayMultitenantMigrationInitializer { private final String[] scriptLocations; public FlywayMultitenantMigrationInitializer(TenantConfigProviderInterface tenantConfigProvider, - final @Value("${spring.flyway.locations}") String[] scriptLocations) { + final @Value("${spring.flyway.locations}") + String[] scriptLocations) { this.tenantConfigProvider = tenantConfigProvider; this.scriptLocations = scriptLocations; } public void migrateFlyway() { this.tenantConfigProvider.getTenantConfigs().forEach((tenantConfig) -> { - TenantConfigProvider.DataSourceConfig dataSourceConfig = this.tenantConfigProvider - .getTenantConfigById(tenantConfig.tenantId()) - .map(TenantConfigProvider.TenantConfig::dataSourceConfig).orElseThrow( - () -> new EntityNotFoundException("Cannot find tenant for configuring flyway migration")); + TenantConfigProvider.DataSourceConfig dataSourceConfig = this.tenantConfigProvider.getTenantConfigById(tenantConfig.tenantId()) + .map(TenantConfigProvider.TenantConfig::dataSourceConfig) + .orElseThrow(() -> new EntityNotFoundException("Cannot find tenant for configuring flyway migration")); Flyway tenantSchemaFlyway = Flyway.configure() // - .dataSource(dataSourceConfig.url(), dataSourceConfig.name(), dataSourceConfig.password()) // - .locations(scriptLocations) // - .baselineOnMigrate(Boolean.TRUE) // - .schemas(dataSourceConfig.schema()) // - .load(); + .dataSource(dataSourceConfig.url(), + dataSourceConfig.name(), + dataSourceConfig.password()) // + .locations(scriptLocations) // + .baselineOnMigrate(Boolean.TRUE) // + .schemas(dataSourceConfig.schema()) // + .load(); tenantSchemaFlyway.migrate(); }); diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/HibernateContext.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/HibernateContext.java index 42e068ece0..d78c3ba4ac 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/HibernateContext.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/HibernateContext.java @@ -1,8 +1,7 @@ package ch.puzzle.okr.multitenancy; -import org.springframework.core.env.ConfigurableEnvironment; - import java.util.Properties; +import org.springframework.core.env.ConfigurableEnvironment; public class HibernateContext { public static final String HIBERNATE_CONNECTION_URL = "hibernate.connection.url"; diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProvider.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProvider.java index 05ff90ce53..33e2648ffd 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProvider.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProvider.java @@ -1,6 +1,12 @@ package ch.puzzle.okr.multitenancy; +import static ch.puzzle.okr.multitenancy.TenantContext.DEFAULT_TENANT_ID; + import ch.puzzle.okr.exception.ConnectionProviderException; +import java.sql.Connection; +import java.sql.SQLException; +import java.text.MessageFormat; +import java.util.*; import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider; @@ -8,13 +14,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.Connection; -import java.sql.SQLException; -import java.text.MessageFormat; -import java.util.*; - -import static ch.puzzle.okr.multitenancy.TenantContext.DEFAULT_TENANT_ID; - public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider { private static final Logger logger = LoggerFactory.getLogger(SchemaMultiTenantConnectionProvider.class); @@ -56,26 +55,26 @@ protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { protected ConnectionProvider getConnectionProvider(String tenantIdentifier) { return Optional.ofNullable(tenantIdentifier) // - .map(connectionProviderMap::get) // - .orElseGet(() -> createNewConnectionProvider(tenantIdentifier)); + .map(connectionProviderMap::get) // + .orElseGet(() -> createNewConnectionProvider(tenantIdentifier)); } private ConnectionProvider createNewConnectionProvider(String tenantIdentifier) { return Optional.ofNullable(tenantIdentifier) // - .map(this::createConnectionProvider) // - .map(connectionProvider -> { - connectionProviderMap.put(tenantIdentifier, connectionProvider); - return connectionProvider; - }) // - .orElseThrow(() -> new ConnectionProviderException( - String.format("Cannot create new connection provider for tenant: %s", tenantIdentifier))); + .map(this::createConnectionProvider) // + .map(connectionProvider -> { + connectionProviderMap.put(tenantIdentifier, connectionProvider); + return connectionProvider; + }) // + .orElseThrow(() -> new ConnectionProviderException(String.format("Cannot create new connection provider for tenant: %s", + tenantIdentifier))); } private ConnectionProvider createConnectionProvider(String tenantIdentifier) { return Optional.ofNullable(tenantIdentifier) // - .map(this::getHibernatePropertiesForTenantIdentifier) // - .map(this::initConnectionProvider) // - .orElse(null); + .map(this::getHibernatePropertiesForTenantIdentifier) // + .map(this::initConnectionProvider) // + .orElse(null); } protected Properties getHibernatePropertiesForTenantIdentifier(String tenantIdentifier) { diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantConfigProvider.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantConfigProvider.java index 97521d9d7a..7006e6d1e2 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantConfigProvider.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantConfigProvider.java @@ -1,44 +1,54 @@ package ch.puzzle.okr.multitenancy; +import java.text.MessageFormat; +import java.util.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -import java.text.MessageFormat; -import java.util.*; - @Component public class TenantConfigProvider implements TenantConfigProviderInterface { private static final String EMAIL_DELIMITER = ","; private final Map tenantConfigs = new HashMap<>(); private final Environment env; - public TenantConfigProvider(final @Value("${okr.tenant-ids}") String[] tenantIds, Environment env) { + public TenantConfigProvider(final @Value("${okr.tenant-ids}") + String[] tenantIds, Environment env) { this.env = env; for (String tenantId : tenantIds) { OauthConfig c = readOauthConfig(tenantId); tenantConfigs.put(tenantId, - createTenantConfig(c.jwkSetUri(), c.frontendClientIssuerUrl(), c.frontendClientId(), tenantId)); + createTenantConfig(c.jwkSetUri(), + c.frontendClientIssuerUrl(), + c.frontendClientId(), + tenantId)); } } private OauthConfig readOauthConfig(String tenantId) { - return new OauthConfig( - env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.resourceserver.jwt.jwk-set-uri", - tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.frontend.issuer-url", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.frontend.client-id", tenantId))); + return new OauthConfig(env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.resourceserver.jwt.jwk-set-uri", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.frontend.issuer-url", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.security.oauth2.frontend.client-id", + tenantId))); } private TenantConfig createTenantConfig(String jwkSetUriTemplate, String frontendClientIssuerUrl, - String frontendClientId, String tenantId) { - return new TenantConfig(tenantId, getOkrChampionEmailsFromTenant(tenantId), jwkSetUriTemplate, - frontendClientIssuerUrl, frontendClientId, this.readDataSourceConfig(tenantId)); + String frontendClientId, String tenantId) { + return new TenantConfig(tenantId, + getOkrChampionEmailsFromTenant(tenantId), + jwkSetUriTemplate, + frontendClientIssuerUrl, + frontendClientId, + this.readDataSourceConfig(tenantId)); } private String[] getOkrChampionEmailsFromTenant(String tenantId) { return Arrays.stream(env.getProperty(MessageFormat.format("okr.tenants.{0}.user.champion.emails", tenantId), "") - .split(EMAIL_DELIMITER)).map(String::trim).toArray(String[]::new); + .split(EMAIL_DELIMITER)) + .map(String::trim) + .toArray(String[]::new); } public List getTenantConfigs() { @@ -47,10 +57,13 @@ public List getTenantConfigs() { private DataSourceConfig readDataSourceConfig(String tenantId) { return new DataSourceConfig(env.getProperty("okr.datasource.driver-class-name"), - env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.url", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.username", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.password", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.schema", tenantId))); + env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.url", tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.username", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.password", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.datasource.schema", + tenantId))); } public Optional getTenantConfigById(String tenantId) { diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantContext.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantContext.java index 7c560ecf8c..d7e16756c9 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantContext.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantContext.java @@ -1,10 +1,9 @@ package ch.puzzle.okr.multitenancy; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Optional; - public class TenantContext { public static final String DEFAULT_TENANT_ID = "public"; private static final Logger logger = LoggerFactory.getLogger(TenantContext.class); diff --git a/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProvider.java b/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProvider.java index 0085cedd8c..e8631bbb3e 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProvider.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProvider.java @@ -1,15 +1,14 @@ package ch.puzzle.okr.multitenancy.customization; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - import java.io.Serializable; import java.text.MessageFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; @Component public class TenantClientCustomizationProvider { @@ -24,7 +23,8 @@ public class TenantClientCustomizationProvider { record CssConfigItem(String cssName, String cssValue) implements Serializable { } - public TenantClientCustomizationProvider(final @Value("${okr.tenant-ids}") String[] tenantIds, Environment env) { + public TenantClientCustomizationProvider(final @Value("${okr.tenant-ids}") + String[] tenantIds, Environment env) { this.env = env; for (String tenantId : tenantIds) { readClientCustomizationConfig(tenantId); @@ -33,14 +33,19 @@ public TenantClientCustomizationProvider(final @Value("${okr.tenant-ids}") Strin } private TenantClientCustomization readClientCustomizationConfig(String tenantId) { - return new TenantClientCustomization( - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.favicon", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.logo", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.triangles", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.background-logo", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.title", tenantId)), - env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.helpSiteUrl", tenantId)), - getCustomCssStyles(tenantId) // + return new TenantClientCustomization(env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.favicon", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.logo", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.triangles", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.background-logo", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.title", + tenantId)), + env.getProperty(MessageFormat.format("okr.tenants.{0}.clientcustomization.helpSiteUrl", + tenantId)), + getCustomCssStyles(tenantId) // ); } diff --git a/backend/src/main/java/ch/puzzle/okr/repository/ActionRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/ActionRepository.java index c6baa06bb4..ed82d16e41 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/ActionRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/ActionRepository.java @@ -1,9 +1,8 @@ package ch.puzzle.okr.repository; import ch.puzzle.okr.models.Action; -import org.springframework.data.repository.CrudRepository; - import java.util.List; +import org.springframework.data.repository.CrudRepository; public interface ActionRepository extends CrudRepository { List getActionsByKeyResultIdOrderByPriorityAsc(Long keyResultId); diff --git a/backend/src/main/java/ch/puzzle/okr/repository/AlignmentRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/AlignmentRepository.java index d6ebcc70a7..5c8a43778f 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/AlignmentRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/AlignmentRepository.java @@ -3,19 +3,20 @@ import ch.puzzle.okr.models.alignment.Alignment; import ch.puzzle.okr.models.alignment.KeyResultAlignment; import ch.puzzle.okr.models.alignment.ObjectiveAlignment; +import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; -import java.util.List; - public interface AlignmentRepository extends CrudRepository { List findByAlignedObjectiveId(Long alignedObjectiveId); @Query(value = "from KeyResultAlignment where targetKeyResult.id = :keyResultId") - List findByKeyResultAlignmentId(@Param("keyResultId") Long keyResultId); + List findByKeyResultAlignmentId(@Param("keyResultId") + Long keyResultId); @Query(value = "from ObjectiveAlignment where targetObjective.id = :objectiveId") - List findByObjectiveAlignmentId(@Param("objectiveId") Long objectiveId); + List findByObjectiveAlignmentId(@Param("objectiveId") + Long objectiveId); } diff --git a/backend/src/main/java/ch/puzzle/okr/repository/AlignmentSelectionRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/AlignmentSelectionRepository.java index 50896b44f3..188c3377e3 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/AlignmentSelectionRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/AlignmentSelectionRepository.java @@ -2,14 +2,14 @@ import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.models.alignment.AlignmentSelectionId; +import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import java.util.List; - public interface AlignmentSelectionRepository extends ReadOnlyRepository { @Query(value = "from AlignmentSelection where quarterId = :quarter_id and teamId != :ignoredTeamId") - List getAlignmentSelectionByQuarterIdAndTeamIdNot(@Param("quarter_id") Long quarterId, - @Param("ignoredTeamId") Long ignoredTeamId); + List getAlignmentSelectionByQuarterIdAndTeamIdNot(@Param("quarter_id") + Long quarterId, @Param("ignoredTeamId") + Long ignoredTeamId); } diff --git a/backend/src/main/java/ch/puzzle/okr/repository/CheckInRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/CheckInRepository.java index 74622032a2..3a17fecf0e 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/CheckInRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/CheckInRepository.java @@ -1,9 +1,8 @@ package ch.puzzle.okr.repository; import ch.puzzle.okr.models.checkin.CheckIn; -import org.springframework.data.repository.CrudRepository; - import java.util.List; +import org.springframework.data.repository.CrudRepository; public interface CheckInRepository extends CrudRepository { List findCheckInsByKeyResultIdOrderByCreatedOnDesc(Long keyResultId); diff --git a/backend/src/main/java/ch/puzzle/okr/repository/KeyResultRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/KeyResultRepository.java index b5aa92dbac..a48afe82e1 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/KeyResultRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/KeyResultRepository.java @@ -1,9 +1,8 @@ package ch.puzzle.okr.repository; import ch.puzzle.okr.models.keyresult.KeyResult; -import org.springframework.data.repository.CrudRepository; - import java.util.List; +import org.springframework.data.repository.CrudRepository; public interface KeyResultRepository extends CrudRepository { List findByObjectiveId(Long objectiveId); diff --git a/backend/src/main/java/ch/puzzle/okr/repository/ObjectiveRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/ObjectiveRepository.java index 009b34ac96..95f2fe0dbf 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/ObjectiveRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/ObjectiveRepository.java @@ -3,11 +3,10 @@ import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.models.Team; +import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; -import java.util.List; - @Repository public interface ObjectiveRepository extends CrudRepository { diff --git a/backend/src/main/java/ch/puzzle/okr/repository/QuarterRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/QuarterRepository.java index a742c2d236..f687ee343d 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/QuarterRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/QuarterRepository.java @@ -1,14 +1,13 @@ package ch.puzzle.okr.repository; import ch.puzzle.okr.models.Quarter; +import java.time.LocalDate; +import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import java.time.LocalDate; -import java.util.List; - @Repository public interface QuarterRepository extends CrudRepository { @@ -18,5 +17,6 @@ public interface QuarterRepository extends CrudRepository { Quarter findByLabel(String label); @Query(value = "Select q from Quarter q where q.startDate <= :date and q.endDate >= :date") - Quarter getActiveQuarter(@Param("date") LocalDate date); + Quarter getActiveQuarter(@Param("date") + LocalDate date); } diff --git a/backend/src/main/java/ch/puzzle/okr/repository/TeamRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/TeamRepository.java index 14e48978ed..f4aaf40bb9 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/TeamRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/TeamRepository.java @@ -1,9 +1,8 @@ package ch.puzzle.okr.repository; import ch.puzzle.okr.models.Team; -import org.springframework.data.repository.CrudRepository; - import java.util.List; +import org.springframework.data.repository.CrudRepository; public interface TeamRepository extends CrudRepository { diff --git a/backend/src/main/java/ch/puzzle/okr/repository/UserRepository.java b/backend/src/main/java/ch/puzzle/okr/repository/UserRepository.java index 2bf83e1f1d..addae09197 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/UserRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/UserRepository.java @@ -1,10 +1,9 @@ package ch.puzzle.okr.repository; import ch.puzzle.okr.models.User; -import org.springframework.data.repository.CrudRepository; - import java.util.List; import java.util.Optional; +import org.springframework.data.repository.CrudRepository; public interface UserRepository extends CrudRepository { Optional findByEmail(String email); diff --git a/backend/src/main/java/ch/puzzle/okr/security/JwtHelper.java b/backend/src/main/java/ch/puzzle/okr/security/JwtHelper.java index fe15d284f1..0799245168 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/JwtHelper.java +++ b/backend/src/main/java/ch/puzzle/okr/security/JwtHelper.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.security; +import static ch.puzzle.okr.Constants.USER; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; @@ -8,28 +11,24 @@ import ch.puzzle.okr.security.helper.TokenHelper; import com.nimbusds.jwt.JWTClaimsSet; import jakarta.persistence.EntityNotFoundException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.oauth2.jwt.Jwt; -import org.springframework.stereotype.Component; - import java.text.MessageFormat; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; - -import static ch.puzzle.okr.Constants.USER; -import static org.springframework.http.HttpStatus.BAD_REQUEST; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.stereotype.Component; @Component public class JwtHelper { public static final String CLAIM_TENANT = "tenant"; public static final String CLAIM_ISS = "iss"; public static final String ERROR_MESSAGE = "Missing `" + CLAIM_TENANT + "` and '" + CLAIM_ISS - + "' claims in JWT token!"; + + "' claims in JWT token!"; private static final Logger logger = LoggerFactory.getLogger(JwtHelper.class); @@ -38,10 +37,10 @@ public class JwtHelper { private final String lastname; private final String email; - public JwtHelper(TenantConfigProvider tenantConfigProvider, - @Value("${okr.jwt.claim.firstname}") final String tokenClaimsKeyFirstname, - @Value("${okr.jwt.claim.lastname}") final String tokenClaimsKeyLastname, - @Value("${okr.jwt.claim.email}") final String tokenClaimsKeyEmail) { + public JwtHelper(TenantConfigProvider tenantConfigProvider, @Value("${okr.jwt.claim.firstname}") + final String tokenClaimsKeyFirstname, @Value("${okr.jwt.claim.lastname}") + final String tokenClaimsKeyLastname, @Value("${okr.jwt.claim.email}") + final String tokenClaimsKeyEmail) { this.tenantConfigProvider = tenantConfigProvider; this.firstname = tokenClaimsKeyFirstname; this.lastname = tokenClaimsKeyLastname; @@ -54,10 +53,10 @@ public User getUserFromJwt(Jwt token) { try { return User.Builder.builder() // - .withFirstname(claims.get(firstname).toString()) // - .withLastname(claims.get(lastname).toString()) // - .withEmail(claims.get(email).toString()) // - .build(); + .withFirstname(claims.get(firstname).toString()) // + .withLastname(claims.get(lastname).toString()) // + .withEmail(claims.get(email).toString()) // + .build(); } catch (Exception e) { logger.warn("can not convert user from claims {}", claims); throw new OkrResponseStatusException(BAD_REQUEST, ErrorKey.CONVERT_TOKEN, USER); @@ -67,51 +66,53 @@ public User getUserFromJwt(Jwt token) { public String getTenantFromToken(Jwt token) { TokenHelper helper = new TokenHelper(); List>> getTenantFromTokenFunctions = Arrays.asList( // - helper::getTenantFromTokenUsingClaimIss, // - helper::getTenantFromTokenUsingClaimTenant // + helper::getTenantFromTokenUsingClaimIss, // + helper::getTenantFromTokenUsingClaimTenant // ); return getFirstMatchingTenantUsingListOfHelperFunctions(token, getTenantFromTokenFunctions); } private String getFirstMatchingTenantUsingListOfHelperFunctions(Jwt token, - List>> getTenantFunctions) { + List>> getTenantFunctions) { return getTenantFunctions.stream() // - .map(func -> func.apply(token)) // - .filter(Optional::isPresent) // - .map(Optional::get) // - .map(this::getMatchingTenantFromConfigOrThrow) // - .findFirst() // - .orElseThrow(() -> new RuntimeException(ERROR_MESSAGE)); + .map(func -> func.apply(token)) // + .filter(Optional::isPresent) // + .map(Optional::get) // + .map(this::getMatchingTenantFromConfigOrThrow) // + .findFirst() // + .orElseThrow(() -> new RuntimeException(ERROR_MESSAGE)); } public String getTenantFromJWTClaimsSet(JWTClaimsSet claimSet) { ClaimHelper helper = new ClaimHelper(); List>> getTenantFromClaimsSetFunctions = Arrays.asList( // - helper::getTenantFromClaimsSetUsingClaimIss, // - helper::getTenantFromClaimsSetUsingClaimTenant // + helper::getTenantFromClaimsSetUsingClaimIss, // + helper::getTenantFromClaimsSetUsingClaimTenant // ); return getFirstMatchingTenantUsingListOfHelperFunctions(claimSet, getTenantFromClaimsSetFunctions); } private String getFirstMatchingTenantUsingListOfHelperFunctions(JWTClaimsSet claimSet, - List>> getTenantFunctions) { + List>> getTenantFunctions) { return getTenantFunctions.stream() // - .map(func -> func.apply(claimSet)) // - .filter(Optional::isPresent) // - .map(Optional::get) // - .map(this::getMatchingTenantFromConfigOrThrow).findFirst() // - .orElseThrow(() -> new RuntimeException(ERROR_MESSAGE)); + .map(func -> func.apply(claimSet)) // + .filter(Optional::isPresent) // + .map(Optional::get) // + .map(this::getMatchingTenantFromConfigOrThrow) + .findFirst() // + .orElseThrow(() -> new RuntimeException(ERROR_MESSAGE)); } private String getMatchingTenantFromConfigOrThrow(String tenant) { // Ensure we return only tenants for realms which really exist return this.tenantConfigProvider.getTenantConfigById(tenant) - .orElseThrow(() -> new EntityNotFoundException(MessageFormat.format("Cannot find tenant {0}", tenant))) - .tenantId(); + .orElseThrow(() -> new EntityNotFoundException(MessageFormat.format("Cannot find tenant {0}", + tenant))) + .tenantId(); } } \ No newline at end of file diff --git a/backend/src/main/java/ch/puzzle/okr/security/TenantJWSKeySelector.java b/backend/src/main/java/ch/puzzle/okr/security/TenantJWSKeySelector.java index f900296174..1c53f9b0f7 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/TenantJWSKeySelector.java +++ b/backend/src/main/java/ch/puzzle/okr/security/TenantJWSKeySelector.java @@ -8,13 +8,12 @@ import com.nimbusds.jose.proc.SecurityContext; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.proc.JWTClaimsSetAwareJWSKeySelector; -import org.springframework.stereotype.Component; - import java.net.URL; import java.security.Key; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.springframework.stereotype.Component; @Component public class TenantJWSKeySelector implements JWTClaimsSetAwareJWSKeySelector { @@ -31,10 +30,11 @@ public TenantJWSKeySelector(final TenantConfigProvider tenantConfigProvider, Jwt @Override public List selectKeys(JWSHeader jwsHeader, JWTClaimsSet jwtClaimsSet, - SecurityContext securityContext) throws KeySourceException { + SecurityContext securityContext) + throws KeySourceException { return this.selectors.computeIfAbsent(toTenant(jwtClaimsSet), this::fromTenant) // - .selectJWSKeys(jwsHeader, securityContext); + .selectJWSKeys(jwsHeader, securityContext); } private String toTenant(JWTClaimsSet claimSet) { @@ -43,8 +43,8 @@ private String toTenant(JWTClaimsSet claimSet) { private JWSKeySelector fromTenant(String tenantId) { return this.tenantConfigProvider.getJwkSetUri(tenantId)// - .map(this::fromUri) // - .orElseThrow(() -> new IllegalArgumentException("unknown tenant")); + .map(this::fromUri) // + .orElseThrow(() -> new IllegalArgumentException("unknown tenant")); } JWSKeySelector fromUri(String uri) { diff --git a/backend/src/main/java/ch/puzzle/okr/security/TenantJwtIssuerValidator.java b/backend/src/main/java/ch/puzzle/okr/security/TenantJwtIssuerValidator.java index 1dadd96b3f..50c9a62298 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/TenantJwtIssuerValidator.java +++ b/backend/src/main/java/ch/puzzle/okr/security/TenantJwtIssuerValidator.java @@ -1,15 +1,14 @@ package ch.puzzle.okr.security; import ch.puzzle.okr.multitenancy.TenantConfigProvider; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtIssuerValidator; import org.springframework.stereotype.Component; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - @Component public class TenantJwtIssuerValidator implements OAuth2TokenValidator { private final TenantConfigProvider tenantConfigProvider; @@ -32,9 +31,9 @@ public OAuth2TokenValidatorResult validate(Jwt token) { private JwtIssuerValidator createValidatorForTenant(String tenant) { return this.tenantConfigProvider.getTenantConfigById(tenant) // - .map(TenantConfigProvider.TenantConfig::issuerUrl) // - .map(this::createValidator) // - .orElseThrow(() -> new IllegalArgumentException("unknown tenant")); + .map(TenantConfigProvider.TenantConfig::issuerUrl) // + .map(this::createValidator) // + .orElseThrow(() -> new IllegalArgumentException("unknown tenant")); } JwtIssuerValidator createValidator(String issuer) { diff --git a/backend/src/main/java/ch/puzzle/okr/security/helper/ClaimHelper.java b/backend/src/main/java/ch/puzzle/okr/security/helper/ClaimHelper.java index 9ceb7a4034..b7fb0b88de 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/helper/ClaimHelper.java +++ b/backend/src/main/java/ch/puzzle/okr/security/helper/ClaimHelper.java @@ -1,15 +1,14 @@ package ch.puzzle.okr.security.helper; -import com.nimbusds.jwt.JWTClaimsSet; - -import java.text.ParseException; -import java.util.Optional; - import static ch.puzzle.okr.security.JwtHelper.CLAIM_ISS; import static ch.puzzle.okr.security.JwtHelper.CLAIM_TENANT; import static ch.puzzle.okr.security.helper.JwtStatusLogger.logStatus; import static ch.puzzle.okr.security.helper.UrlHelper.extractTenantFromIssUrl; +import com.nimbusds.jwt.JWTClaimsSet; +import java.text.ParseException; +import java.util.Optional; + public class ClaimHelper { public Optional getTenantFromClaimsSetUsingClaimTenant(JWTClaimsSet claimSet) { diff --git a/backend/src/main/java/ch/puzzle/okr/security/helper/JwtStatusLogger.java b/backend/src/main/java/ch/puzzle/okr/security/helper/JwtStatusLogger.java index ca5d678458..5812570e8f 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/helper/JwtStatusLogger.java +++ b/backend/src/main/java/ch/puzzle/okr/security/helper/JwtStatusLogger.java @@ -1,10 +1,9 @@ package ch.puzzle.okr.security.helper; +import java.text.ParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.text.ParseException; - public class JwtStatusLogger { private static final Logger logger = LoggerFactory.getLogger(ClaimHelper.class); @@ -15,17 +14,24 @@ public static void logStatus(String claim, Object context, String result) { public static void logStatus(String claim, Object context, boolean isOk) { if (isOk) { - logger.info("Tenant: get claim '{}' from {}{}", claim, context.getClass().getSimpleName(), - statusToSymbol(isOk)); + logger.info("Tenant: get claim '{}' from {}{}", + claim, + context.getClass().getSimpleName(), + statusToSymbol(isOk)); } else { - logger.warn("Tenant: get claim '{}' from {}{}", claim, context.getClass().getSimpleName(), - statusToSymbol(isOk)); + logger.warn("Tenant: get claim '{}' from {}{}", + claim, + context.getClass().getSimpleName(), + statusToSymbol(isOk)); } } public static void logStatus(String claim, Object context, ParseException e) { - logger.warn("Tenant: get claim '{}' from {}{}", claim, context.getClass().getSimpleName(), - statusToSymbol(false), e); + logger.warn("Tenant: get claim '{}' from {}{}", + claim, + context.getClass().getSimpleName(), + statusToSymbol(false), + e); } private static String statusToSymbol(boolean isOk) { diff --git a/backend/src/main/java/ch/puzzle/okr/security/helper/TokenHelper.java b/backend/src/main/java/ch/puzzle/okr/security/helper/TokenHelper.java index 513241cb06..8bdab64f86 100644 --- a/backend/src/main/java/ch/puzzle/okr/security/helper/TokenHelper.java +++ b/backend/src/main/java/ch/puzzle/okr/security/helper/TokenHelper.java @@ -1,14 +1,13 @@ package ch.puzzle.okr.security.helper; -import org.springframework.security.oauth2.jwt.Jwt; - -import java.util.Optional; - import static ch.puzzle.okr.security.JwtHelper.CLAIM_ISS; import static ch.puzzle.okr.security.JwtHelper.CLAIM_TENANT; import static ch.puzzle.okr.security.helper.JwtStatusLogger.logStatus; import static ch.puzzle.okr.security.helper.UrlHelper.extractTenantFromIssUrl; +import java.util.Optional; +import org.springframework.security.oauth2.jwt.Jwt; + public class TokenHelper { public Optional getTenantFromTokenUsingClaimTenant(Jwt token) { diff --git a/backend/src/main/java/ch/puzzle/okr/service/CacheService.java b/backend/src/main/java/ch/puzzle/okr/service/CacheService.java index de907468c1..5a315116fd 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/CacheService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/CacheService.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.service; +import static ch.puzzle.okr.SpringCachingConfig.AUTHORIZATION_USER_CACHE; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.CacheManager; @@ -8,8 +10,6 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import static ch.puzzle.okr.SpringCachingConfig.AUTHORIZATION_USER_CACHE; - @EnableScheduling @Service public class CacheService { diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/ActionAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/ActionAuthorizationService.java index a6a54a4de4..937e5a893b 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/ActionAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/ActionAuthorizationService.java @@ -4,9 +4,8 @@ import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.service.business.ActionBusinessService; -import org.springframework.stereotype.Service; - import java.util.List; +import org.springframework.stereotype.Service; @Service public class ActionAuthorizationService { @@ -15,7 +14,7 @@ public class ActionAuthorizationService { private final AuthorizationService authorizationService; public ActionAuthorizationService(ActionBusinessService actionBusinessService, - AuthorizationService authorizationService) { + AuthorizationService authorizationService) { this.actionBusinessService = actionBusinessService; this.authorizationService = authorizationService; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationService.java index fc1213b565..f12e85af4a 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationService.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.SpringCachingConfig.AUTHORIZATION_USER_CACHE; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.multitenancy.TenantConfigProvider; @@ -9,8 +11,6 @@ import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; -import static ch.puzzle.okr.SpringCachingConfig.AUTHORIZATION_USER_CACHE; - @Service public class AuthorizationRegistrationService { @@ -20,7 +20,7 @@ public class AuthorizationRegistrationService { private final UserUpdateHelper helper = new UserUpdateHelper(); public AuthorizationRegistrationService(UserBusinessService userBusinessService, - TenantConfigProvider tenantConfigProvider) { + TenantConfigProvider tenantConfigProvider) { this.userBusinessService = userBusinessService; this.tenantConfigProvider = tenantConfigProvider; } @@ -41,9 +41,8 @@ private User setFirstLastNameFromToken(User userFromDB, User userFromToken) { // okr champion is set in application properties private User setOkrChampionFromProperties(User user) { - TenantConfigProvider.TenantConfig tenantConfig = this.tenantConfigProvider - .getTenantConfigById(TenantContext.getCurrentTenant()) - .orElseThrow(() -> new EntityNotFoundException("Cannot find tenant")); + TenantConfigProvider.TenantConfig tenantConfig = this.tenantConfigProvider.getTenantConfigById(TenantContext.getCurrentTenant()) + .orElseThrow(() -> new EntityNotFoundException("Cannot find tenant")); return helper.setOkrChampionFromProperties(user, tenantConfig); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationService.java index 3ddde9734b..92e5bb10e8 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationService.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.Constants.*; +import static ch.puzzle.okr.ErrorKey.*; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.Objective; @@ -17,9 +20,6 @@ import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.stereotype.Service; -import static ch.puzzle.okr.Constants.*; -import static ch.puzzle.okr.ErrorKey.*; - @Service public class AuthorizationService { @@ -29,8 +29,8 @@ public class AuthorizationService { private final JwtHelper jwtHelper; public AuthorizationService(AuthorizationRegistrationService authorizationRegistrationService, - ObjectivePersistenceService objectivePersistenceService, ActionPersistenceService actionPersistenceService, - JwtHelper jwtHelper) { + ObjectivePersistenceService objectivePersistenceService, + ActionPersistenceService actionPersistenceService, JwtHelper jwtHelper) { this.authorizationRegistrationService = authorizationRegistrationService; this.actionPersistenceService = actionPersistenceService; this.objectivePersistenceService = objectivePersistenceService; @@ -45,7 +45,7 @@ public static boolean hasRoleWriteForTeam(AuthorizationUser authorizationUser, L } public static void checkRoleWriteAndReadAll(AuthorizationUser user, - OkrResponseStatusException notAuthorizedException) { + OkrResponseStatusException notAuthorizedException) { if (hasRoleWriteAndReadAll(user)) { return; } @@ -67,40 +67,52 @@ public AuthorizationUser updateOrAddAuthorizationUser() { } public void hasRoleReadByObjectiveId(Long objectiveId, AuthorizationUser authorizationUser) { - objectivePersistenceService.findObjectiveById(objectiveId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, OBJECTIVE)); + objectivePersistenceService.findObjectiveById(objectiveId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, OBJECTIVE)); } public void hasRoleReadByKeyResultId(Long keyResultId, AuthorizationUser authorizationUser) { - objectivePersistenceService.findObjectiveByKeyResultId(keyResultId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, KEY_RESULT)); + objectivePersistenceService.findObjectiveByKeyResultId(keyResultId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + KEY_RESULT)); } public void hasRoleReadByCheckInId(Long checkInId, AuthorizationUser authorizationUser) { - objectivePersistenceService.findObjectiveByCheckInId(checkInId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, CHECK_IN)); + objectivePersistenceService.findObjectiveByCheckInId(checkInId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + CHECK_IN)); } public void hasRoleCreateOrUpdate(Objective objective, AuthorizationUser authorizationUser) { - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, OBJECTIVE)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, OBJECTIVE)); } public void hasRoleCreateOrUpdate(KeyResult keyResult, AuthorizationUser authorizationUser) { Objective objective = objectivePersistenceService.findObjectiveById(keyResult.getObjective().getId(), - authorizationUser, OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, KEY_RESULT)); + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + KEY_RESULT)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, KEY_RESULT)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, KEY_RESULT)); } public void hasRoleCreateOrUpdate(CheckIn checkIn, AuthorizationUser authorizationUser) { Objective objective = objectivePersistenceService.findObjectiveByKeyResultId(checkIn.getKeyResult().getId(), - authorizationUser, OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, CHECK_IN)); + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + CHECK_IN)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, CHECK_IN)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, CHECK_IN)); } public boolean hasRoleWriteForTeam(Objective objective, AuthorizationUser authorizationUser) { @@ -109,58 +121,75 @@ public boolean hasRoleWriteForTeam(Objective objective, AuthorizationUser author public boolean hasRoleWriteForTeam(KeyResult keyResult, AuthorizationUser authorizationUser) { Objective objective = objectivePersistenceService.findObjectiveById(keyResult.getObjective().getId(), - authorizationUser, OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, KEY_RESULT)); + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + KEY_RESULT)); return hasRoleWriteForTeam(authorizationUser, objective.getTeam()); } public boolean hasRoleWriteForTeam(CheckIn checkIn, AuthorizationUser authorizationUser) { Objective objective = objectivePersistenceService.findObjectiveByKeyResultId(checkIn.getKeyResult().getId(), - authorizationUser, OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, CHECK_IN)); + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + CHECK_IN)); return hasRoleWriteForTeam(authorizationUser, objective.getTeam()); } public void hasRoleCreateOrUpdateByObjectiveId(Long objectiveId, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveById(objectiveId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, OBJECTIVE)); + Objective objective = objectivePersistenceService.findObjectiveById(objectiveId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + OBJECTIVE)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, OBJECTIVE)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_WRITE, OBJECTIVE)); } public void hasRoleDeleteByObjectiveId(Long objectiveId, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveById(objectiveId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, OBJECTIVE)); + Objective objective = objectivePersistenceService.findObjectiveById(objectiveId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + OBJECTIVE)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, OBJECTIVE)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, OBJECTIVE)); } public void hasRoleDeleteByKeyResultId(Long keyResultId, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveByKeyResultId(keyResultId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, KEY_RESULT)); + Objective objective = objectivePersistenceService.findObjectiveByKeyResultId(keyResultId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + KEY_RESULT)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, KEY_RESULT)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, KEY_RESULT)); } public void hasRoleDeleteByActionId(Long actionId, AuthorizationUser authorizationUser) { Action action = actionPersistenceService.findById(actionId); - hasRoleWriteForTeam(authorizationUser, action.getKeyResult().getObjective().getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, ACTION)); + hasRoleWriteForTeam(authorizationUser, + action.getKeyResult().getObjective().getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, ACTION)); } public void hasRoleDeleteByCheckInId(Long checkInId, AuthorizationUser authorizationUser) { - Objective objective = objectivePersistenceService.findObjectiveByCheckInId(checkInId, authorizationUser, - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, CHECK_IN)); + Objective objective = objectivePersistenceService.findObjectiveByCheckInId(checkInId, + authorizationUser, + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, + CHECK_IN)); - hasRoleWriteForTeam(authorizationUser, objective.getTeam(), - OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, CHECK_IN)); + hasRoleWriteForTeam(authorizationUser, + objective.getTeam(), + OkrResponseStatusException.of(NOT_AUTHORIZED_TO_DELETE, CHECK_IN)); } private void hasRoleWriteForTeam(AuthorizationUser authorizationUser, Team team, - OkrResponseStatusException notAuthorizedException) { + OkrResponseStatusException notAuthorizedException) { if (hasRoleWriteForTeam(authorizationUser, team)) { return; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationServiceBase.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationServiceBase.java index 51cd7ab046..92766a80fc 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationServiceBase.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/AuthorizationServiceBase.java @@ -17,7 +17,7 @@ public abstract class AuthorizationServiceBase businessService, - AuthorizationService authorizationService) { + AuthorizationService authorizationService) { this.businessService = businessService; this.authorizationService = authorizationService; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationService.java index bb6196d6f6..04c8f6f64e 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationService.java @@ -9,7 +9,7 @@ public class CheckInAuthorizationService extends AuthorizationServiceBase { public CheckInAuthorizationService(CheckInBusinessService checkInBusinessService, - AuthorizationService authorizationService) { + AuthorizationService authorizationService) { super(checkInBusinessService, authorizationService); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationService.java index a59467a3ca..3ea9524532 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationService.java @@ -11,7 +11,7 @@ public class CompletedAuthorizationService { private final AuthorizationService authorizationService; public CompletedAuthorizationService(CompletedBusinessService completedBusinessService, - AuthorizationService authorizationService) { + AuthorizationService authorizationService) { this.completedBusinessService = completedBusinessService; this.authorizationService = authorizationService; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationService.java index a2197e89b5..a280f33bef 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationService.java @@ -1,23 +1,22 @@ package ch.puzzle.okr.service.authorization; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultWithActionList; import ch.puzzle.okr.service.business.KeyResultBusinessService; +import java.util.List; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static org.springframework.http.HttpStatus.BAD_REQUEST; - @Service public class KeyResultAuthorizationService extends AuthorizationServiceBase { public KeyResultAuthorizationService(KeyResultBusinessService keyResultBusinessService, - AuthorizationService authorizationService) { + AuthorizationService authorizationService) { super(keyResultBusinessService, authorizationService); } @@ -52,7 +51,8 @@ public List getAllCheckInsByKeyResult(Long keyResultId) { @Override public KeyResult updateEntity(Long id, KeyResult keyResult) { throw new ResponseStatusException(BAD_REQUEST, - "unsupported method in class " + getClass().getSimpleName() + ", use updateEntities() instead"); + "unsupported method in class " + getClass().getSimpleName() + + ", use updateEntities() instead"); } public KeyResultWithActionList updateEntities(Long id, KeyResult entity, List actionList) { diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationService.java index 22dd21de0c..55aadc584d 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationService.java @@ -9,7 +9,7 @@ public class ObjectiveAuthorizationService extends AuthorizationServiceBase { public ObjectiveAuthorizationService(ObjectiveBusinessService objectiveBusinessService, - AuthorizationService authorizationService) { + AuthorizationService authorizationService) { super(objectiveBusinessService, authorizationService); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationService.java index 3f4487b31b..a61ca35d64 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationService.java @@ -1,16 +1,15 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.service.business.OverviewBusinessService; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - import java.util.HashMap; import java.util.List; import java.util.Map; - -import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; @Service public class OverviewAuthorizationService { @@ -19,15 +18,17 @@ public class OverviewAuthorizationService { private final AuthorizationService authorizationService; public OverviewAuthorizationService(OverviewBusinessService overviewBusinessService, - AuthorizationService authorizationService) { + AuthorizationService authorizationService) { this.overviewBusinessService = overviewBusinessService; this.authorizationService = authorizationService; } public List getFilteredOverview(Long quarterId, List teamIds, String objectiveQuery) { AuthorizationUser authorizationUser = authorizationService.updateOrAddAuthorizationUser(); - List overviews = overviewBusinessService.getFilteredOverview(quarterId, teamIds, objectiveQuery, - authorizationUser); + List overviews = overviewBusinessService.getFilteredOverview(quarterId, + teamIds, + objectiveQuery, + authorizationUser); setRoleCreateOrUpdateTeam(overviews, authorizationUser); return overviews; } @@ -40,7 +41,7 @@ private void setRoleCreateOrUpdateTeam(List overviews, AuthorizationUs } private void setRoleCreateOrUpdateTeam(Overview overview, AuthorizationUser authorizationUser, - Map teamAccess) { + Map teamAccess) { if (hasOverviewTeamIdAndObjectiveId(overview)) { Long teamId = overview.getOverviewId().getTeamId(); teamAccess.putIfAbsent(teamId, isWriteable(authorizationUser, overview)); @@ -50,7 +51,7 @@ private void setRoleCreateOrUpdateTeam(Overview overview, AuthorizationUser auth private boolean hasOverviewTeamIdAndObjectiveId(Overview overview) { return overview.getOverviewId() != null && overview.getOverviewId().getObjectiveId() != null - && overview.getOverviewId().getTeamId() != null; + && overview.getOverviewId().getTeamId() != null; } public boolean hasWriteAllAccess() { diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/TeamAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/TeamAuthorizationService.java index 33e2cecd33..0909821d35 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/TeamAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/TeamAuthorizationService.java @@ -1,16 +1,15 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.Constants.TEAM; +import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.TeamBusinessService; -import org.springframework.stereotype.Service; - import java.util.List; - -import static ch.puzzle.okr.Constants.TEAM; -import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; +import org.springframework.stereotype.Service; @Service public class TeamAuthorizationService { @@ -18,7 +17,7 @@ public class TeamAuthorizationService { private final AuthorizationService authorizationService; public TeamAuthorizationService(TeamBusinessService teamBusinessService, - AuthorizationService authorizationService) { + AuthorizationService authorizationService) { this.teamBusinessService = teamBusinessService; this.authorizationService = authorizationService; } diff --git a/backend/src/main/java/ch/puzzle/okr/service/authorization/UserAuthorizationService.java b/backend/src/main/java/ch/puzzle/okr/service/authorization/UserAuthorizationService.java index fab3dba8fe..d3bec7f2e1 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/authorization/UserAuthorizationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/authorization/UserAuthorizationService.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.Constants.USER; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.dto.userOkrData.UserOkrDataDto; import ch.puzzle.okr.exception.OkrResponseStatusException; @@ -9,11 +11,8 @@ import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.service.business.KeyResultBusinessService; import ch.puzzle.okr.service.business.UserBusinessService; -import org.springframework.stereotype.Service; - import java.util.List; - -import static ch.puzzle.okr.Constants.USER; +import org.springframework.stereotype.Service; @Service public class UserAuthorizationService { @@ -24,7 +23,8 @@ public class UserAuthorizationService { private final KeyResultBusinessService keyResultBusinessService; public UserAuthorizationService(UserBusinessService userBusinessService, AuthorizationService authorizationService, - TeamAuthorizationService teamAuthorizationService, KeyResultBusinessService keyResultBusinessService) { + TeamAuthorizationService teamAuthorizationService, + KeyResultBusinessService keyResultBusinessService) { this.userBusinessService = userBusinessService; this.authorizationService = authorizationService; this.teamAuthorizationService = teamAuthorizationService; @@ -55,13 +55,15 @@ public User getById(long id) { public User setIsOkrChampion(long id, boolean isOkrChampion) { var user = userBusinessService.getUserById(id); AuthorizationService.checkRoleWriteAndReadAll(authorizationService.updateOrAddAuthorizationUser(), - OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_WRITE, USER)); + OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_WRITE, + USER)); return userBusinessService.setIsOkrChampion(user, isOkrChampion); } public List createUsers(List userList) { AuthorizationService.checkRoleWriteAndReadAll(authorizationService.updateOrAddAuthorizationUser(), - OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_WRITE, USER)); + OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_WRITE, + USER)); return userBusinessService.createUsers(userList); } @@ -72,7 +74,8 @@ public boolean isUserMemberOfTeams(long id) { public void deleteEntityById(long id) { AuthorizationService.checkRoleWriteAndReadAll(authorizationService.updateOrAddAuthorizationUser(), - OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_DELETE, USER)); + OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_DELETE, + USER)); userBusinessService.deleteEntityById(id); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/ActionBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/ActionBusinessService.java index 9a684f6a54..7d1d1a9188 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/ActionBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/ActionBusinessService.java @@ -4,10 +4,9 @@ import ch.puzzle.okr.service.persistence.ActionPersistenceService; import ch.puzzle.okr.service.validation.ActionValidationService; import jakarta.transaction.Transactional; -import org.springframework.stereotype.Service; - import java.util.ArrayList; import java.util.List; +import org.springframework.stereotype.Service; @Service public class ActionBusinessService { diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessService.java index 8e6feefed1..a65135aaef 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessService.java @@ -2,22 +2,20 @@ import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.service.persistence.AlignmentSelectionPersistenceService; -import org.springframework.stereotype.Service; - import java.util.List; +import org.springframework.stereotype.Service; @Service public class AlignmentSelectionBusinessService { private final AlignmentSelectionPersistenceService alignmentSelectionPersistenceService; - public AlignmentSelectionBusinessService( - AlignmentSelectionPersistenceService alignmentSelectionPersistenceService) { + public AlignmentSelectionBusinessService(AlignmentSelectionPersistenceService alignmentSelectionPersistenceService) { this.alignmentSelectionPersistenceService = alignmentSelectionPersistenceService; } public List getAlignmentSelectionByQuarterIdAndTeamIdNot(Long quarterId, Long ignoredTeamId) { return alignmentSelectionPersistenceService.getAlignmentSelectionByQuarterIdAndTeamIdNot(quarterId, - ignoredTeamId); + ignoredTeamId); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/CheckInBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/CheckInBusinessService.java index db6e892cb0..ad9456d175 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/CheckInBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/CheckInBusinessService.java @@ -5,10 +5,9 @@ import ch.puzzle.okr.service.persistence.CheckInPersistenceService; import ch.puzzle.okr.service.validation.CheckInValidationService; import jakarta.transaction.Transactional; -import org.springframework.stereotype.Service; - import java.time.LocalDateTime; import java.util.List; +import org.springframework.stereotype.Service; @Service public class CheckInBusinessService implements BusinessServiceInterface { @@ -16,7 +15,7 @@ public class CheckInBusinessService implements BusinessServiceInterface { @@ -26,8 +25,8 @@ public class KeyResultBusinessService implements BusinessServiceInterface acti public void deleteEntityById(Long id) { validator.validateOnDelete(id); checkInBusinessService.getCheckInsByKeyResultId(id) - .forEach(checkIn -> checkInBusinessService.deleteEntityById(checkIn.getId())); + .forEach(checkIn -> checkInBusinessService.deleteEntityById(checkIn.getId())); actionBusinessService.getActionsByKeyResultId(id) - .forEach(action -> actionBusinessService.deleteEntityById(action.getId())); + .forEach(action -> actionBusinessService.deleteEntityById(action.getId())); keyResultPersistenceService.deleteById(id); } @@ -120,7 +119,7 @@ public boolean hasKeyResultAnyCheckIns(Long id) { public boolean isImUsed(Long id, KeyResult keyResult) { return hasKeyResultAnyCheckIns(id) - && !keyResultPersistenceService.findById(id).getKeyResultType().equals(keyResult.getKeyResultType()); + && !keyResultPersistenceService.findById(id).getKeyResultType().equals(keyResult.getKeyResultType()); } private boolean isKeyResultTypeChangeable(Long id) { diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/ObjectiveBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/ObjectiveBusinessService.java index 2dc987df98..daa7c5cb3b 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/ObjectiveBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/ObjectiveBusinessService.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.service.business; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; + import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.keyresult.KeyResult; @@ -8,18 +11,14 @@ import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.service.validation.ObjectiveValidationService; import jakarta.transaction.Transactional; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Objects; - -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; - @Service public class ObjectiveBusinessService implements BusinessServiceInterface { private final ObjectivePersistenceService objectivePersistenceService; @@ -29,9 +28,10 @@ public class ObjectiveBusinessService implements BusinessServiceInterface keyResultBusinessService.hasKeyResultAnyCheckIns(kr.getId())); + return keyResultBusinessService.getAllKeyResultsByObjective(savedObjective.getId()) + .stream() + .anyMatch(kr -> keyResultBusinessService.hasKeyResultAnyCheckIns(kr.getId())); } private static boolean hasQuarterChanged(Objective objective, Objective savedObjective) { @@ -101,8 +102,8 @@ public Objective createEntity(Objective objective, AuthorizationUser authorizati } /** - * Create a new Objective (with a new ID) and copy from a source Objective (identified by id) the KeyResults. The - * CheckIns are not copied. + * Create a new Objective (with a new ID) and copy from a source Objective + * (identified by id) the KeyResults. The CheckIns are not copied. * * @param id * ID of the source Objective @@ -123,7 +124,7 @@ public Objective duplicateObjective(Long id, Objective objective, AuthorizationU } private void duplicateKeyResult(AuthorizationUser authorizationUser, KeyResult keyResult, - Objective duplicatedObjective) { + Objective duplicatedObjective) { if (keyResult.getKeyResultType().equals(KEY_RESULT_TYPE_METRIC)) { KeyResult keyResultMetric = makeCopyOfKeyResultMetric(keyResult, duplicatedObjective); keyResultBusinessService.createEntity(keyResultMetric, authorizationUser); @@ -135,26 +136,26 @@ private void duplicateKeyResult(AuthorizationUser authorizationUser, KeyResult k private KeyResult makeCopyOfKeyResultMetric(KeyResult keyResult, Objective duplicatedObjective) { return KeyResultMetric.Builder.builder() // - .withObjective(duplicatedObjective) // - .withTitle(keyResult.getTitle()) // - .withDescription(keyResult.getDescription()) // - .withOwner(keyResult.getOwner()) // - .withUnit(((KeyResultMetric) keyResult).getUnit()) // - .withBaseline(0D) // - .withStretchGoal(1D) // - .build(); + .withObjective(duplicatedObjective) // + .withTitle(keyResult.getTitle()) // + .withDescription(keyResult.getDescription()) // + .withOwner(keyResult.getOwner()) // + .withUnit(((KeyResultMetric) keyResult).getUnit()) // + .withBaseline(0D) // + .withStretchGoal(1D) // + .build(); } private KeyResult makeCopyOfKeyResultOrdinal(KeyResult keyResult, Objective duplicatedObjective) { return KeyResultOrdinal.Builder.builder() // - .withObjective(duplicatedObjective) // - .withTitle(keyResult.getTitle()) // - .withDescription(keyResult.getDescription()) // - .withOwner(keyResult.getOwner()) // - .withCommitZone("-") // - .withTargetZone("-") // - .withStretchZone("-") // - .build(); + .withObjective(duplicatedObjective) // + .withTitle(keyResult.getTitle()) // + .withDescription(keyResult.getDescription()) // + .withOwner(keyResult.getOwner()) // + .withCommitZone("-") // + .withTargetZone("-") // + .withStretchZone("-") // + .build(); } @Transactional @@ -162,8 +163,8 @@ public void deleteEntityById(Long id) { validator.validateOnDelete(id); completedBusinessService.deleteCompletedByObjectiveId(id); keyResultBusinessService // - .getAllKeyResultsByObjective(id) // - .forEach(keyResult -> keyResultBusinessService.deleteEntityById(keyResult.getId())); + .getAllKeyResultsByObjective(id) // + .forEach(keyResult -> keyResultBusinessService.deleteEntityById(keyResult.getId())); objectivePersistenceService.deleteById(id); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/OverviewBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/OverviewBusinessService.java index da721f6c27..dc551c50ed 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/OverviewBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/OverviewBusinessService.java @@ -4,11 +4,10 @@ import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.service.persistence.OverviewPersistenceService; import ch.puzzle.okr.service.validation.OverviewValidationService; -import org.springframework.stereotype.Service; - import java.util.Comparator; import java.util.List; import java.util.Objects; +import org.springframework.stereotype.Service; @Service public class OverviewBusinessService { @@ -17,14 +16,14 @@ public class OverviewBusinessService { private final OverviewValidationService validator; public OverviewBusinessService(OverviewPersistenceService overviewPersistenceService, - QuarterBusinessService quarterBusinessService, OverviewValidationService validator) { + QuarterBusinessService quarterBusinessService, OverviewValidationService validator) { this.overviewPersistenceService = overviewPersistenceService; this.quarterBusinessService = quarterBusinessService; this.validator = validator; } public List getFilteredOverview(Long quarterId, List teamIds, String objectiveQuery, - AuthorizationUser authorizationUser) { + AuthorizationUser authorizationUser) { if (Objects.isNull(quarterId)) { quarterId = quarterBusinessService.getCurrentQuarter().getId(); } @@ -35,8 +34,10 @@ public List getFilteredOverview(Long quarterId, List teamIds, St return List.of(); } - List overviews = overviewPersistenceService.getFilteredOverview(quarterId, teamIds, objectiveQuery, - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(quarterId, + teamIds, + objectiveQuery, + authorizationUser); return sortOverview(overviews, authorizationUser); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/QuarterBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/QuarterBusinessService.java index 5f6c35053b..caee3814c8 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/QuarterBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/QuarterBusinessService.java @@ -1,8 +1,15 @@ package ch.puzzle.okr.service.business; +import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.service.persistence.QuarterPersistenceService; import ch.puzzle.okr.service.validation.QuarterValidationService; +import java.time.LocalDateTime; +import java.time.YearMonth; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -10,14 +17,6 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import java.time.LocalDateTime; -import java.time.YearMonth; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; - @Service public class QuarterBusinessService { private static final Logger logger = LoggerFactory.getLogger(QuarterBusinessService.class); @@ -32,7 +31,7 @@ public class QuarterBusinessService { private String quarterFormat; public QuarterBusinessService(QuarterPersistenceService quarterPersistenceService, - QuarterValidationService validator) { + QuarterValidationService validator) { this.quarterPersistenceService = quarterPersistenceService; this.validator = validator; } @@ -66,9 +65,10 @@ private String createQuarterLabel(YearMonth startOfQuarter, int quarter) { int yearStart = getStartOfBusinessYear(startOfQuarter, quarter); int yearEnd = yearStart + 1; - return StringUtils.replaceEach(quarterFormat, new String[] { "xxxx", "yyyy", "xx", "yy", "zz" }, - new String[] { String.valueOf(yearStart), String.valueOf(yearEnd), shortenYear(yearStart), - shortenYear(yearEnd), String.valueOf(quarter) }); + return StringUtils.replaceEach(quarterFormat, + new String[]{"xxxx", "yyyy", "xx", "yy", "zz"}, + new String[]{String.valueOf(yearStart), String.valueOf(yearEnd), + shortenYear(yearStart), shortenYear(yearEnd), String.valueOf(quarter)}); } private int getStartOfBusinessYear(YearMonth startOfQuarter, int quarter) { @@ -79,8 +79,11 @@ private int getStartOfBusinessYear(YearMonth startOfQuarter, int quarter) { private void generateQuarter(LocalDateTime start, String label) { YearMonth yearMonth = YearMonth.from(start); - Quarter quarter = Quarter.Builder.builder().withLabel(label).withStartDate(start.toLocalDate()) - .withEndDate(yearMonth.plusMonths(2).atEndOfMonth()).build(); + Quarter quarter = Quarter.Builder.builder() + .withLabel(label) + .withStartDate(start.toLocalDate()) + .withEndDate(yearMonth.plusMonths(2).atEndOfMonth()) + .build(); validator.validateOnGeneration(quarter); quarterPersistenceService.save(quarter); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/TeamBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/TeamBusinessService.java index f05a069673..8d703c439a 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/TeamBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/TeamBusinessService.java @@ -12,13 +12,12 @@ import ch.puzzle.okr.service.persistence.UserTeamPersistenceService; import ch.puzzle.okr.service.validation.TeamValidationService; import jakarta.transaction.Transactional; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; @Service public class TeamBusinessService { @@ -35,9 +34,9 @@ public class TeamBusinessService { private final CacheService cacheService; public TeamBusinessService(TeamPersistenceService teamPersistenceService, - ObjectiveBusinessService objectiveBusinessService, TeamValidationService validator, - CacheService cacheService, UserPersistenceService userPersistenceService, - UserTeamPersistenceService userTeamPersistenceService) { + ObjectiveBusinessService objectiveBusinessService, TeamValidationService validator, + CacheService cacheService, UserPersistenceService userPersistenceService, + UserTeamPersistenceService userTeamPersistenceService) { this.teamPersistenceService = teamPersistenceService; this.objectiveBusinessService = objectiveBusinessService; this.userPersistenceService = userPersistenceService; @@ -52,7 +51,8 @@ public Team getTeamById(Long teamId) { } @Transactional - // Creates a new team. Current authorization user is added as admin user in team. + // Creates a new team. Current authorization user is added as admin user in + // team. public Team createTeam(Team team, AuthorizationUser authorizationUser) { validator.validateOnCreate(team); cacheService.emptyAuthorizationUsersCache(); @@ -73,7 +73,7 @@ public Team updateTeam(Team team, Long id) { public void deleteTeam(Long id) { validator.validateOnDelete(id); objectiveBusinessService.getEntitiesByTeamId(id) - .forEach(objective -> objectiveBusinessService.deleteEntityById(objective.getId())); + .forEach(objective -> objectiveBusinessService.deleteEntityById(objective.getId())); deleteUserTeamList(id); cacheService.emptyAuthorizationUsersCache(); teamPersistenceService.deleteById(id); @@ -81,7 +81,8 @@ public void deleteTeam(Long id) { private void deleteUserTeamList(Long id) { var team = teamPersistenceService.findById(id); - // remove userTeam from each user, otherwise they are still in the session and are not deleted + // remove userTeam from each user, otherwise they are still in the session and + // are not deleted team.getUserTeamList().forEach(userTeam -> { var user = userTeam.getUser(); user.getUserTeamList().remove(userTeam); @@ -122,9 +123,11 @@ public void removeUserFromTeam(long teamId, long userId) { checkTeamHasAtLeastOneAdmin(team, user); var userTeamList = user.getUserTeamList(); - var userTeamToRemove = userTeamList.stream().filter(ut -> ut.getTeam().getId() == teamId).findFirst() - .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, - "No team found to remove from userTeam list")); + var userTeamToRemove = userTeamList.stream() + .filter(ut -> ut.getTeam().getId() == teamId) + .findFirst() + .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + "No team found to remove from userTeam list")); userTeamList.remove(userTeamToRemove); team.getUserTeamList().remove(userTeamToRemove); userTeamPersistenceService.delete(userTeamToRemove); @@ -133,10 +136,12 @@ public void removeUserFromTeam(long teamId, long userId) { } private void checkTeamHasAtLeastOneAdmin(Team team, User user) { - team.getUserTeamList().stream() - .filter(ut -> ut.isTeamAdmin() && !Objects.equals(ut.getUser().getId(), user.getId())).findAny() - .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, - ErrorKey.TRIED_TO_DELETE_LAST_ADMIN)); + team.getUserTeamList() + .stream() + .filter(ut -> ut.isTeamAdmin() && !Objects.equals(ut.getUser().getId(), user.getId())) + .findAny() + .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.TRIED_TO_DELETE_LAST_ADMIN)); } @Transactional diff --git a/backend/src/main/java/ch/puzzle/okr/service/business/UserBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/UserBusinessService.java index cfb7d3901e..add77fd124 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/UserBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/UserBusinessService.java @@ -7,12 +7,11 @@ import ch.puzzle.okr.service.persistence.UserPersistenceService; import ch.puzzle.okr.service.validation.UserValidationService; import jakarta.transaction.Transactional; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - import java.util.List; import java.util.Objects; import java.util.stream.StreamSupport; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; @Service public class UserBusinessService { @@ -24,7 +23,7 @@ public class UserBusinessService { private final CacheService cacheService; public UserBusinessService(UserPersistenceService userPersistenceService, UserValidationService validationService, - CacheService cacheService) { + CacheService cacheService) { this.userPersistenceService = userPersistenceService; this.validationService = validationService; this.cacheService = cacheService; @@ -55,9 +54,11 @@ public User setIsOkrChampion(User user, boolean okrChampion) { // checks if at least one okr champion remains after removing given one private void checkAtLeastOneOkrChampionExists(User user) { var champions = userPersistenceService.findAllOkrChampions(); - champions.stream().filter(c -> c.isOkrChampion() && !Objects.equals(c.getId(), user.getId())).findAny() - .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, - ErrorKey.TRIED_TO_REMOVE_LAST_OKR_CHAMPION)); + champions.stream() + .filter(c -> c.isOkrChampion() && !Objects.equals(c.getId(), user.getId())) + .findAny() + .orElseThrow(() -> new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.TRIED_TO_REMOVE_LAST_OKR_CHAMPION)); } public User saveUser(User user) { diff --git a/backend/src/main/java/ch/puzzle/okr/service/clientconfig/ClientConfigService.java b/backend/src/main/java/ch/puzzle/okr/service/clientconfig/ClientConfigService.java index 0b83fd2f4a..468c5e86cb 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/clientconfig/ClientConfigService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/clientconfig/ClientConfigService.java @@ -5,14 +5,13 @@ import ch.puzzle.okr.multitenancy.customization.TenantClientCustomization; import ch.puzzle.okr.multitenancy.customization.TenantClientCustomizationProvider; import jakarta.persistence.EntityNotFoundException; +import java.text.MessageFormat; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import java.text.MessageFormat; -import java.util.Optional; - @Service public class ClientConfigService { @@ -24,7 +23,7 @@ public class ClientConfigService { private String activeProfile; public ClientConfigService(final TenantClientCustomizationProvider clientCustomizationProvider, - final TenantConfigProvider tenantConfigProvider) { + final TenantConfigProvider tenantConfigProvider) { this.tenantConfigProvider = tenantConfigProvider; this.tenantClientCustomizationProvider = clientCustomizationProvider; } @@ -33,32 +32,34 @@ public ClientConfigDto getConfigBasedOnActiveEnv(String hostName) { String subdomain = hostName.split("\\.")[0]; String domainPrefixByHyphen = hostName.split("-")[0]; - Optional tenantConfig = getTenantConfig(hostName, subdomain, - domainPrefixByHyphen); + Optional tenantConfig = getTenantConfig(hostName, + subdomain, + domainPrefixByHyphen); if (tenantConfig.isEmpty()) { - throw new EntityNotFoundException( - MessageFormat.format("Could not find tenant config for subdomain:{0}", subdomain)); + throw new EntityNotFoundException(MessageFormat.format("Could not find tenant config for subdomain:{0}", + subdomain)); } Optional tenantClientCustomization = getTenantClientCustomization(hostName, - subdomain, domainPrefixByHyphen); + subdomain, + domainPrefixByHyphen); if (tenantClientCustomization.isEmpty()) { - throw new EntityNotFoundException( - MessageFormat.format("Could not find tenant client customization for subdomain:{0}", subdomain)); + throw new EntityNotFoundException(MessageFormat.format("Could not find tenant client customization for subdomain:{0}", + subdomain)); } return new ClientConfigDto(activeProfile, // - tenantConfig.get().issuerUrl(), // - tenantConfig.get().clientId(), // - tenantClientCustomization.get().favicon(), // - tenantClientCustomization.get().logo(), // - tenantClientCustomization.get().triangles(), // - tenantClientCustomization.get().backgroundLogo(), // - tenantClientCustomization.get().title(), // - tenantClientCustomization.get().helpSiteUrl(), // - tenantClientCustomization.get().customStyles()); // + tenantConfig.get().issuerUrl(), // + tenantConfig.get().clientId(), // + tenantClientCustomization.get().favicon(), // + tenantClientCustomization.get().logo(), // + tenantClientCustomization.get().triangles(), // + tenantClientCustomization.get().backgroundLogo(), // + tenantClientCustomization.get().title(), // + tenantClientCustomization.get().helpSiteUrl(), // + tenantClientCustomization.get().customStyles()); // } private Optional getTenantConfig(String hostname, String... tenantsFromUrl) { @@ -75,10 +76,9 @@ private Optional getTenantConfig(String hostn } private Optional getTenantClientCustomization(String hostname, - String... tenantsFromUrl) { + String... tenantsFromUrl) { for (String tenant : tenantsFromUrl) { - Optional tenantCustomization = tenantClientCustomizationProvider - .getTenantClientCustomizationsById(tenant); + Optional tenantCustomization = tenantClientCustomizationProvider.getTenantClientCustomizationsById(tenant); if (tenantCustomization.isPresent()) { logger.info("get client customization for " + tenant + ": OK"); return tenantCustomization; diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/ActionPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/ActionPersistenceService.java index 3c3a1ff83c..2ceb3685fe 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/ActionPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/ActionPersistenceService.java @@ -1,12 +1,11 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.ACTION; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.repository.ActionRepository; -import org.springframework.stereotype.Service; - import java.util.List; - -import static ch.puzzle.okr.Constants.ACTION; +import org.springframework.stereotype.Service; @Service public class ActionPersistenceService extends PersistenceBase { diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceService.java index 03bb2ad444..e3451cb05a 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceService.java @@ -1,14 +1,13 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.ALIGNMENT; + import ch.puzzle.okr.models.alignment.Alignment; import ch.puzzle.okr.models.alignment.KeyResultAlignment; import ch.puzzle.okr.models.alignment.ObjectiveAlignment; import ch.puzzle.okr.repository.AlignmentRepository; -import org.springframework.stereotype.Service; - import java.util.List; - -import static ch.puzzle.okr.Constants.ALIGNMENT; +import org.springframework.stereotype.Service; @Service public class AlignmentPersistenceService extends PersistenceBase { diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceService.java index 3a439073b8..b460372231 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceService.java @@ -2,9 +2,8 @@ import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.repository.AlignmentSelectionRepository; -import org.springframework.stereotype.Service; - import java.util.List; +import org.springframework.stereotype.Service; @Service public class AlignmentSelectionPersistenceService { diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/AuthorizationCriteria.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/AuthorizationCriteria.java index 50649665db..fd00daa848 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/AuthorizationCriteria.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/AuthorizationCriteria.java @@ -1,17 +1,16 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.models.State.*; +import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; +import static java.lang.String.format; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import jakarta.persistence.TypedQuery; +import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; -import java.util.List; - -import static ch.puzzle.okr.models.State.*; -import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; -import static java.lang.String.format; - @Component public class AuthorizationCriteria { @@ -30,7 +29,7 @@ public String appendOverview(List teamIds, String objectiveQuery, Authoriz } if (shouldAddObjectiveFilter(objectiveQuery)) { sb.append("\n and lower(coalesce(o.objectiveTitle, '')) like lower(concat('%',:" + PARAM_OBJECTIVE_QUERY - + ",'%'))"); + + ",'%'))"); } String authorizationWhereClause = append(user, alias, "objectiveState", "overviewId.teamId"); if (!authorizationWhereClause.isEmpty()) { @@ -50,8 +49,13 @@ private String append(AuthorizationUser user, String alias, String stateColumn, sb.append(format(" or %s.%s=:%s", alias, stateColumn, PARAM_ALL_DRAFT_STATE)); } else { // users can read draft state of teams with admin role - sb.append(format(" or (%s.%s=:%s and %s.%s IN (:%s))", alias, stateColumn, PARAM_TEAM_DRAFT_STATE, alias, - teamIdColumn, PARAM_USER_TEAM_IDS)); + sb.append(format(" or (%s.%s=:%s and %s.%s IN (:%s))", + alias, + stateColumn, + PARAM_TEAM_DRAFT_STATE, + alias, + teamIdColumn, + PARAM_USER_TEAM_IDS)); } // all users can read published state sb.append(format(" or %s.%s IN (:%s)", alias, stateColumn, PARAM_PUBLISHED_STATES)); @@ -62,7 +66,7 @@ private String append(AuthorizationUser user, String alias, String stateColumn, } public void setParameters(TypedQuery typedQuery, List teamIds, String objectiveQuery, - AuthorizationUser user) { + AuthorizationUser user) { if (shouldAddTeamFilter(teamIds)) { typedQuery.setParameter(PARAM_TEAM_IDS, teamIds); } diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/CheckInPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/CheckInPersistenceService.java index 5a96b8dcb5..8beee6fd3b 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/CheckInPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/CheckInPersistenceService.java @@ -1,12 +1,11 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.CHECK_IN; + import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.repository.CheckInRepository; -import org.springframework.stereotype.Service; - import java.util.List; - -import static ch.puzzle.okr.Constants.CHECK_IN; +import org.springframework.stereotype.Service; @Service public class CheckInPersistenceService extends PersistenceBase { diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/CompletedPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/CompletedPersistenceService.java index 48a5d2c195..4741bde78e 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/CompletedPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/CompletedPersistenceService.java @@ -1,11 +1,11 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.COMPLETED; + import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.repository.CompletedRepository; import org.springframework.stereotype.Service; -import static ch.puzzle.okr.Constants.COMPLETED; - @Service public class CompletedPersistenceService extends PersistenceBase { diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceService.java index 095a5800ef..17f54b24fe 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceService.java @@ -1,13 +1,12 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.KEY_RESULT; + import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.repository.KeyResultRepository; import jakarta.transaction.Transactional; -import org.springframework.stereotype.Service; - import java.util.List; - -import static ch.puzzle.okr.Constants.KEY_RESULT; +import org.springframework.stereotype.Service; @Service public class KeyResultPersistenceService extends PersistenceBase { @@ -41,7 +40,7 @@ public KeyResult updateEntity(KeyResult keyResult) { public List getKeyResultsOwnedByUser(long userId) { return findAll().stream() // - .filter(keyResult -> keyResult.getOwner().getId().equals(userId)) // - .toList(); + .filter(keyResult -> keyResult.getOwner().getId().equals(userId)) // + .toList(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceService.java index 9e7a2bcd34..aac01d8da1 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceService.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.OBJECTIVE; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.Quarter; @@ -9,14 +11,11 @@ import jakarta.persistence.EntityManager; import jakarta.persistence.NoResultException; import jakarta.persistence.TypedQuery; +import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import java.util.List; - -import static ch.puzzle.okr.Constants.OBJECTIVE; - @Service public class ObjectivePersistenceService extends PersistenceBase { @@ -29,7 +28,7 @@ public class ObjectivePersistenceService extends PersistenceBase authorizationCriteria; protected ObjectivePersistenceService(ObjectiveRepository repository, EntityManager entityManager, - AuthorizationCriteria authorizationCriteria) { + AuthorizationCriteria authorizationCriteria) { super(repository); this.entityManager = entityManager; this.authorizationCriteria = authorizationCriteria; @@ -41,8 +40,9 @@ public String getModelName() { } /** - * Get the number of Objectives of a Team in a Quarter. The underling sql looks like "select count(*) from objective - * where teamId = team.id and quarterId = quarter.id." + * Get the number of Objectives of a Team in a Quarter. The underling sql looks + * like "select count(*) from objective where teamId = team.id and quarterId = + * quarter.id." * * @param team * Team @@ -56,7 +56,7 @@ public Integer countByTeamAndQuarter(Team team, Quarter quarter) { } public Objective findObjectiveById(Long objectiveId, AuthorizationUser authorizationUser, - OkrResponseStatusException noResultException) { + OkrResponseStatusException noResultException) { return findByAnyId(objectiveId, authorizationUser, SELECT_OBJECTIVE_BY_ID, noResultException); } @@ -65,17 +65,17 @@ public List findObjectiveByTeamId(Long teamId) { } public Objective findObjectiveByKeyResultId(Long keyResultId, AuthorizationUser authorizationUser, - OkrResponseStatusException noResultException) { + OkrResponseStatusException noResultException) { return findByAnyId(keyResultId, authorizationUser, SELECT_OBJECTIVE_BY_KEY_RESULT_ID, noResultException); } public Objective findObjectiveByCheckInId(Long checkInId, AuthorizationUser authorizationUser, - OkrResponseStatusException noResultException) { + OkrResponseStatusException noResultException) { return findByAnyId(checkInId, authorizationUser, SELECT_OBJECTIVE_BY_CHECK_IN_ID, noResultException); } private Objective findByAnyId(Long id, AuthorizationUser authorizationUser, String queryString, - OkrResponseStatusException noResultException) { + OkrResponseStatusException noResultException) { checkIdNull(id); String fullQueryString = queryString + authorizationCriteria.appendObjective(authorizationUser); logger.debug("select objective by id={}: {}", id, fullQueryString); diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/OverviewPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/OverviewPersistenceService.java index 197cdc5d9d..6d2a2800b6 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/OverviewPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/OverviewPersistenceService.java @@ -4,12 +4,11 @@ import ch.puzzle.okr.models.overview.Overview; import jakarta.persistence.EntityManager; import jakarta.persistence.TypedQuery; +import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import java.util.List; - @Service public class OverviewPersistenceService { @@ -20,15 +19,15 @@ public class OverviewPersistenceService { private final AuthorizationCriteria authorizationCriteria; public OverviewPersistenceService(EntityManager entityManager, - AuthorizationCriteria authorizationCriteria) { + AuthorizationCriteria authorizationCriteria) { this.entityManager = entityManager; this.authorizationCriteria = authorizationCriteria; } public List getFilteredOverview(Long quarterId, List teamIds, String objectiveQuery, - AuthorizationUser authorizationUser) { + AuthorizationUser authorizationUser) { String queryString = SELECT_OVERVIEW - + authorizationCriteria.appendOverview(teamIds, objectiveQuery, authorizationUser); + + authorizationCriteria.appendOverview(teamIds, objectiveQuery, authorizationUser); logger.debug("select overview by quarterId={} and teamIds={}: {}", quarterId, teamIds, queryString); TypedQuery typedQuery = entityManager.createQuery(queryString, Overview.class); typedQuery.setParameter("quarterId", quarterId); diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/PersistenceBase.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/PersistenceBase.java index f10ea423fc..edc4246a8c 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/PersistenceBase.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/PersistenceBase.java @@ -1,21 +1,20 @@ package ch.puzzle.okr.service.persistence; +import static org.springframework.http.HttpStatus.BAD_REQUEST; +import static org.springframework.http.HttpStatus.NOT_FOUND; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; +import java.util.List; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.stream.StreamSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.data.repository.CrudRepository; import org.springframework.http.HttpStatus; -import java.util.List; -import java.util.Spliterator; -import java.util.Spliterators; -import java.util.stream.StreamSupport; - -import static org.springframework.http.HttpStatus.BAD_REQUEST; -import static org.springframework.http.HttpStatus.NOT_FOUND; - /** * @param * the Type or entity of the repository @@ -59,8 +58,9 @@ public T save(T model) throws OkrResponseStatusException { return repository.save(model); } catch (OptimisticLockingFailureException ex) { logger.info("optimistic locking exception while saving {}", model, ex); - throw new OkrResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, ErrorKey.DATA_HAS_BEEN_UPDATED, - getModelName()); + throw new OkrResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, + ErrorKey.DATA_HAS_BEEN_UPDATED, + getModelName()); } } @@ -75,7 +75,8 @@ public void deleteById(ID id) { public abstract String getModelName(); private List iteratorToList(Iterable iterable) { - return StreamSupport - .stream(Spliterators.spliteratorUnknownSize(iterable.iterator(), Spliterator.ORDERED), false).toList(); + return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterable.iterator(), Spliterator.ORDERED), + false) + .toList(); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/QuarterPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/QuarterPersistenceService.java index 5646a15998..d9e4d938ab 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/QuarterPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/QuarterPersistenceService.java @@ -1,13 +1,12 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.QUARTER; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.repository.QuarterRepository; -import org.springframework.stereotype.Service; - import java.time.LocalDate; import java.util.List; - -import static ch.puzzle.okr.Constants.QUARTER; +import org.springframework.stereotype.Service; @Service public class QuarterPersistenceService extends PersistenceBase { diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/TeamPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/TeamPersistenceService.java index 533949d848..dd485164aa 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/TeamPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/TeamPersistenceService.java @@ -1,12 +1,11 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.TEAM; + import ch.puzzle.okr.models.Team; import ch.puzzle.okr.repository.TeamRepository; -import org.springframework.stereotype.Service; - import java.util.List; - -import static ch.puzzle.okr.Constants.TEAM; +import org.springframework.stereotype.Service; @Service public class TeamPersistenceService extends PersistenceBase { diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/UserPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/UserPersistenceService.java index 6d5befc699..2cfa105ec8 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/UserPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/UserPersistenceService.java @@ -1,13 +1,12 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.USER; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.repository.UserRepository; -import org.springframework.stereotype.Service; - import java.util.List; import java.util.Optional; - -import static ch.puzzle.okr.Constants.USER; +import org.springframework.stereotype.Service; @Service public class UserPersistenceService extends PersistenceBase { diff --git a/backend/src/main/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceService.java b/backend/src/main/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceService.java index 326feabe4d..8bb03cd758 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceService.java @@ -1,12 +1,11 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.USER_TEAM; + import ch.puzzle.okr.models.UserTeam; import ch.puzzle.okr.repository.UserTeamRepository; -import org.springframework.stereotype.Service; - import java.util.List; - -import static ch.puzzle.okr.Constants.USER_TEAM; +import org.springframework.stereotype.Service; @Service public class UserTeamPersistenceService extends PersistenceBase { diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/ActionValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/ActionValidationService.java index 4e591099ff..94b9af0e89 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/ActionValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/ActionValidationService.java @@ -7,11 +7,10 @@ import ch.puzzle.okr.models.MessageKey; import ch.puzzle.okr.repository.ActionRepository; import ch.puzzle.okr.service.persistence.ActionPersistenceService; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - import java.util.List; import java.util.Objects; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; @Service public class ActionValidationService extends ValidationBase { @@ -19,7 +18,7 @@ public class ActionValidationService extends ValidationBase { + extends + ValidationBase { public CheckInValidationService(CheckInPersistenceService checkInPersistenceService) { super(checkInPersistenceService); @@ -39,8 +39,9 @@ public void validateOnUpdate(Long id, CheckIn model) { private static void throwExceptionWhenKeyResultHasChanged(CheckIn checkIn, CheckIn savedCheckIn) { if (!Objects.equals(checkIn.getKeyResult().getId(), savedCheckIn.getKeyResult().getId())) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_CANNOT_CHANGE, - List.of(Constants.KEY_RESULT, Constants.CHECK_IN)); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_CANNOT_CHANGE, + List.of(Constants.KEY_RESULT, Constants.CHECK_IN)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/CompletedValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/CompletedValidationService.java index 702db8e4d7..178ef9019e 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/CompletedValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/CompletedValidationService.java @@ -7,7 +7,8 @@ @Service public class CompletedValidationService - extends ValidationBase { + extends + ValidationBase { public CompletedValidationService(CompletedPersistenceService completedPersistenceService) { super(completedPersistenceService); diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/KeyResultValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/KeyResultValidationService.java index ea5a3b68e9..8f4795fb1c 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/KeyResultValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/KeyResultValidationService.java @@ -6,15 +6,15 @@ import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.repository.KeyResultRepository; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - import java.util.List; import java.util.Objects; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; @Service public class KeyResultValidationService - extends ValidationBase { + extends + ValidationBase { public KeyResultValidationService(KeyResultPersistenceService keyResultPersistenceService) { super(keyResultPersistenceService); @@ -39,8 +39,9 @@ public void validateOnUpdate(Long id, KeyResult model) { private static void throwExceptionWhenObjectiveHasChanged(KeyResult keyResult, KeyResult savedKeyResult) { if (!Objects.equals(keyResult.getObjective().getId(), savedKeyResult.getObjective().getId())) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_CANNOT_CHANGE, - List.of(Constants.OBJECTIVE, Constants.KEY_RESULT)); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_CANNOT_CHANGE, + List.of(Constants.OBJECTIVE, Constants.KEY_RESULT)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/ObjectiveValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/ObjectiveValidationService.java index 72f518c738..e2761c17c8 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/ObjectiveValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/ObjectiveValidationService.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.Constants.*; +import static ch.puzzle.okr.service.validation.QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -7,18 +10,15 @@ import ch.puzzle.okr.models.Team; import ch.puzzle.okr.repository.ObjectiveRepository; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - import java.util.List; import java.util.Objects; - -import static ch.puzzle.okr.Constants.*; -import static ch.puzzle.okr.service.validation.QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; @Service public class ObjectiveValidationService - extends ValidationBase { + extends + ValidationBase { public ObjectiveValidationService(ObjectivePersistenceService objectivePersistenceService) { super(objectivePersistenceService); @@ -49,36 +49,40 @@ public void validateOnUpdate(Long id, Objective model) { private void throwExceptionWhenModifiedByIsSet(Objective model) { if (model.getModifiedBy() != null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_SET_FORBIDDEN, - List.of("ModifiedBy", model.getModifiedBy())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_SET_FORBIDDEN, + List.of("ModifiedBy", model.getModifiedBy())); } } private void throwExceptionWhenModifiedByIsNull(Objective model) { if (model.getModifiedBy() == null) { - throw new OkrResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, ErrorKey.ATTRIBUTE_NOT_SET, - "modifiedBy"); + throw new OkrResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, + ErrorKey.ATTRIBUTE_NOT_SET, + "modifiedBy"); } } private void throwExceptionWhenTeamHasChanged(Team team, Team savedTeam) { if (!Objects.equals(team, savedTeam)) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_CANNOT_CHANGE, - List.of(TEAM, OBJECTIVE)); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_CANNOT_CHANGE, + List.of(TEAM, OBJECTIVE)); } } private void throwExceptionWhenNotDraftInBacklogQuarter(Objective model) { if (isInvalidBacklogObjective(model)) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_MUST_BE_DRAFT, - List.of(OBJECTIVE, STATE_DRAFT, model.getState())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_MUST_BE_DRAFT, + List.of(OBJECTIVE, STATE_DRAFT, model.getState())); } } private boolean isInvalidBacklogObjective(Objective model) { return model.getQuarter().getLabel().equals(BACK_LOG_QUARTER_LABEL) // - && model.getQuarter().getStartDate() == null // - && model.getQuarter().getEndDate() == null // - && (model.getState() != State.DRAFT); + && model.getQuarter().getStartDate() == null // + && model.getQuarter().getEndDate() == null // + && (model.getState() != State.DRAFT); } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/OverviewValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/OverviewValidationService.java index af0013b52d..1ff7e18fdf 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/OverviewValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/OverviewValidationService.java @@ -1,7 +1,7 @@ package ch.puzzle.okr.service.validation; -import org.springframework.stereotype.Service; import java.util.List; +import org.springframework.stereotype.Service; @Service public class OverviewValidationService { diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/QuarterValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/QuarterValidationService.java index baa9df7252..4f1d47787b 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/QuarterValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/QuarterValidationService.java @@ -1,20 +1,20 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.repository.QuarterRepository; import ch.puzzle.okr.service.persistence.QuarterPersistenceService; +import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; -import java.util.List; - -import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; - @Service public class QuarterValidationService - extends ValidationBase { + extends + ValidationBase { public QuarterValidationService(QuarterPersistenceService quarterPersistenceService) { super(quarterPersistenceService); @@ -33,11 +33,13 @@ public void validateOnUpdate(Long id, Quarter model) { public static void throwExceptionWhenStartEndDateQuarterIsNull(Quarter model) { if (!model.getLabel().equals(BACK_LOG_QUARTER_LABEL)) { if (model.getStartDate() == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_NULL, - List.of("StartDate", model.getLabel())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_NULL, + List.of("StartDate", model.getLabel())); } else if (model.getEndDate() == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_NULL, - List.of("EndDate", model.getLabel())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_NULL, + List.of("EndDate", model.getLabel())); } } @@ -45,11 +47,13 @@ public static void throwExceptionWhenStartEndDateQuarterIsNull(Quarter model) { public void validateOnGeneration(Quarter quarter) { if (quarter.getStartDate() == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_NULL, - List.of("StartDate", quarter.getLabel())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_NULL, + List.of("StartDate", quarter.getLabel())); } else if (quarter.getEndDate() == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_NULL, - List.of("EndDate", quarter.getLabel())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_NULL, + List.of("EndDate", quarter.getLabel())); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/TeamValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/TeamValidationService.java index 8b08e1d4a2..56b6f43dd0 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/TeamValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/TeamValidationService.java @@ -1,17 +1,16 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.Constants.TEAM; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.repository.TeamRepository; import ch.puzzle.okr.service.persistence.TeamPersistenceService; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - import java.util.List; import java.util.Objects; - -import static ch.puzzle.okr.Constants.TEAM; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; @Service public class TeamValidationService extends ValidationBase { @@ -39,11 +38,15 @@ public void validateOnUpdate(Long id, Team model) { } private void checkIfTeamWithNameAlreadyExists(String name, Long id) { - List filteredTeam = this.getPersistenceService().findTeamsByName(name).stream() - .filter(team -> !Objects.equals(team.getId(), id)).toList(); + List filteredTeam = this.getPersistenceService() + .findTeamsByName(name) + .stream() + .filter(team -> !Objects.equals(team.getId(), id)) + .toList(); if (!filteredTeam.isEmpty()) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ALREADY_EXISTS_SAME_NAME, - List.of(TEAM, name)); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ALREADY_EXISTS_SAME_NAME, + List.of(TEAM, name)); } } } diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/UserValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/UserValidationService.java index 487530aa3e..b2ed76eabf 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/UserValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/UserValidationService.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.service.validation; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; @@ -10,8 +12,6 @@ import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.stereotype.Service; -import static org.springframework.http.HttpStatus.BAD_REQUEST; - @Service public class UserValidationService extends ValidationBase { diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/ValidationBase.java b/backend/src/main/java/ch/puzzle/okr/service/validation/ValidationBase.java index e18cd9e982..ccb7fe2e87 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/ValidationBase.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/ValidationBase.java @@ -9,14 +9,13 @@ import jakarta.validation.Validation; import jakarta.validation.Validator; import jakarta.validation.ValidatorFactory; -import org.springframework.http.HttpStatus; - import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.springframework.http.HttpStatus; /** * @param @@ -62,29 +61,33 @@ public T doesEntityExist(ID id) { public void throwExceptionWhenModelIsNull(T model) { if (model == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.MODEL_NULL, - persistenceService.getModelName()); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.MODEL_NULL, + persistenceService.getModelName()); } } public void throwExceptionWhenIdIsNull(ID id) { if (id == null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_NULL, - List.of("ID", persistenceService.getModelName())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_NULL, + List.of("ID", persistenceService.getModelName())); } } protected void throwExceptionWhenIdIsNotNull(ID id) { if (id != null) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, MessageKey.ATTRIBUTE_NOT_NULL, - List.of("ID", persistenceService.getModelName())); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + MessageKey.ATTRIBUTE_NOT_NULL, + List.of("ID", persistenceService.getModelName())); } } protected void throwExceptionWhenIdHasChanged(ID id, ID modelId) { if (!Objects.equals(id, modelId)) { - throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, ErrorKey.ATTRIBUTE_CHANGED, - List.of("ID", id, modelId)); + throw new OkrResponseStatusException(HttpStatus.BAD_REQUEST, + ErrorKey.ATTRIBUTE_CHANGED, + List.of("ID", id, modelId)); } } @@ -102,13 +105,15 @@ private void processViolations(Set> violations) { private List createErrorDtos(Set> violations) { return violations.stream() // - .map(e -> { // - String path = e.getPropertyPath().toString(); // - List attributes = new ArrayList<>(List.of(path, persistenceService.getModelName())); // - attributes.addAll(getAttributes(e.getMessage(), e.getMessageTemplate())); // - String errorKey = e.getMessageTemplate().replaceAll("_\\{.*", ""); // - return ErrorDto.of(errorKey, attributes); // - }).toList(); + .map(e -> { // + String path = e.getPropertyPath().toString(); // + List attributes = new ArrayList<>(List.of(path, + persistenceService.getModelName())); // + attributes.addAll(getAttributes(e.getMessage(), e.getMessageTemplate())); // + String errorKey = e.getMessageTemplate().replaceAll("_\\{.*", ""); // + return ErrorDto.of(errorKey, attributes); // + }) + .toList(); } // example: diff --git a/backend/src/main/java/ch/puzzle/okr/util/CollectionUtils.java b/backend/src/main/java/ch/puzzle/okr/util/CollectionUtils.java index 5c3a002a28..d3cc589812 100644 --- a/backend/src/main/java/ch/puzzle/okr/util/CollectionUtils.java +++ b/backend/src/main/java/ch/puzzle/okr/util/CollectionUtils.java @@ -8,7 +8,7 @@ public class CollectionUtils { public static List iterableToList(Iterable iterable) { return StreamSupport // - .stream(iterable.spliterator(), false) // - .collect(Collectors.toList()); + .stream(iterable.spliterator(), false) // + .collect(Collectors.toList()); } } diff --git a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterData.java b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterData.java index 2bab507122..e4bf233d1e 100644 --- a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterData.java +++ b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterData.java @@ -1,13 +1,13 @@ package ch.puzzle.okr.util.quarter.generate; -import org.springframework.context.annotation.Profile; - import java.time.LocalDate; +import org.springframework.context.annotation.Profile; /** * Quarter data for H2 database.
*
- * This class is used for testing purposes only. Do NOT use this class in production mode. + * This class is used for testing purposes only. Do NOT use this class in + * production mode. */ @Profile("integration-test") public record QuarterData(String label, LocalDate startDate, LocalDate endDate) { @@ -30,9 +30,9 @@ private String isoFormat(LocalDate date) { @Override public String toString() { return "(" + "'" + label() + "', " + // - "'" + startDateAsIsoString() + "', " + // - "'" + endDateAsIsoString() + "'" + // - ")"; + "'" + startDateAsIsoString() + "', " + // + "'" + endDateAsIsoString() + "'" + // + ")"; } } diff --git a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterLabel.java b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterLabel.java index 4b44aaf00b..85f6e36b8c 100644 --- a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterLabel.java +++ b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/QuarterLabel.java @@ -1,13 +1,13 @@ package ch.puzzle.okr.util.quarter.generate; -import org.springframework.context.annotation.Profile; - import java.time.LocalDate; +import org.springframework.context.annotation.Profile; /** * Quarter label for H2 database.
*
- * This class is used for testing purposes only. Do NOT use this class in production mode. + * This class is used for testing purposes only. Do NOT use this class in + * production mode. */ @Profile("integration-test") public class QuarterLabel { @@ -19,9 +19,9 @@ public QuarterLabel(LocalDate date) { public String label() { return "GJ " + // - formatYearAs2Digits(firstYearOfGeschaeftsJahr()) + "/" + // - formatYearAs2Digits(secondYearOfGeschaeftsJahr()) + "-Q" + // - getQuarterDigit(); + formatYearAs2Digits(firstYearOfGeschaeftsJahr()) + "/" + // + formatYearAs2Digits(secondYearOfGeschaeftsJahr()) + "-Q" + // + getQuarterDigit(); } private int getQuarterDigit() { diff --git a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/Quarters.java b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/Quarters.java index 0c7679714b..d7dcc53f12 100644 --- a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/Quarters.java +++ b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/Quarters.java @@ -1,15 +1,15 @@ package ch.puzzle.okr.util.quarter.generate; -import org.springframework.context.annotation.Profile; - import java.time.LocalDate; import java.util.ArrayList; import java.util.List; +import org.springframework.context.annotation.Profile; /** * Static initialize quarters for H2 database.
*
- * This class is used for testing purposes only. Do NOT use this class in production mode. + * This class is used for testing purposes only. Do NOT use this class in + * production mode. */ @Profile("integration-test") public class Quarters { diff --git a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunction.java b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunction.java index fec72a232a..563b7e4f29 100644 --- a/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunction.java +++ b/backend/src/main/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunction.java @@ -2,19 +2,19 @@ import ch.puzzle.okr.util.quarter.generate.QuarterData; import ch.puzzle.okr.util.quarter.generate.Quarters; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; -import java.time.LocalDate; -import java.util.HashMap; -import java.util.Map; - /** * Quarter functions for H2 database.
*
- * This class is used for testing purposes only. Do NOT use this class in production mode. + * This class is used for testing purposes only. Do NOT use this class in + * production mode. */ @Component @Profile("integration-test") diff --git a/backend/src/test/java/ch/puzzle/okr/ForwardFilterTest.java b/backend/src/test/java/ch/puzzle/okr/ForwardFilterTest.java index 1c27667c3e..81fe66f00c 100644 --- a/backend/src/test/java/ch/puzzle/okr/ForwardFilterTest.java +++ b/backend/src/test/java/ch/puzzle/okr/ForwardFilterTest.java @@ -1,12 +1,14 @@ package ch.puzzle.okr; +import static org.mockito.Mockito.*; + import jakarta.servlet.FilterChain; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; +import java.io.IOException; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -15,10 +17,6 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import java.io.IOException; - -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class ForwardFilterTest { @InjectMocks diff --git a/backend/src/test/java/ch/puzzle/okr/SpringCachingConfigTest.java b/backend/src/test/java/ch/puzzle/okr/SpringCachingConfigTest.java index 1ca5d0825a..0d4001cd23 100644 --- a/backend/src/test/java/ch/puzzle/okr/SpringCachingConfigTest.java +++ b/backend/src/test/java/ch/puzzle/okr/SpringCachingConfigTest.java @@ -1,5 +1,9 @@ package ch.puzzle.okr; +import static ch.puzzle.okr.SpringCachingConfig.AUTHORIZATION_USER_CACHE; +import static ch.puzzle.okr.test.TestHelper.defaultUser; +import static org.junit.jupiter.api.Assertions.*; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.multitenancy.TenantContext; @@ -14,10 +18,6 @@ import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; -import static ch.puzzle.okr.SpringCachingConfig.AUTHORIZATION_USER_CACHE; -import static ch.puzzle.okr.test.TestHelper.defaultUser; -import static org.junit.jupiter.api.Assertions.*; - @SpringIntegrationTest class SpringCachingConfigTest { @@ -64,12 +64,12 @@ void testUserIsCached() { } private void assertEqualUsers(AuthorizationUser expectedAuthorizationUser, - AuthorizationUser actualAuthorizationUser) { + AuthorizationUser actualAuthorizationUser) { User expcetedUser = expectedAuthorizationUser.user(); User actualUser = actualAuthorizationUser.user(); assertTrue(expcetedUser.getFirstname().equals(actualUser.getFirstname()) - && expcetedUser.getLastname().equals(actualUser.getLastname()) - && expcetedUser.getEmail().equals(actualUser.getEmail())); + && expcetedUser.getLastname().equals(actualUser.getLastname()) + && expcetedUser.getEmail().equals(actualUser.getEmail())); } } \ No newline at end of file diff --git a/backend/src/test/java/ch/puzzle/okr/UserKeyGeneratorTest.java b/backend/src/test/java/ch/puzzle/okr/UserKeyGeneratorTest.java index 05d38792e5..511dc51dc3 100644 --- a/backend/src/test/java/ch/puzzle/okr/UserKeyGeneratorTest.java +++ b/backend/src/test/java/ch/puzzle/okr/UserKeyGeneratorTest.java @@ -1,14 +1,13 @@ package ch.puzzle.okr; +import static ch.puzzle.okr.test.KeyResultTestHelpers.user; + import ch.puzzle.okr.multitenancy.TenantContext; +import java.lang.reflect.Method; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; - -import static ch.puzzle.okr.test.KeyResultTestHelpers.user; - class UserKeyGeneratorTest { @BeforeEach diff --git a/backend/src/test/java/ch/puzzle/okr/architecture/OkrArchitectureTest.java b/backend/src/test/java/ch/puzzle/okr/architecture/OkrArchitectureTest.java index cde1091ed1..dd6c848a00 100644 --- a/backend/src/test/java/ch/puzzle/okr/architecture/OkrArchitectureTest.java +++ b/backend/src/test/java/ch/puzzle/okr/architecture/OkrArchitectureTest.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.architecture; +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; +import static com.tngtech.archunit.library.Architectures.layeredArchitecture; + import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.core.importer.ImportOption; @@ -13,17 +17,18 @@ import org.springframework.stereotype.*; import org.springframework.web.bind.annotation.RestController; -import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; -import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; -import static com.tngtech.archunit.library.Architectures.layeredArchitecture; - class OkrArchitectureTest { @Test void repositoryAccessedOnlyByPersistenceService() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..repository..").should().onlyBeAccessed() - .byAnyPackage("..service.persistence..").andShould().beInterfaces(); + ArchRule rule = classes().that() + .resideInAPackage("..repository..") + .should() + .onlyBeAccessed() + .byAnyPackage("..service.persistence..") + .andShould() + .beInterfaces(); rule.check(importedClasses); } @@ -31,8 +36,11 @@ void repositoryAccessedOnlyByPersistenceService() { @Test void mapperAccessedByControllerOrAuthorization() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..mapper..").should().onlyBeAccessed() - .byAnyPackage("..controller..", "..mapper..", "..authorization.."); + ArchRule rule = classes().that() + .resideInAPackage("..mapper..") + .should() + .onlyBeAccessed() + .byAnyPackage("..controller..", "..mapper..", "..authorization.."); rule.check(importedClasses); } @@ -40,8 +48,11 @@ void mapperAccessedByControllerOrAuthorization() { @Test void authorizationServiceAccessedByControllerOrAuthorization() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..service.authorization..").should().onlyBeAccessed() - .byAnyPackage("..controller..", "..authorization.."); + ArchRule rule = classes().that() + .resideInAPackage("..service.authorization..") + .should() + .onlyBeAccessed() + .byAnyPackage("..controller..", "..authorization.."); rule.check(importedClasses); } @@ -49,8 +60,11 @@ void authorizationServiceAccessedByControllerOrAuthorization() { @Test void businessServiceAccessedByControllerOrAuthorizationServiceOrMapper() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..service.business..").should().onlyBeAccessed() - .byAnyPackage("..controller..", "..authorization..", "..mapper..", "..business"); + ArchRule rule = classes().that() + .resideInAPackage("..service.business..") + .should() + .onlyBeAccessed() + .byAnyPackage("..controller..", "..authorization..", "..mapper..", "..business"); rule.check(importedClasses); } @@ -59,8 +73,13 @@ void businessServiceAccessedByControllerOrAuthorizationServiceOrMapper() { void controllerCallsNoRepository() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = noClasses().that().resideInAPackage("ch.puzzle.okr.controller..").should().dependOnClassesThat() - .resideInAPackage("..repository..").andShould().notBeInterfaces(); + ArchRule rule = noClasses().that() + .resideInAPackage("ch.puzzle.okr.controller..") + .should() + .dependOnClassesThat() + .resideInAPackage("..repository..") + .andShould() + .notBeInterfaces(); rule.check(importedClasses); } @@ -69,8 +88,13 @@ void controllerCallsNoRepository() { void repositoryCallsNoService() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = noClasses().that().resideInAPackage("ch.puzzle.okr.repository").should().dependOnClassesThat() - .resideInAPackage("..service..").andShould().beInterfaces(); + ArchRule rule = noClasses().that() + .resideInAPackage("ch.puzzle.okr.repository") + .should() + .dependOnClassesThat() + .resideInAPackage("..service..") + .andShould() + .beInterfaces(); rule.check(importedClasses); } @@ -79,8 +103,14 @@ void repositoryCallsNoService() { void servicesAreAnnotatedWithService() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().areNotAnonymousClasses().and().resideInAPackage("ch.puzzle.okr.service") - .should().beAnnotatedWith(Service.class).andShould().notBeInterfaces(); + ArchRule rule = classes().that() + .areNotAnonymousClasses() + .and() + .resideInAPackage("ch.puzzle.okr.service") + .should() + .beAnnotatedWith(Service.class) + .andShould() + .notBeInterfaces(); rule.check(importedClasses); } @@ -89,9 +119,16 @@ void servicesAreAnnotatedWithService() { void controllersAreAnnotatedWithRestController() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().areNotAnonymousClasses().and().resideInAPackage("ch.puzzle.okr.controller..") - .should().beAnnotatedWith(RestController.class).orShould().beAnnotatedWith(Controller.class).andShould() - .notBeInterfaces(); + ArchRule rule = classes().that() + .areNotAnonymousClasses() + .and() + .resideInAPackage("ch.puzzle.okr.controller..") + .should() + .beAnnotatedWith(RestController.class) + .orShould() + .beAnnotatedWith(Controller.class) + .andShould() + .notBeInterfaces(); rule.check(importedClasses); } @@ -100,8 +137,14 @@ void controllersAreAnnotatedWithRestController() { void mappersAreAnnotatedWithComponent() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().areNotAnonymousClasses().and().resideInAPackage("ch.puzzle.okr.mapper") - .should().beAnnotatedWith(Component.class).andShould().notBeInterfaces(); + ArchRule rule = classes().that() + .areNotAnonymousClasses() + .and() + .resideInAPackage("ch.puzzle.okr.mapper") + .should() + .beAnnotatedWith(Component.class) + .andShould() + .notBeInterfaces(); rule.check(importedClasses); } @@ -109,23 +152,34 @@ void mappersAreAnnotatedWithComponent() { @ParameterizedTest @CsvFileSource(resources = "/repositoriesAndPersistenceServices.csv", numLinesToSkip = 1) void repositoriesShouldOnlyBeCalledFromPersistenceServicesAndValidationService(String repository, - String persistenceService, String validationService) { + String persistenceService, + String validationService) { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().haveSimpleName(repository).should().onlyHaveDependentClassesThat() - .haveSimpleName(persistenceService).orShould().haveSimpleName(repository).orShould() - .haveSimpleName(validationService); + ArchRule rule = classes().that() + .haveSimpleName(repository) + .should() + .onlyHaveDependentClassesThat() + .haveSimpleName(persistenceService) + .orShould() + .haveSimpleName(repository) + .orShould() + .haveSimpleName(validationService); rule.check(importedClasses); } @ParameterizedTest - @ValueSource(strings = { "controller", "service", "mapper", "repository", "dto", "exception" }) + @ValueSource(strings = {"controller", "service", "mapper", "repository", "dto", "exception"}) void classesInRightPackages(String passedName) { JavaClasses importedClasses = new ClassFileImporter().importPackages("ch.puzzle.okr"); - ArchRule rule = classes().that().haveSimpleNameEndingWith(StringUtils.capitalize(passedName)).and() - .areTopLevelClasses().should().resideInAPackage("ch.puzzle.okr." + passedName + ".."); + ArchRule rule = classes().that() + .haveSimpleNameEndingWith(StringUtils.capitalize(passedName)) + .and() + .areTopLevelClasses() + .should() + .resideInAPackage("ch.puzzle.okr." + passedName + ".."); rule.check(importedClasses); } @@ -134,28 +188,44 @@ void classesInRightPackages(String passedName) { void serviceLayerCheck() { JavaClasses importedClasses = getMainSourceClasses(); Architectures.LayeredArchitecture layeredArchitecture = layeredArchitecture().consideringAllDependencies() // - .layer("Controller").definedBy("..controller..") // - .layer("AuthorizationService").definedBy("..service.authorization..") // - .layer("BusinessService").definedBy("..service.business..") // - .layer("ValidationService").definedBy("..service.validation..") // - .layer("PersistenceService").definedBy("..service.persistence..") // - .layer("Repository").definedBy("..repository..") // - .layer("Mapper").definedBy("..mapper..") // - - .whereLayer("Controller").mayNotBeAccessedByAnyLayer() // - .whereLayer("AuthorizationService").mayOnlyBeAccessedByLayers("Controller") // - .whereLayer("BusinessService") - .mayOnlyBeAccessedByLayers("Controller", "AuthorizationService", "Mapper", "BusinessService") // - .whereLayer("ValidationService").mayOnlyBeAccessedByLayers("BusinessService") // - .whereLayer("PersistenceService") - .mayOnlyBeAccessedByLayers("BusinessService", "PersistenceService", "ValidationService") // - .whereLayer("Repository").mayOnlyBeAccessedByLayers("PersistenceService"); // + .layer("Controller") + .definedBy("..controller..") // + .layer("AuthorizationService") + .definedBy("..service.authorization..") // + .layer("BusinessService") + .definedBy("..service.business..") // + .layer("ValidationService") + .definedBy("..service.validation..") // + .layer("PersistenceService") + .definedBy("..service.persistence..") // + .layer("Repository") + .definedBy("..repository..") // + .layer("Mapper") + .definedBy("..mapper..") // + + .whereLayer("Controller") + .mayNotBeAccessedByAnyLayer() // + .whereLayer("AuthorizationService") + .mayOnlyBeAccessedByLayers("Controller") // + .whereLayer("BusinessService") + .mayOnlyBeAccessedByLayers("Controller", + "AuthorizationService", + "Mapper", + "BusinessService") // + .whereLayer("ValidationService") + .mayOnlyBeAccessedByLayers("BusinessService") // + .whereLayer("PersistenceService") + .mayOnlyBeAccessedByLayers("BusinessService", + "PersistenceService", + "ValidationService") // + .whereLayer("Repository") + .mayOnlyBeAccessedByLayers("PersistenceService"); // layeredArchitecture.check(importedClasses); } private static JavaClasses getMainSourceClasses() { return new ClassFileImporter().withImportOption(new ImportOption.DoNotIncludeTests()) - .importPackages("ch.puzzle.okr"); + .importPackages("ch.puzzle.okr"); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/ActionControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/ActionControllerIT.java index f7fececa04..1d46989dba 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/ActionControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/ActionControllerIT.java @@ -1,9 +1,16 @@ package ch.puzzle.okr.controller; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; + import ch.puzzle.okr.mapper.ActionMapper; import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.authorization.ActionAuthorizationService; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -20,14 +27,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(ActionController.class) @@ -74,16 +73,25 @@ class ActionControllerIT { @BeforeEach void setUp() { - Action action = Action.Builder.builder().withId(3L).withAction("Neues Haus").withPriority(1).withIsChecked(true) - .withKeyResult(KeyResultMetric.Builder.builder().withId(10L).withTitle("KR Title").build()).build(); + Action action = Action.Builder.builder() + .withId(3L) + .withAction("Neues Haus") + .withPriority(1) + .withIsChecked(true) + .withKeyResult(KeyResultMetric.Builder.builder() + .withId(10L) + .withTitle("KR Title") + .build()) + .build(); BDDMockito.given(actionMapper.toActions(any())).willReturn(List.of(action, action)); } @Test void updateSuccessfulActions() throws Exception { - mvc.perform(put(BASEURL).content(SUCCESSFUL_UPDATE_BODY).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); + mvc.perform(put(BASEURL).content(SUCCESSFUL_UPDATE_BODY) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); verify(actionMapper, times(1)).toActions(any()); verify(actionAuthorizationService, times(1)).updateEntities(any()); @@ -91,9 +99,10 @@ void updateSuccessfulActions() throws Exception { @Test void updateSuccessfulOnlyOneAction() throws Exception { - mvc.perform(put(BASEURL).content(SUCCESSFUL_UPDATE_BODY_SINGLE_ACTION).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); + mvc.perform(put(BASEURL).content(SUCCESSFUL_UPDATE_BODY_SINGLE_ACTION) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); verify(actionMapper, times(1)).toActions(any()); verify(actionAuthorizationService, times(1)).updateEntities(any()); @@ -102,15 +111,16 @@ void updateSuccessfulOnlyOneAction() throws Exception { @Test void shouldDeleteAction() throws Exception { mvc.perform(delete("/api/v2/action/1").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void throwExceptionWhenActionWithIdCantBeFoundWhileDeleting() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Action not found")).when(actionAuthorizationService) - .deleteActionByActionId(anyLong()); + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, + "Action not found")).when(actionAuthorizationService) + .deleteActionByActionId(anyLong()); mvc.perform(delete("/api/v2/action/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/AlignmentControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/AlignmentControllerIT.java index c0372930db..b5694e423a 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/AlignmentControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/AlignmentControllerIT.java @@ -1,9 +1,16 @@ package ch.puzzle.okr.controller; +import static org.mockito.ArgumentMatchers.any; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + import ch.puzzle.okr.mapper.AlignmentSelectionMapper; import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.models.alignment.AlignmentSelectionId; import ch.puzzle.okr.service.business.AlignmentSelectionBusinessService; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.Test; @@ -19,14 +26,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(AlignmentController.class) @@ -39,22 +38,47 @@ class AlignmentControllerIT { private AlignmentSelectionMapper alignmentSelectionMapper; static String alignmentObjectiveName = "Objective 5"; - static List alignmentSelectionPuzzle = List.of( - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(1L, 20L)) - .withObjectiveTitle("Objective 1").withKeyResultTitle("KeyResult 20").build(), - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(1L, 40L)) - .withObjectiveTitle("Objective 1").withKeyResultTitle("KeyResult 40").build()); - static List alignmentSelectionOKR = List.of( - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(5L, 21L)) - .withObjectiveTitle(alignmentObjectiveName).withKeyResultTitle("KeyResult 21").build(), - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(5L, 41L)) - .withObjectiveTitle(alignmentObjectiveName).withKeyResultTitle("KeyResult 41").build(), - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(5L, 61L)) - .withObjectiveTitle(alignmentObjectiveName).withKeyResultTitle("KeyResult 61").build(), - AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(5L, 81L)) - .withObjectiveTitle(alignmentObjectiveName).withKeyResultTitle("KeyResult 81").build()); + static List alignmentSelectionPuzzle = List.of(AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(1L, + 20L)) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("KeyResult 20") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(1L, + 40L)) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("KeyResult 40") + .build()); + static List alignmentSelectionOKR = List.of(AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(5L, + 21L)) + .withObjectiveTitle(alignmentObjectiveName) + .withKeyResultTitle("KeyResult 21") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(5L, + 41L)) + .withObjectiveTitle(alignmentObjectiveName) + .withKeyResultTitle("KeyResult 41") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(5L, + 61L)) + .withObjectiveTitle(alignmentObjectiveName) + .withKeyResultTitle("KeyResult 61") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(5L, + 81L)) + .withObjectiveTitle(alignmentObjectiveName) + .withKeyResultTitle("KeyResult 81") + .build()); static AlignmentSelection alignmentSelectionEmptyKeyResults = AlignmentSelection.Builder.builder() - .withAlignmentSelectionId(AlignmentSelectionId.of(8L, null)).withObjectiveTitle("Objective 8").build(); + .withAlignmentSelectionId(AlignmentSelectionId.of(8L, + null)) + .withObjectiveTitle("Objective 8") + .build(); @Test void shouldGetAllObjectivesWithKeyResults() throws Exception { @@ -63,35 +87,42 @@ void shouldGetAllObjectivesWithKeyResults() throws Exception { alignmentSelections.addAll(alignmentSelectionOKR); alignmentSelections.add(alignmentSelectionEmptyKeyResults); BDDMockito.given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, 4L)) - .willReturn(alignmentSelections); + .willReturn(alignmentSelections); mvc.perform(get("/api/v2/alignments/selections?quarter=2&team=4").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(3))) - .andExpect(jsonPath("$[0].id", Is.is(1))).andExpect(jsonPath("$[0].keyResults[0].id", Is.is(20))) - .andExpect(jsonPath("$[0].keyResults[1].id", Is.is(40))).andExpect(jsonPath("$[1].id", Is.is(5))) - .andExpect(jsonPath("$[1].keyResults[0].id", Is.is(21))) - .andExpect(jsonPath("$[1].keyResults[1].id", Is.is(41))) - .andExpect(jsonPath("$[1].keyResults[2].id", Is.is(61))) - .andExpect(jsonPath("$[1].keyResults[3].id", Is.is(81))).andExpect(jsonPath("$[2].id", Is.is(8))) - .andExpect(jsonPath("$[2].keyResults.size()", Is.is(0))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(3))) + .andExpect(jsonPath("$[0].id", Is.is(1))) + .andExpect(jsonPath("$[0].keyResults[0].id", Is.is(20))) + .andExpect(jsonPath("$[0].keyResults[1].id", Is.is(40))) + .andExpect(jsonPath("$[1].id", Is.is(5))) + .andExpect(jsonPath("$[1].keyResults[0].id", Is.is(21))) + .andExpect(jsonPath("$[1].keyResults[1].id", Is.is(41))) + .andExpect(jsonPath("$[1].keyResults[2].id", Is.is(61))) + .andExpect(jsonPath("$[1].keyResults[3].id", Is.is(81))) + .andExpect(jsonPath("$[2].id", Is.is(8))) + .andExpect(jsonPath("$[2].keyResults.size()", Is.is(0))); } @Test void shouldGetAllObjectivesWithKeyResultsIfAllObjectivesFiltered() throws Exception { BDDMockito.given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(any(), any())) - .willReturn(Collections.emptyList()); + .willReturn(Collections.emptyList()); mvc.perform(get("/api/v2/alignments/selections").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnObjectiveWithEmptyKeyResultListWhenNoKeyResultsInFilteredQuarter() throws Exception { BDDMockito.given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, 4L)) - .willReturn(List.of(alignmentSelectionEmptyKeyResults)); + .willReturn(List.of(alignmentSelectionEmptyKeyResults)); mvc.perform(get("/api/v2/alignments/selections?quarter=2&team=4").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(1))) - .andExpect(jsonPath("$[0].id", Is.is(8))).andExpect(jsonPath("$[0].keyResults.size()", Is.is(0))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(1))) + .andExpect(jsonPath("$[0].id", Is.is(8))) + .andExpect(jsonPath("$[0].keyResults.size()", Is.is(0))); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/CacheControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/CacheControllerIT.java index 6fbe6bc0be..9c4c4d4283 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/CacheControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/CacheControllerIT.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.controller; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; + import ch.puzzle.okr.service.CacheService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -12,10 +16,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(CacheController.class) @@ -27,16 +27,15 @@ class CacheControllerIT { @Test void shouldEmptyAuthorisationUsersCache() throws Exception { - mvc.perform( - post("/api/v2/caches/emptyAuthorizationUsersCache").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); + mvc.perform(post("/api/v2/caches/emptyAuthorizationUsersCache").with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); verify(cacheService, times(1)).emptyAuthorizationUsersCache(); } @Test void shouldEmptyAllCaches() throws Exception { mvc.perform(post("/api/v2/caches/emptyAllCaches").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()); verify(cacheService, times(1)).emptyAllCaches(); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/CheckInControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/CheckInControllerIT.java index cbb63560fb..7349aa51b0 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/CheckInControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/CheckInControllerIT.java @@ -1,12 +1,19 @@ package ch.puzzle.okr.controller; +import static ch.puzzle.okr.test.CheckInTestHelpers.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + import ch.puzzle.okr.mapper.checkin.CheckInMapper; import ch.puzzle.okr.models.checkin.Zone; +import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; -import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.service.authorization.CheckInAuthorizationService; import ch.puzzle.okr.service.business.KeyResultBusinessService; +import java.time.LocalDateTime; import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -25,14 +32,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; - -import static ch.puzzle.okr.test.CheckInTestHelpers.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(CheckInController.class) @@ -57,13 +56,14 @@ void shouldGetMetricCheckInWithId() throws Exception { BDDMockito.given(checkInAuthorizationService.getEntityById(anyLong())).willReturn(checkInMetric); mvc.perform(get(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_INITIATIVES, Is.is(INITIATIVES_1))) - .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))) - .andExpect(jsonPath(JSON_PATH_MODIFIED_ON, Is.is(LocalDateTime.MAX.toString()))) - .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(LocalDateTime.MAX.toString()))) - .andExpect(jsonPath(JSON_PATH_VALUE, Is.is(46D))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_INITIATIVES, Is.is(INITIATIVES_1))) + .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))) + .andExpect(jsonPath(JSON_PATH_MODIFIED_ON, Is.is(LocalDateTime.MAX.toString()))) + .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(LocalDateTime.MAX.toString()))) + .andExpect(jsonPath(JSON_PATH_VALUE, Is.is(46D))); } @Test @@ -71,94 +71,103 @@ void shouldGetOrdinalCheckInWithId() throws Exception { BDDMockito.given(checkInAuthorizationService.getEntityById(anyLong())).willReturn(checkInOrdinal); mvc.perform(get(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_ID, Is.is(4))) - .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_2))) - .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(2))) - .andExpect(jsonPath(JSON_PATH_MODIFIED_ON, Is.is(LocalDateTime.MAX.toString()))) - .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(LocalDateTime.MAX.toString()))) - .andExpect(jsonPath(JSON_PATH_ZONE, Is.is(Zone.COMMIT.toString()))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(4))) + .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_2))) + .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(2))) + .andExpect(jsonPath(JSON_PATH_MODIFIED_ON, Is.is(LocalDateTime.MAX.toString()))) + .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(LocalDateTime.MAX.toString()))) + .andExpect(jsonPath(JSON_PATH_ZONE, Is.is(Zone.COMMIT.toString()))); } @Test void shouldNotFindTheCheckInWithId() throws Exception { BDDMockito.given(checkInAuthorizationService.getEntityById(anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); mvc.perform(get(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void shouldReturnUpdatedCheckIn() throws Exception { BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); + .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); BDDMockito.given(checkInAuthorizationService.updateEntity(anyLong(), any())).willReturn(checkInMetric); BDDMockito.given(checkInMapper.toCheckIn(any())).willReturn(checkInMetric); mvc.perform(put(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_1))) - .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_1))) - .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_1))) + .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_1))) + .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))); } @Test void shouldReturnNotFound() throws Exception { BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); + .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); BDDMockito.given(checkInMapper.toCheckIn(any())).willReturn(checkInMetric); BDDMockito.given(checkInAuthorizationService.updateEntity(anyLong(), any())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found")); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found")); mvc.perform(put(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void shouldCreateKeyResultMetric() throws Exception { BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); + .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); BDDMockito.given(checkInAuthorizationService.createEntity(any())).willReturn(checkInMetric); mvc.perform(post(CHECK_IN_BASE_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_1))) - .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_1))) - .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))) - .andExpect(jsonPath(JSON_PATH_VALUE, Is.is(46D))); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_1))) + .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_1))) + .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(6))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(1))) + .andExpect(jsonPath(JSON_PATH_VALUE, Is.is(46D))); } @Test void shouldCreateKeyResultOrdinal() throws Exception { BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(KeyResultOrdinal.Builder.builder().withId(1L).build()); + .willReturn(KeyResultOrdinal.Builder.builder().withId(1L).build()); BDDMockito.given(checkInAuthorizationService.createEntity(any())).willReturn(checkInOrdinal); mvc.perform(post(CHECK_IN_BASE_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(4))) - .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_2))) - .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_2))) - .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(2))) - .andExpect(jsonPath(JSON_PATH_ZONE, Is.is(Zone.COMMIT.toString()))); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(4))) + .andExpect(jsonPath(JSON_PATH_CHANGE_INFO, Is.is(CHANGE_INFO_2))) + .andExpect(jsonPath(JSON_PATH_INITIATIVES, Is.is(INITIATIVES_2))) + .andExpect(jsonPath(JSON_PATH_CONFIDENCE, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_ID, Is.is(2))) + .andExpect(jsonPath(JSON_PATH_ZONE, Is.is(Zone.COMMIT.toString()))); } @Test void shouldThrowExceptionWhenKeyResultIdMissing() throws Exception { BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); + .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); BDDMockito.given(checkInAuthorizationService.createEntity(any())).willReturn(checkInOrdinal); mvc.perform(post(CHECK_IN_BASE_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON_WITHOUT_KEY_RESULT_ID)) - .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON_WITHOUT_KEY_RESULT_ID)) + .andExpect(MockMvcResultMatchers.status().is4xxClientError()); } @DisplayName("Should return client error for KeyResult not of type metric or ordinal") @@ -168,16 +177,17 @@ class NonMetricOrOrdinalKeyResult extends KeyResult { } BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) - .willReturn(new NonMetricOrOrdinalKeyResult()); + .willReturn(new NonMetricOrOrdinalKeyResult()); mvc.perform(post(CHECK_IN_BASE_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status().is4xxClientError()); } @Test void shouldDeleteCheckInById() throws Exception { mvc.perform(delete(CHECK_IN_5_URL).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/ClientConfigControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/ClientConfigControllerIT.java index f60eb9ede4..b4b939cd77 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/ClientConfigControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/ClientConfigControllerIT.java @@ -1,7 +1,13 @@ package ch.puzzle.okr.controller; +import static ch.puzzle.okr.controller.OverviewControllerIT.JSON_PATH_ROOT; +import static org.mockito.ArgumentMatchers.anyString; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + import ch.puzzle.okr.dto.ClientConfigDto; import ch.puzzle.okr.service.clientconfig.ClientConfigService; +import java.util.Map; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -15,13 +21,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import java.util.Map; - -import static ch.puzzle.okr.controller.OverviewControllerIT.JSON_PATH_ROOT; -import static org.mockito.ArgumentMatchers.anyString; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(ClientConfigController.class) @@ -37,25 +36,33 @@ void shouldGetClientConfig() throws Exception { BDDMockito.given(configService.getConfigBasedOnActiveEnv(anyString())).willReturn(createClientConfigDto()); mvc.perform(get("/config").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.aMapWithSize(10))) - .andExpect(jsonPath("$.activeProfile", Matchers.is("Active_Profile"))) - .andExpect(jsonPath("$.issuer", Matchers.is("Issuer"))) - .andExpect(jsonPath("$.clientId", Matchers.is("Client_Id"))) - .andExpect(jsonPath("$.favicon", Matchers.is("Favicon"))) - .andExpect(jsonPath("$.logo", Matchers.is("Logo"))) - .andExpect(jsonPath("$.triangles", Matchers.is("Triangles"))) - .andExpect(jsonPath("$.backgroundLogo", Matchers.is("Background_Logo"))) - .andExpect(jsonPath("$.title", Matchers.is("Title"))) - .andExpect(jsonPath("$.helpSiteUrl", Matchers.is("helpSiteUrl"))) - .andExpect(jsonPath("$.customStyles.font-family", Matchers.is("verdana"))) - .andExpect(jsonPath("$.customStyles.font-size", Matchers.is("20px"))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.aMapWithSize(10))) + .andExpect(jsonPath("$.activeProfile", Matchers.is("Active_Profile"))) + .andExpect(jsonPath("$.issuer", Matchers.is("Issuer"))) + .andExpect(jsonPath("$.clientId", Matchers.is("Client_Id"))) + .andExpect(jsonPath("$.favicon", Matchers.is("Favicon"))) + .andExpect(jsonPath("$.logo", Matchers.is("Logo"))) + .andExpect(jsonPath("$.triangles", Matchers.is("Triangles"))) + .andExpect(jsonPath("$.backgroundLogo", Matchers.is("Background_Logo"))) + .andExpect(jsonPath("$.title", Matchers.is("Title"))) + .andExpect(jsonPath("$.helpSiteUrl", Matchers.is("helpSiteUrl"))) + .andExpect(jsonPath("$.customStyles.font-family", Matchers.is("verdana"))) + .andExpect(jsonPath("$.customStyles.font-size", Matchers.is("20px"))); } private ClientConfigDto createClientConfigDto() { Map customStyles = Map.of("font-family", "verdana", "font-size", "20px"); - return new ClientConfigDto("Active_Profile", "Issuer", "Client_Id", "Favicon", "Logo", "Triangles", - "Background_Logo", "Title", "helpSiteUrl", customStyles); + return new ClientConfigDto("Active_Profile", + "Issuer", + "Client_Id", + "Favicon", + "Logo", + "Triangles", + "Background_Logo", + "Title", + "helpSiteUrl", + customStyles); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/CompletedControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/CompletedControllerIT.java index 4f2c00353c..098ddf9996 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/CompletedControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/CompletedControllerIT.java @@ -1,5 +1,13 @@ package ch.puzzle.okr.controller; +import static ch.puzzle.okr.test.KeyResultTestHelpers.JSON_PATH_ID; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doThrow; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + import ch.puzzle.okr.dto.CompletedDto; import ch.puzzle.okr.mapper.CompletedMapper; import ch.puzzle.okr.models.Completed; @@ -25,14 +33,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import static ch.puzzle.okr.test.KeyResultTestHelpers.JSON_PATH_ID; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.doThrow; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(CompletedController.class) @@ -57,20 +57,20 @@ class CompletedControllerIT { private CompletedMapper completedMapper; private final Completed successfulCompleted = Completed.Builder.builder() // - .withId(COMPLETED_ID) // - .withObjective(Objective.Builder.builder() // - .withId(OBJECTIVE_ID) // - .build()) // - .withComment(COMPLETED_COMMENT) // - .build(); + .withId(COMPLETED_ID) // + .withObjective(Objective.Builder.builder() // + .withId(OBJECTIVE_ID) // + .build()) // + .withComment(COMPLETED_COMMENT) // + .build(); private final CompletedDto completedDto = CompletedDtoBuilder.builder() // - .withId(COMPLETED_ID) // - .withComment(COMPLETED_COMMENT) // - .withObjectiveDto(ObjectiveDtoBuilder.builder() // - .withId(OBJECTIVE_ID) // - .build()) // - .build(); + .withId(COMPLETED_ID) // + .withComment(COMPLETED_COMMENT) // + .withObjectiveDto(ObjectiveDtoBuilder.builder() // + .withId(OBJECTIVE_ID) // + .build()) // + .build(); String baseUrl = "/api/v2/completed"; @Autowired @@ -88,30 +88,31 @@ void createShouldCreateCompleted() throws Exception { BDDMockito.given(this.completedAuthorizationService.createCompleted(any())).willReturn(successfulCompleted); mvc.perform(post(baseUrl) // - .content(SUCCESSFUL_CREATE_BODY) // - .contentType(MediaType.APPLICATION_JSON) // - .with(SecurityMockMvcRequestPostProcessors.csrf())) // - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) // - .andExpect(jsonPath(JSON_PATH_ID, Is.is(COMPLETED_ID_AS_INT))) // - .andExpect(jsonPath("$.id", Is.is(COMPLETED_ID_AS_INT))) // - .andExpect(jsonPath("$.objective.id", Is.is(OBJECTIVE_ID_AS_INT))) // - .andExpect(jsonPath("$.comment", Is.is(COMPLETED_COMMENT))); + .content(SUCCESSFUL_CREATE_BODY) // + .contentType(MediaType.APPLICATION_JSON) // + .with(SecurityMockMvcRequestPostProcessors.csrf())) // + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) // + .andExpect(jsonPath(JSON_PATH_ID, Is.is(COMPLETED_ID_AS_INT))) // + .andExpect(jsonPath("$.id", Is.is(COMPLETED_ID_AS_INT))) // + .andExpect(jsonPath("$.objective.id", Is.is(OBJECTIVE_ID_AS_INT))) // + .andExpect(jsonPath("$.comment", Is.is(COMPLETED_COMMENT))); } @DisplayName("delete() should delete Completed") @Test void deleteShouldDeleteCompleted() throws Exception { mvc.perform(delete("/api/v2/completed/1").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); } @DisplayName("delete() should throw exception when Completed with id cant be found") @Test void deleteShouldThrowExceptionWhenCompletedWithIdCantBeFound() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Completed not found")) - .when(completedAuthorizationService).deleteCompletedByObjectiveId(anyLong()); + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, + "Completed not found")).when(completedAuthorizationService) + .deleteCompletedByObjectiveId(anyLong()); mvc.perform(delete("/api/v2/completed/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/KeyResultControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/KeyResultControllerIT.java index ae97be5da3..b5d0f3886c 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/KeyResultControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/KeyResultControllerIT.java @@ -1,5 +1,15 @@ package ch.puzzle.okr.controller; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; +import static ch.puzzle.okr.test.KeyResultTestHelpers.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import ch.puzzle.okr.mapper.ActionMapper; import ch.puzzle.okr.mapper.checkin.CheckInMapper; import ch.puzzle.okr.mapper.keyresult.KeyResultMapper; @@ -10,6 +20,9 @@ import ch.puzzle.okr.service.authorization.KeyResultAuthorizationService; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.service.persistence.UserPersistenceService; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; @@ -28,20 +41,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; -import static ch.puzzle.okr.test.KeyResultTestHelpers.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(KeyResultController.class) @@ -76,18 +75,19 @@ void shouldGetMetricKeyResultWithId() throws Exception { BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultMetricDto); mvc.perform(get(URL_TO_KEY_RESULT_1).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(1))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) - .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) - .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_ID_LAST_CHECK_IN_VALUE, Is.is(4.0))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) - .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(1))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) + .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) + .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_ID_LAST_CHECK_IN_VALUE, Is.is(4.0))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) + .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))); } @Test @@ -96,28 +96,30 @@ void shouldGetOrdinalKeyResultWithId() throws Exception { BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultOrdinalDto); mvc.perform(get(URL_TO_KEY_RESULT_1).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_QUARTER_LABEL, Is.is(QUARTER_LABEL))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ZONE, Is.is(LAST_CHECK_IN_ZONE.toString()))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) - .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))) - .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) - .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_QUARTER_LABEL, Is.is(QUARTER_LABEL))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ZONE, Is.is(LAST_CHECK_IN_ZONE.toString()))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) + .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))) + .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) + .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))); } @Test void shouldNotFindTheKeyResultWithGivenId() throws Exception { BDDMockito.given(keyResultAuthorizationService.getEntityById(anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "KeyResult with id 55 not found")); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "KeyResult with id 55 not found")); mvc.perform(get(URL_TO_KEY_RESULT_55).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isNotFound()).andExpect(status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()) + .andExpect(status().isNotFound()); } @Test @@ -128,32 +130,38 @@ void shouldReturnCheckInsFromKeyResult() throws Exception { BDDMockito.given(checkInMapper.toDto(checkIn2)).willReturn(checkInDto2); mvc.perform(get(URL_TO_KEY_RESULT_5_CHECK_IN).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(2))) - .andExpect(jsonPath("$[0].id", Is.is(1))).andExpect(jsonPath("$[0].value", Is.is(23.0))) - .andExpect(jsonPath("$[0].keyResultId", Is.is(5))) - .andExpect(jsonPath("$[0].changeInfo", Is.is("Changeinfo1"))) - .andExpect(jsonPath("$[0].initiatives", Is.is("Initiatives1"))).andExpect(jsonPath("$[1].id", Is.is(4))) - .andExpect(jsonPath("$[1].value", Is.is(12.0))).andExpect(jsonPath("$[1].keyResultId", Is.is(5))) - .andExpect(jsonPath("$[1].changeInfo", Is.is("Changeinfo2"))) - .andExpect(jsonPath("$[1].initiatives", Is.is("Initiatives2"))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(2))) + .andExpect(jsonPath("$[0].id", Is.is(1))) + .andExpect(jsonPath("$[0].value", Is.is(23.0))) + .andExpect(jsonPath("$[0].keyResultId", Is.is(5))) + .andExpect(jsonPath("$[0].changeInfo", Is.is("Changeinfo1"))) + .andExpect(jsonPath("$[0].initiatives", Is.is("Initiatives1"))) + .andExpect(jsonPath("$[1].id", Is.is(4))) + .andExpect(jsonPath("$[1].value", Is.is(12.0))) + .andExpect(jsonPath("$[1].keyResultId", Is.is(5))) + .andExpect(jsonPath("$[1].changeInfo", Is.is("Changeinfo2"))) + .andExpect(jsonPath("$[1].initiatives", Is.is("Initiatives2"))); } @Test void shouldGetAllCheckInsIfNoCheckInExistsInKeyResult() throws Exception { BDDMockito.given(keyResultAuthorizationService.getAllCheckInsByKeyResult(anyLong())) - .willReturn(Collections.emptyList()); + .willReturn(Collections.emptyList()); mvc.perform(get(URL_TO_KEY_RESULT_1_CHECK_IN).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnErrorWhenKeyResultDoesntExistWhenGettingCheckInsFromKeyResult() throws Exception { BDDMockito.given(keyResultAuthorizationService.getAllCheckInsByKeyResult(anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "KeyResult with id 1 not found")); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "KeyResult with id 1 not found")); mvc.perform(get(URL_TO_KEY_RESULT_1_CHECK_IN).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isNotFound()).andExpect(status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()) + .andExpect(status().isNotFound()); } @Test @@ -162,20 +170,22 @@ void createMetricKeyResult() throws Exception { BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultMetricDto); BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(metricKeyResult); - mvc.perform(post(URL_BASE).content(CREATE_BODY_METRIC).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) - .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) - .andExpect(jsonPath(JSON_PATH_ID_LAST_CHECK_IN_VALUE, Is.is(4.0))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); + mvc.perform(post(URL_BASE).content(CREATE_BODY_METRIC) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) + .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) + .andExpect(jsonPath(JSON_PATH_ID_LAST_CHECK_IN_VALUE, Is.is(4.0))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); verify(actionMapper, times(1)).toActions(anyList(), any()); verify(actionAuthorizationService, times(1)).createEntities(List.of()); @@ -187,19 +197,21 @@ void createOrdinalKeyResult() throws Exception { BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultOrdinalDto); BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(ordinalKeyResult); - mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) - .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); + mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) + .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); verify(actionMapper, times(1)).toActions(anyList(), any()); verify(actionAuthorizationService, times(1)).createEntities(List.of()); @@ -207,10 +219,20 @@ void createOrdinalKeyResult() throws Exception { @Test void shouldCreateActionsWhenCreatingKeyResult() throws Exception { - Action action1 = Action.Builder.builder().withVersion(1).withAction("Neue Katze").withPriority(0) - .withKeyResult(ordinalKeyResult).withIsChecked(false).build(); - Action action2 = Action.Builder.builder().withVersion(1).withAction("Neuer Hund").withPriority(1) - .withKeyResult(ordinalKeyResult).withIsChecked(false).build(); + Action action1 = Action.Builder.builder() + .withVersion(1) + .withAction("Neue Katze") + .withPriority(0) + .withKeyResult(ordinalKeyResult) + .withIsChecked(false) + .build(); + Action action2 = Action.Builder.builder() + .withVersion(1) + .withAction("Neuer Hund") + .withPriority(1) + .withKeyResult(ordinalKeyResult) + .withIsChecked(false) + .build(); action1.setWriteable(false); action2.setWriteable(false); List actionList = List.of(action1, action2); @@ -220,19 +242,21 @@ void shouldCreateActionsWhenCreatingKeyResult() throws Exception { BDDMockito.given(actionAuthorizationService.createEntities(actionList)).willReturn(actionList); BDDMockito.given(actionMapper.toActions(anyList(), any())).willReturn(actionList); - mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL_ACTION_LIST).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) - .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); + mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL_ACTION_LIST) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) + .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_ZONE, Is.is(STRETCH_ZONE))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_QUARTER_START_DATE, Is.is(START_DATE))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))); verify(actionMapper, times(1)).toActions(anyList(), any()); verify(actionAuthorizationService, times(1)).createEntities(actionList); @@ -240,16 +264,18 @@ void shouldCreateActionsWhenCreatingKeyResult() throws Exception { @Test void shouldThrowExceptionWhenKeyResultTypeMissing() throws Exception { - mvc.perform(post(URL_BASE).content(CREATE_BODY_KEY_RESULT_TYPE_MISSING).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + mvc.perform(post(URL_BASE).content(CREATE_BODY_KEY_RESULT_TYPE_MISSING) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().is4xxClientError()); } @Test void shouldThrowExceptionWhenKeyResultTypeUnknown() throws Exception { - mvc.perform(post(URL_BASE).content(CREATE_BODY_KEY_RESULT_TYPE_UNKNOWN).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + mvc.perform(post(URL_BASE).content(CREATE_BODY_KEY_RESULT_TYPE_UNKNOWN) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().is4xxClientError()); } @Test @@ -258,53 +284,59 @@ void createEntityWithEnumKeys() throws Exception { BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultOrdinalDto); BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(ordinalKeyResult); - mvc.perform(post(URL_BASE).content(CREATE_BODY_WITH_ENUM_KEYS).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ZONE, Is.is(LAST_CHECK_IN_ZONE.toString()))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) - .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))) - .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) - .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))); + mvc.perform(post(URL_BASE).content(CREATE_BODY_WITH_ENUM_KEYS) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) + .andExpect(jsonPath(JSON_PATH_ID, Is.is(5))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_DESCRIPTION, Is.is(DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_ORDINAL))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_STATE, Is.is(OBJECTIVE_STATE_ONGOING))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ZONE, Is.is(LAST_CHECK_IN_ZONE.toString()))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) + .andExpect(jsonPath(JSON_PATH_CREATED_ON, Is.is(KEY_RESULT_CREATED_ON))) + .andExpect(jsonPath(JSON_PATH_COMMIT_ZONE, Is.is(COMMIT_ZONE))) + .andExpect(jsonPath(JSON_PATH_TARGET_ZONE, Is.is(TARGET_ZONE))); } @Test void createEntityShouldThrowErrorWhenInvalidDto() throws Exception { BDDMockito.given(keyResultMapper.toKeyResult(any())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Error")); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Error")); - mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void shouldReturnUpdatedKeyResult() throws Exception { BDDMockito.given(keyResultAuthorizationService.updateEntities(anyLong(), any(), anyList())) - .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); + .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultMetricDto); BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(metricKeyResult); BDDMockito.given(keyResultAuthorizationService.isImUsed(any(), any())).willReturn(false); BDDMockito.given(keyResultAuthorizationService.updateEntities(anyLong(), any(), anyList())) - .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); + .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); BDDMockito.given(actionAuthorizationService.getActionsByKeyResult(any())).willReturn(anyList()); mvc.perform(put(URL_TO_KEY_RESULT_1).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) - .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ID, Is.is(LAST_CHECK_IN_ID))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) - .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))).andReturn(); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) + .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ID, Is.is(LAST_CHECK_IN_ID))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) + .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) + .andReturn(); verify(actionMapper, times(1)).toActions(anyList(), any()); verify(keyResultAuthorizationService, times(1)).updateEntities(anyLong(), any(), anyList()); @@ -313,22 +345,25 @@ void shouldReturnUpdatedKeyResult() throws Exception { @Test void shouldReturnUpdatedKeyResultWithImUsed() throws Exception { BDDMockito.given(keyResultAuthorizationService.updateEntities(anyLong(), any(), anyList())) - .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); + .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); BDDMockito.given(keyResultMapper.toDto(any(), anyList())).willReturn(keyResultMetricDto); BDDMockito.given(keyResultMapper.toKeyResult(any())).willReturn(metricKeyResult); BDDMockito.given(keyResultAuthorizationService.isImUsed(any(), any())).willReturn(true); mvc.perform(put(URL_TO_KEY_RESULT_1).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) - .andExpect(MockMvcResultMatchers.status().isImUsed()).andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))) - .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) - .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) - .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) - .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) - .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ID, Is.is(LAST_CHECK_IN_ID))) - .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) - .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))).andReturn(); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) + .andExpect(MockMvcResultMatchers.status().isImUsed()) + .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))) + .andExpect(jsonPath(JSON_PATH_OWNER_FIRSTNAME, Is.is(FIRSTNAME))) + .andExpect(jsonPath(JSON_PATH_KEY_RESULT_TYPE, Is.is(KEY_RESULT_TYPE_METRIC))) + .andExpect(jsonPath(JSON_PATH_BASELINE, Is.is(BASELINE_VALUE))) + .andExpect(jsonPath(JSON_PATH_STRETCH_GOAL, Is.is(STRETCH_GOAL_VALUE))) + .andExpect(jsonPath(JSON_PATH_OBJECTIVE_ID, Is.is(OBJECTIVE_ID))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_ID, Is.is(LAST_CHECK_IN_ID))) + .andExpect(jsonPath(JSON_PATH_LAST_CHECK_IN_CONFIDENCE, Is.is(CONFIDENCE))) + .andExpect(jsonPath(JSON_PATH_UNIT, Is.is(KEY_RESULT_UNIT.toString()))) + .andReturn(); verify(actionMapper, times(1)).toActions(anyList(), any()); verify(keyResultAuthorizationService, times(1)).updateEntities(anyLong(), any(), anyList()); @@ -336,35 +371,39 @@ void shouldReturnUpdatedKeyResultWithImUsed() throws Exception { @Test void shouldReturnNotFoundWhenUpdatingKeyResult() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Keyresult not found")) - .when(keyResultAuthorizationService).updateEntities(any(), any(), anyList()); - - mvc.perform(put(URL_TO_KEY_RESULT_1000).content(PUT_BODY_METRIC).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, + "Keyresult not found")).when(keyResultAuthorizationService) + .updateEntities(any(), any(), anyList()); + + mvc.perform(put(URL_TO_KEY_RESULT_1000).content(PUT_BODY_METRIC) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void shouldReturnBadRequestWhenUpdatingKeyResult() throws Exception { BDDMockito.given(keyResultAuthorizationService.updateEntity(any(), any())) - .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Bad request while updating keyresult")); + .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, + "Bad request while updating keyresult")); mvc.perform(put(URL_TO_KEY_RESULT_10).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isBadRequest()); + .andExpect(MockMvcResultMatchers.status().isBadRequest()); } @Test void shouldDeleteKeyResult() throws Exception { mvc.perform(delete(URL_TO_KEY_RESULT_10).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void throwExceptionWhenKeyResultWithIdCantBeFoundWhileDeleting() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Keyresult not found")) - .when(keyResultAuthorizationService).deleteEntityById(anyLong()); + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, + "Keyresult not found")).when(keyResultAuthorizationService) + .deleteEntityById(anyLong()); mvc.perform(delete(URL_TO_KEY_RESULT_1000).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/ObjectiveControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/ObjectiveControllerIT.java index c2d0fde2a8..afd386fbb1 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/ObjectiveControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/ObjectiveControllerIT.java @@ -1,10 +1,17 @@ package ch.puzzle.okr.controller; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + import ch.puzzle.okr.dto.ObjectiveDto; import ch.puzzle.okr.mapper.ObjectiveMapper; import ch.puzzle.okr.models.*; import ch.puzzle.okr.service.authorization.AuthorizationService; import ch.puzzle.okr.service.authorization.ObjectiveAuthorizationService; +import java.time.LocalDateTime; import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -23,15 +30,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDate; -import java.time.LocalDateTime; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(ObjectiveController.class) @@ -67,21 +65,53 @@ class ObjectiveControllerIT { private static final String RESPONSE_NEW_OBJECTIVE = """ {"id":null,"version":1,"title":"Program Faster","teamId":1,"quarterId":1,"quarterLabel":"GJ 22/23-Q2","description":"Just be faster","state":"DRAFT","createdOn":null,"modifiedOn":null,"writeable":true}"""; private static final String JSON_PATH_TITLE = "$.title"; - private static final Objective objective1 = Objective.Builder.builder().withId(5L).withTitle(OBJECTIVE_TITLE_1) - .build(); - private static final Objective objective2 = Objective.Builder.builder().withId(7L).withTitle(OBJECTIVE_TITLE_2) - .build(); - private static final User user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); + private static final Objective objective1 = Objective.Builder.builder() + .withId(5L) + .withTitle(OBJECTIVE_TITLE_1) + .build(); + private static final Objective objective2 = Objective.Builder.builder() + .withId(7L) + .withTitle(OBJECTIVE_TITLE_2) + .build(); + private static final User user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); private static final Team team = Team.Builder.builder().withId(1L).withName("Team1").build(); private static final Quarter quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build(); - private static final Objective fullObjective = Objective.Builder.builder().withId(42L).withTitle("FullObjective") - .withCreatedBy(user).withTeam(team).withQuarter(quarter).withDescription(DESCRIPTION) - .withModifiedOn(LocalDateTime.MAX).build(); - private static final ObjectiveDto objective1Dto = new ObjectiveDto(5L, 1, OBJECTIVE_TITLE_1, 1L, 1L, "GJ 22/23-Q2", - DESCRIPTION, State.DRAFT, LocalDateTime.MAX, LocalDateTime.MAX, true); - private static final ObjectiveDto objective2Dto = new ObjectiveDto(7L, 1, OBJECTIVE_TITLE_2, 1L, 1L, "GJ 22/23-Q2", - DESCRIPTION, State.DRAFT, LocalDateTime.MIN, LocalDateTime.MIN, true); + private static final Objective fullObjective = Objective.Builder.builder() + .withId(42L) + .withTitle("FullObjective") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withDescription(DESCRIPTION) + .withModifiedOn(LocalDateTime.MAX) + .build(); + private static final ObjectiveDto objective1Dto = new ObjectiveDto(5L, + 1, + OBJECTIVE_TITLE_1, + 1L, + 1L, + "GJ 22/23-Q2", + DESCRIPTION, + State.DRAFT, + LocalDateTime.MAX, + LocalDateTime.MAX, + true); + private static final ObjectiveDto objective2Dto = new ObjectiveDto(7L, + 1, + OBJECTIVE_TITLE_2, + 1L, + 1L, + "GJ 22/23-Q2", + DESCRIPTION, + State.DRAFT, + LocalDateTime.MIN, + LocalDateTime.MIN, + true); @Autowired private MockMvc mvc; @@ -103,112 +133,159 @@ void getObjectiveById() throws Exception { BDDMockito.given(objectiveAuthorizationService.getEntityById(anyLong())).willReturn(objective1); mvc.perform(get(URL_OBJECTIVE_5).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$.id", Is.is(5))) - .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(OBJECTIVE_TITLE_1))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$.id", Is.is(5))) + .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(OBJECTIVE_TITLE_1))); } @Test void getObjectiveByIdFail() throws Exception { BDDMockito.given(objectiveAuthorizationService.getEntityById(anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); mvc.perform(get(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void shouldReturnObjectiveWhenCreatingNewObjective() throws Exception { - ObjectiveDto testObjective = new ObjectiveDto(null, 1, "Program Faster", 1L, 1L, "GJ 22/23-Q2", - "Just be faster", State.DRAFT, null, null, true); + ObjectiveDto testObjective = new ObjectiveDto(null, + 1, + "Program Faster", + 1L, + 1L, + "GJ 22/23-Q2", + "Just be faster", + State.DRAFT, + null, + null, + true); BDDMockito.given(objectiveMapper.toDto(any())).willReturn(testObjective); BDDMockito.given(objectiveAuthorizationService.createEntity(any())).willReturn(fullObjective); mvc.perform(post(URL_BASE_OBJECTIVE).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(CREATE_NEW_OBJECTIVE)) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) - .andExpect(MockMvcResultMatchers.content().string(RESPONSE_NEW_OBJECTIVE)); + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(CREATE_NEW_OBJECTIVE)) + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) + .andExpect(MockMvcResultMatchers.content().string(RESPONSE_NEW_OBJECTIVE)); verify(objectiveAuthorizationService, times(1)).createEntity(any()); } @Test void shouldReturnResponseStatusExceptionWhenCreatingObjectiveWithNullValues() throws Exception { - BDDMockito.given(objectiveAuthorizationService.createEntity(any())).willThrow( - new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing attribute title when creating objective")); + BDDMockito.given(objectiveAuthorizationService.createEntity(any())) + .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, + "Missing attribute title when creating objective")); mvc.perform(post(URL_BASE_OBJECTIVE).contentType(MediaType.APPLICATION_JSON) - .content(CREATE_NEW_OBJECTIVE_WITH_NULL_VALUES).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isBadRequest()); + .content(CREATE_NEW_OBJECTIVE_WITH_NULL_VALUES) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isBadRequest()); } @Test void shouldReturnUpdatedObjective() throws Exception { - ObjectiveDto testObjective = new ObjectiveDto(1L, 1, TITLE, 1L, 1L, "GJ 22/23-Q2", EVERYTHING_FINE_DESCRIPTION, - State.NOTSUCCESSFUL, LocalDateTime.MIN, LocalDateTime.MAX, true); - Objective objective = Objective.Builder.builder().withId(1L).withDescription(EVERYTHING_FINE_DESCRIPTION) - .withTitle(TITLE).build(); + ObjectiveDto testObjective = new ObjectiveDto(1L, + 1, + TITLE, + 1L, + 1L, + "GJ 22/23-Q2", + EVERYTHING_FINE_DESCRIPTION, + State.NOTSUCCESSFUL, + LocalDateTime.MIN, + LocalDateTime.MAX, + true); + Objective objective = Objective.Builder.builder() + .withId(1L) + .withDescription(EVERYTHING_FINE_DESCRIPTION) + .withTitle(TITLE) + .build(); BDDMockito.given(objectiveMapper.toDto(any())).willReturn(testObjective); BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())).willReturn(objective); BDDMockito.given(objectiveAuthorizationService.isImUsed(any())).willReturn(false); - mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON).content(JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath("$.id", Is.is(1))) - .andExpect(jsonPath("$.description", Is.is(EVERYTHING_FINE_DESCRIPTION))) - .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))); + mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON) + .content(JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$.id", Is.is(1))) + .andExpect(jsonPath("$.description", Is.is(EVERYTHING_FINE_DESCRIPTION))) + .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(TITLE))); } @Test void shouldReturnImUsed() throws Exception { - ObjectiveDto testObjectiveDto = new ObjectiveDto(1L, 1, TITLE, 1L, 1L, "GJ 22/23-Q2", - EVERYTHING_FINE_DESCRIPTION, State.SUCCESSFUL, LocalDateTime.MAX, LocalDateTime.MAX, true); - Objective objectiveImUsed = Objective.Builder.builder().withId(1L).withDescription(EVERYTHING_FINE_DESCRIPTION) - .withQuarter(Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build()).withTitle(TITLE) - .build(); + ObjectiveDto testObjectiveDto = new ObjectiveDto(1L, + 1, + TITLE, + 1L, + 1L, + "GJ 22/23-Q2", + EVERYTHING_FINE_DESCRIPTION, + State.SUCCESSFUL, + LocalDateTime.MAX, + LocalDateTime.MAX, + true); + Objective objectiveImUsed = Objective.Builder.builder() + .withId(1L) + .withDescription(EVERYTHING_FINE_DESCRIPTION) + .withQuarter(Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .build()) + .withTitle(TITLE) + .build(); BDDMockito.given(objectiveMapper.toObjective(any())).willReturn(objectiveImUsed); BDDMockito.given(objectiveMapper.toDto(any())).willReturn(testObjectiveDto); BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())).willReturn(objectiveImUsed); BDDMockito.given(objectiveAuthorizationService.isImUsed(any())).willReturn(true); - mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON).content(JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isImUsed()); + mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON) + .content(JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isImUsed()); } @Test void shouldReturnNotFound() throws Exception { - BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())).willThrow( - new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed objective -> Attribut is invalid")); + BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())) + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, + "Failed objective -> Attribut is invalid")); - mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON).content(JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON) + .content(JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void shouldReturnBadRequest() throws Exception { - BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())).willThrow( - new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed objective -> Attribut is invalid")); + BDDMockito.given(objectiveAuthorizationService.updateEntity(anyLong(), any())) + .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, + "Failed objective -> Attribut is invalid")); mvc.perform(put(URL_OBJECTIVE_10).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isBadRequest()); + .andExpect(MockMvcResultMatchers.status().isBadRequest()); } @Test void shouldDeleteObjective() throws Exception { mvc.perform(delete(URL_OBJECTIVE_10).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void throwExceptionWhenObjectiveWithIdCantBeFoundWhileDeleting() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Objective not found")) - .when(objectiveAuthorizationService).deleteEntityById(anyLong()); + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, + "Objective not found")).when(objectiveAuthorizationService) + .deleteEntityById(anyLong()); mvc.perform(delete("/api/v2/objectives/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test @@ -217,12 +294,14 @@ void shouldReturnIsCreatedWhenObjectiveWasDuplicated() throws Exception { BDDMockito.given(objectiveAuthorizationService.getAuthorizationService()).willReturn(authorizationService); BDDMockito.given(objectiveMapper.toDto(objective1)).willReturn(objective1Dto); - mvc.perform(post("/api/v2/objectives/{id}", objective1.getId()).contentType(MediaType.APPLICATION_JSON) - .content(JSON).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isCreated()) - .andExpect(jsonPath("$.id", Is.is(objective1Dto.id().intValue()))) - .andExpect(jsonPath("$.description", Is.is(objective1Dto.description()))) - .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(objective1Dto.title()))); + mvc.perform(post("/api/v2/objectives/{id}", + objective1.getId()).contentType(MediaType.APPLICATION_JSON) + .content(JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andExpect(jsonPath("$.id", Is.is(objective1Dto.id().intValue()))) + .andExpect(jsonPath("$.description", Is.is(objective1Dto.description()))) + .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(objective1Dto.title()))); verify(objectiveMapper, times(1)).toObjective(any()); verify(objectiveMapper, times(1)).toDto(any()); diff --git a/backend/src/test/java/ch/puzzle/okr/controller/OverviewControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/OverviewControllerIT.java index 48b57a8ede..899c8a62f1 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/OverviewControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/OverviewControllerIT.java @@ -1,9 +1,20 @@ package ch.puzzle.okr.controller; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; +import static ch.puzzle.okr.models.State.DRAFT; +import static ch.puzzle.okr.models.State.ONGOING; +import static org.mockito.ArgumentMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + import ch.puzzle.okr.mapper.OverviewMapper; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.models.overview.OverviewId; import ch.puzzle.okr.service.authorization.OverviewAuthorizationService; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.Test; @@ -19,18 +30,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; -import static ch.puzzle.okr.models.State.DRAFT; -import static ch.puzzle.okr.models.State.ONGOING; -import static org.mockito.ArgumentMatchers.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(OverviewController.class) @@ -54,37 +53,92 @@ class OverviewControllerIT { public static final String JSON_PATH_TEAM_ID = "$[0].team.id"; public static final String JSON_PATH_ROOT = "$"; - static List overviewPuzzle = List.of( - Overview.Builder.builder().withOverviewId(OverviewId.of(1L, 1L, 20L, 20L)).withTeamName(PUZZLE) - .withObjectiveTitle("Objective 1").withObjectiveState(DRAFT).withQuarterId(1L) - .withQuarterLabel(QUARTER_LABEL).withKeyResultTitle(DESCRIPTION) - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withUnit(CHF).withBaseline(5.0).withStretchGoal(20.0) - .withCheckInValue(15.0).withConfidence(5).withCheckInCreatedOn(LocalDateTime.now()).build(), - Overview.Builder.builder().withOverviewId(OverviewId.of(1L, 2L, 21L, 41L)).withTeamName(PUZZLE) - .withObjectiveTitle("Objective 1").withObjectiveState(DRAFT).withQuarterId(1L) - .withQuarterLabel(QUARTER_LABEL).withKeyResultTitle(DESCRIPTION) - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withUnit(EUR).withBaseline(5.0).withStretchGoal(20.0) - .withCheckInValue(15.0).withConfidence(5).withCheckInCreatedOn(LocalDateTime.now()).build()); - static List overviewOKR = List.of( - Overview.Builder.builder().withOverviewId(OverviewId.of(2L, 5L, 20L, 40L)).withTeamName("OKR") - .withObjectiveTitle("Objective 5").withObjectiveState(DRAFT).withQuarterId(1L) - .withQuarterLabel(QUARTER_LABEL).withKeyResultTitle(DESCRIPTION) - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withUnit(CHF).withBaseline(5.0).withStretchGoal(20.0) - .withCheckInValue(15.0).withConfidence(5).withCheckInCreatedOn(LocalDateTime.now()).build(), - Overview.Builder.builder().withOverviewId(OverviewId.of(2L, 7L, 21L, 41L)).withTeamName("OKR") - .withObjectiveTitle("Objective 7").withObjectiveState(ONGOING).withQuarterId(1L) - .withQuarterLabel(QUARTER_LABEL).withKeyResultTitle(DESCRIPTION) - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withUnit(FTE).withBaseline(5.0).withStretchGoal(20.0) - .withCheckInValue(15.0).withConfidence(5).withCheckInCreatedOn(LocalDateTime.now()).build()); - - static Overview overviewKuchen = Overview.Builder.builder().withOverviewId(OverviewId.of(3L, 8L, 20L, 40L)) - .withTeamName(TEAM_KUCHEN).withObjectiveTitle("Objective 8").withObjectiveState(ONGOING).withQuarterId(1L) - .withQuarterLabel(QUARTER_LABEL).withKeyResultTitle(DESCRIPTION).withKeyResultType(KEY_RESULT_TYPE_METRIC) - .withUnit(EUR).withBaseline(5.0).withStretchGoal(20.0).withCheckInValue(15.0).withConfidence(5) - .withCheckInCreatedOn(LocalDateTime.now()).build(); - - static Overview simpleOverview = Overview.Builder.builder().withOverviewId(OverviewId.of(4L, -1L, -1L, -1L)) - .withTeamName(TEAM_KUCHEN).build(); + static List overviewPuzzle = List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.of(1L, 1L, 20L, 20L)) + .withTeamName(PUZZLE) + .withObjectiveTitle("Objective 1") + .withObjectiveState(DRAFT) + .withQuarterId(1L) + .withQuarterLabel(QUARTER_LABEL) + .withKeyResultTitle(DESCRIPTION) + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withUnit(CHF) + .withBaseline(5.0) + .withStretchGoal(20.0) + .withCheckInValue(15.0) + .withConfidence(5) + .withCheckInCreatedOn(LocalDateTime.now()) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.of(1L, 2L, 21L, 41L)) + .withTeamName(PUZZLE) + .withObjectiveTitle("Objective 1") + .withObjectiveState(DRAFT) + .withQuarterId(1L) + .withQuarterLabel(QUARTER_LABEL) + .withKeyResultTitle(DESCRIPTION) + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withUnit(EUR) + .withBaseline(5.0) + .withStretchGoal(20.0) + .withCheckInValue(15.0) + .withConfidence(5) + .withCheckInCreatedOn(LocalDateTime.now()) + .build()); + static List overviewOKR = List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.of(2L, 5L, 20L, 40L)) + .withTeamName("OKR") + .withObjectiveTitle("Objective 5") + .withObjectiveState(DRAFT) + .withQuarterId(1L) + .withQuarterLabel(QUARTER_LABEL) + .withKeyResultTitle(DESCRIPTION) + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withUnit(CHF) + .withBaseline(5.0) + .withStretchGoal(20.0) + .withCheckInValue(15.0) + .withConfidence(5) + .withCheckInCreatedOn(LocalDateTime.now()) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.of(2L, 7L, 21L, 41L)) + .withTeamName("OKR") + .withObjectiveTitle("Objective 7") + .withObjectiveState(ONGOING) + .withQuarterId(1L) + .withQuarterLabel(QUARTER_LABEL) + .withKeyResultTitle(DESCRIPTION) + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withUnit(FTE) + .withBaseline(5.0) + .withStretchGoal(20.0) + .withCheckInValue(15.0) + .withConfidence(5) + .withCheckInCreatedOn(LocalDateTime.now()) + .build()); + + static Overview overviewKuchen = Overview.Builder.builder() + .withOverviewId(OverviewId.of(3L, 8L, 20L, 40L)) + .withTeamName(TEAM_KUCHEN) + .withObjectiveTitle("Objective 8") + .withObjectiveState(ONGOING) + .withQuarterId(1L) + .withQuarterLabel(QUARTER_LABEL) + .withKeyResultTitle(DESCRIPTION) + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withUnit(EUR) + .withBaseline(5.0) + .withStretchGoal(20.0) + .withCheckInValue(15.0) + .withConfidence(5) + .withCheckInCreatedOn(LocalDateTime.now()) + .build(); + + static Overview simpleOverview = Overview.Builder.builder() + .withOverviewId(OverviewId.of(4L, -1L, -1L, -1L)) + .withTeamName(TEAM_KUCHEN) + .build(); @Test void shouldGetAllTeamsWithObjective() throws Exception { @@ -93,32 +147,34 @@ void shouldGetAllTeamsWithObjective() throws Exception { overviews.addAll(overviewOKR); overviews.add(overviewKuchen); BDDMockito.given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) - .willReturn(overviews); + .willReturn(overviews); BDDMockito.given(overviewAuthorizationService.hasWriteAllAccess()).willReturn(true); mvc.perform(get("/api/v2/overview?quarter=2&team=1,2,3,4").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(3))) - .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(1))) - .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(PUZZLE))) - .andExpect(jsonPath("$[0].objectives[0].id", Is.is(1))) - .andExpect(jsonPath("$[0].objectives[1].id", Is.is(2))).andExpect(jsonPath("$[1].team.id", Is.is(2))) - .andExpect(jsonPath("$[1].team.name", Is.is("OKR"))) - .andExpect(jsonPath("$[1].objectives[0].id", Is.is(5))) - .andExpect(jsonPath("$[1].objectives[1].id", Is.is(7))).andExpect(jsonPath("$[2].team.id", Is.is(3))) - .andExpect(jsonPath("$[2].team.name", Is.is(TEAM_KUCHEN))) - .andExpect(jsonPath("$[2].objectives[0].id", Is.is(8))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(3))) + .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(1))) + .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(PUZZLE))) + .andExpect(jsonPath("$[0].objectives[0].id", Is.is(1))) + .andExpect(jsonPath("$[0].objectives[1].id", Is.is(2))) + .andExpect(jsonPath("$[1].team.id", Is.is(2))) + .andExpect(jsonPath("$[1].team.name", Is.is("OKR"))) + .andExpect(jsonPath("$[1].objectives[0].id", Is.is(5))) + .andExpect(jsonPath("$[1].objectives[1].id", Is.is(7))) + .andExpect(jsonPath("$[2].team.id", Is.is(3))) + .andExpect(jsonPath("$[2].team.name", Is.is(TEAM_KUCHEN))) + .andExpect(jsonPath("$[2].objectives[0].id", Is.is(8))); } @Test void shouldGetAllTeamsWithObjectiveIfNoTeamsExists() throws Exception { BDDMockito.given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) - .willReturn(Collections.emptyList()); + .willReturn(Collections.emptyList()); BDDMockito.given(overviewAuthorizationService.hasWriteAllAccess()).willReturn(true); mvc.perform(get("/api/v2/overview").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(0))); } @Test @@ -126,29 +182,30 @@ void shouldReturnOnlyFilteredObjectivesByQuarterAndTeam() throws Exception { List overviews = new ArrayList<>(overviewPuzzle); overviews.add(overviewKuchen); BDDMockito.given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) - .willReturn(overviews); + .willReturn(overviews); mvc.perform(get("/api/v2/overview?quarter=2&team=1,3").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(2))) - .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(1))) - .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(PUZZLE))) - .andExpect(jsonPath("$[0].objectives[0].id", Is.is(1))) - .andExpect(jsonPath("$[0].objectives[1].id", Is.is(2))).andExpect(jsonPath("$[1].team.id", Is.is(3))) - .andExpect(jsonPath("$[1].team.name", Is.is(TEAM_KUCHEN))) - .andExpect(jsonPath("$[1].objectives[0].id", Is.is(8))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(2))) + .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(1))) + .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(PUZZLE))) + .andExpect(jsonPath("$[0].objectives[0].id", Is.is(1))) + .andExpect(jsonPath("$[0].objectives[1].id", Is.is(2))) + .andExpect(jsonPath("$[1].team.id", Is.is(3))) + .andExpect(jsonPath("$[1].team.name", Is.is(TEAM_KUCHEN))) + .andExpect(jsonPath("$[1].objectives[0].id", Is.is(8))); } @Test void shouldReturnTeamWithEmptyObjectiveListWhenNoObjectiveInFilteredQuarter() throws Exception { BDDMockito.given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) - .willReturn(List.of(simpleOverview)); + .willReturn(List.of(simpleOverview)); mvc.perform(get("/api/v2/overview?quarter=2&team=4").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(1))) - .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(4))) - .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(TEAM_KUCHEN))) - .andExpect(jsonPath("$[0].objectives.size()", Is.is(0))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(1))) + .andExpect(jsonPath(JSON_PATH_TEAM_ID, Is.is(4))) + .andExpect(jsonPath(JSON_PATH_TEAM_NAME, Is.is(TEAM_KUCHEN))) + .andExpect(jsonPath("$[0].objectives.size()", Is.is(0))); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/QuarterControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/QuarterControllerIT.java index 5a582cd117..007653ccdf 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/QuarterControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/QuarterControllerIT.java @@ -1,7 +1,16 @@ package ch.puzzle.okr.controller; +import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; +import static ch.puzzle.okr.test.TestConstants.BACK_LOG_QUARTER_ID; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.service.business.QuarterBusinessService; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.Test; @@ -17,27 +26,29 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import java.time.LocalDate; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; -import static ch.puzzle.okr.test.TestConstants.BACK_LOG_QUARTER_ID; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(QuarterController.class) class QuarterControllerIT { - static Quarter quarter1 = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2") - .withStartDate(LocalDate.of(2022, 9, 1)).withEndDate(LocalDate.of(2022, 12, 31)).build(); - static Quarter quarter2 = Quarter.Builder.builder().withId(2L).withLabel("GJ 22/23-Q3") - .withStartDate(LocalDate.of(2023, 1, 1)).withEndDate(LocalDate.of(2023, 3, 31)).build(); - static Quarter backlogQuarter = Quarter.Builder.builder().withId(BACK_LOG_QUARTER_ID) - .withLabel(BACK_LOG_QUARTER_LABEL).withStartDate(null).withEndDate(null).build(); + static Quarter quarter1 = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .withStartDate(LocalDate.of(2022, 9, 1)) + .withEndDate(LocalDate.of(2022, 12, 31)) + .build(); + static Quarter quarter2 = Quarter.Builder.builder() + .withId(2L) + .withLabel("GJ 22/23-Q3") + .withStartDate(LocalDate.of(2023, 1, 1)) + .withEndDate(LocalDate.of(2023, 3, 31)) + .build(); + static Quarter backlogQuarter = Quarter.Builder.builder() + .withId(BACK_LOG_QUARTER_ID) + .withLabel(BACK_LOG_QUARTER_LABEL) + .withStartDate(null) + .withEndDate(null) + .build(); static List quaterList = Arrays.asList(quarter1, quarter2, backlogQuarter); @Autowired @@ -50,15 +61,18 @@ void shouldGetAllQuarters() throws Exception { BDDMockito.given(quarterBusinessService.getQuarters()).willReturn(quaterList); mvc.perform(get("/api/v2/quarters").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(3))) - .andExpect(jsonPath("$[0].id", Is.is(1))).andExpect(jsonPath("$[0].label", Is.is("GJ 22/23-Q2"))) - .andExpect(jsonPath("$[0].startDate", Is.is(LocalDate.of(2022, 9, 1).toString()))) - .andExpect(jsonPath("$[0].endDate", Is.is(LocalDate.of(2022, 12, 31).toString()))) - .andExpect(jsonPath("$[1].id", Is.is(2))).andExpect(jsonPath("$[1].label", Is.is("GJ 22/23-Q3"))) - .andExpect(jsonPath("$[1].startDate", Is.is(LocalDate.of(2023, 1, 1).toString()))) - .andExpect(jsonPath("$[1].endDate", Is.is(LocalDate.of(2023, 3, 31).toString()))) - .andExpect(jsonPath("$[2].id", Is.is((int) BACK_LOG_QUARTER_ID))) - .andExpect(jsonPath("$[2].label", Is.is(BACK_LOG_QUARTER_LABEL))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(3))) + .andExpect(jsonPath("$[0].id", Is.is(1))) + .andExpect(jsonPath("$[0].label", Is.is("GJ 22/23-Q2"))) + .andExpect(jsonPath("$[0].startDate", Is.is(LocalDate.of(2022, 9, 1).toString()))) + .andExpect(jsonPath("$[0].endDate", Is.is(LocalDate.of(2022, 12, 31).toString()))) + .andExpect(jsonPath("$[1].id", Is.is(2))) + .andExpect(jsonPath("$[1].label", Is.is("GJ 22/23-Q3"))) + .andExpect(jsonPath("$[1].startDate", Is.is(LocalDate.of(2023, 1, 1).toString()))) + .andExpect(jsonPath("$[1].endDate", Is.is(LocalDate.of(2023, 3, 31).toString()))) + .andExpect(jsonPath("$[2].id", Is.is((int) BACK_LOG_QUARTER_ID))) + .andExpect(jsonPath("$[2].label", Is.is(BACK_LOG_QUARTER_LABEL))); } @Test @@ -66,7 +80,8 @@ void shouldGetAllTeamsIfNoTeamsExists() throws Exception { BDDMockito.given(quarterBusinessService.getQuarters()).willReturn(Collections.emptyList()); mvc.perform(get("/api/v2/quarters").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test diff --git a/backend/src/test/java/ch/puzzle/okr/controller/TeamControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/TeamControllerIT.java index 999c8cacf1..ff3985cebd 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/TeamControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/TeamControllerIT.java @@ -1,9 +1,18 @@ package ch.puzzle.okr.controller; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doThrow; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + import ch.puzzle.okr.dto.TeamDto; import ch.puzzle.okr.mapper.TeamMapper; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.service.authorization.TeamAuthorizationService; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; @@ -22,16 +31,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.doThrow; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(TeamController.class) @@ -88,9 +87,12 @@ void shouldGetAllTeams() throws Exception { BDDMockito.given(teamAuthorizationService.getAllTeams()).willReturn(teamList); mvc.perform(get("/api/v2/teams?quarterId=1").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(2))) - .andExpect(jsonPath("$[0].id", Is.is(5))).andExpect(jsonPath("$[0].name", Is.is(PUZZLE))) - .andExpect(jsonPath("$[1].id", Is.is(7))).andExpect(jsonPath("$[1].name", Is.is("OKR"))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(2))) + .andExpect(jsonPath("$[0].id", Is.is(5))) + .andExpect(jsonPath("$[0].name", Is.is(PUZZLE))) + .andExpect(jsonPath("$[1].id", Is.is(7))) + .andExpect(jsonPath("$[1].name", Is.is("OKR"))); } @Test @@ -106,27 +108,31 @@ void shouldGetAllTeamsIfTeamModelIsNull() throws Exception { BDDMockito.given(teamAuthorizationService.getAllTeams()).willReturn(Collections.emptyList()); mvc.perform(get("/api/v2/teams?quarterId=1").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnCreatedTeam() throws Exception { BDDMockito.given(teamAuthorizationService.createEntity(any())).willReturn(teamOKR); - mvc.perform(post(BASE_URL).contentType(MediaType.APPLICATION_JSON).content(CREATE_NEW_TEAM) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isCreated()) - .andExpect(MockMvcResultMatchers.content().string(RESPONSE_NEW_TEAM)); + mvc.perform(post(BASE_URL).contentType(MediaType.APPLICATION_JSON) + .content(CREATE_NEW_TEAM) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andExpect(MockMvcResultMatchers.content().string(RESPONSE_NEW_TEAM)); } @Test void shouldReturnResponseStatusExceptionWhenCreatingObjectiveWithNullValues() throws Exception { - BDDMockito.given(teamAuthorizationService.createEntity(any())).willThrow( - new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing attribute name when creating team")); - - mvc.perform(post(BASE_URL).contentType(MediaType.APPLICATION_JSON).content(CREATE_NEW_TEAM_WITH_NULL_VALUES) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isBadRequest()); + BDDMockito.given(teamAuthorizationService.createEntity(any())) + .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, + "Missing attribute name when creating team")); + + mvc.perform(post(BASE_URL).contentType(MediaType.APPLICATION_JSON) + .content(CREATE_NEW_TEAM_WITH_NULL_VALUES) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isBadRequest()); } @Test @@ -137,64 +143,73 @@ void shouldReturnUpdatedTeam() throws Exception { BDDMockito.given(teamMapper.toDto(any())).willReturn(teamDto); BDDMockito.given(teamAuthorizationService.updateEntity(any(), anyLong())).willReturn(team); - mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON).content(UPDATE_TEAM) - .with(SecurityMockMvcRequestPostProcessors.csrf())).andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(jsonPath("$.id", Is.is(teamDto.id().intValue()))) - .andExpect(jsonPath("$.version", Is.is(teamDto.version()))) - .andExpect(jsonPath("$.name", Is.is(teamDto.name()))); + mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON) + .content(UPDATE_TEAM) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$.id", Is.is(teamDto.id().intValue()))) + .andExpect(jsonPath("$.version", Is.is(teamDto.version()))) + .andExpect(jsonPath("$.name", Is.is(teamDto.name()))); } @Test void shouldReturnNotFound() throws Exception { BDDMockito.given(teamAuthorizationService.updateEntity(any(), anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed team -> Attribut is invalid")); + .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed team -> Attribut is invalid")); - mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON).content(UPDATE_TEAM) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON) + .content(UPDATE_TEAM) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void shouldReturnBadRequest() throws Exception { BDDMockito.given(teamAuthorizationService.updateEntity(any(), anyLong())) - .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed team -> Attribut is invalid")); + .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Failed team -> Attribut is invalid")); - mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON).content(UPDATE_TEAM) - .with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isBadRequest()); + mvc.perform(put(URL_TEAM_1).contentType(MediaType.APPLICATION_JSON) + .content(UPDATE_TEAM) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isBadRequest()); } @Test void shouldDeleteTeam() throws Exception { mvc.perform(delete(URL_TEAM_1).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void throwExceptionWhenOTeamWithIdCantBeFoundWhileDeleting() throws Exception { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Team not found")).when(teamAuthorizationService) - .deleteEntity(anyLong()); + .deleteEntity(anyLong()); mvc.perform(delete(URL_TEAM_1).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void addUsersToTeam_shouldReturnOk() throws Exception { - mvc.perform(put(URL_TEAM_1 + "/addusers").contentType(MediaType.APPLICATION_JSON).content(ADD_USERS) - .with(SecurityMockMvcRequestPostProcessors.csrf())).andExpect(MockMvcResultMatchers.status().isOk()); + mvc.perform(put(URL_TEAM_1 + "/addusers").contentType(MediaType.APPLICATION_JSON) + .content(ADD_USERS) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void removeUserFromTeam_shouldReturnOk() throws Exception { mvc.perform(put(URL_TEAM_1 + SUB_URL_USER_5 + "/removeuser").contentType(MediaType.APPLICATION_JSON) - .content(ADD_USERS).with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .content(ADD_USERS) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void updateOrAddTeamMembership_shouldReturnOk() throws Exception { - mvc.perform(put(URL_TEAM_1 + SUB_URL_USER_5 + "/updateaddteammembership/true") - .contentType(MediaType.APPLICATION_JSON).content(ADD_USERS) - .with(SecurityMockMvcRequestPostProcessors.csrf())).andExpect(MockMvcResultMatchers.status().isOk()); + mvc.perform(put(URL_TEAM_1 + SUB_URL_USER_5 + + "/updateaddteammembership/true").contentType(MediaType.APPLICATION_JSON) + .content(ADD_USERS) + .with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(MockMvcResultMatchers.status().isOk()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/controller/UserControllerIT.java b/backend/src/test/java/ch/puzzle/okr/controller/UserControllerIT.java index 04cf20eb1c..e545169239 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/UserControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/UserControllerIT.java @@ -1,11 +1,21 @@ package ch.puzzle.okr.controller; +import static ch.puzzle.okr.controller.ActionControllerIT.SUCCESSFUL_UPDATE_BODY; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + import ch.puzzle.okr.dto.UserDto; import ch.puzzle.okr.mapper.UserMapper; import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.authorization.AuthorizationService; import ch.puzzle.okr.service.authorization.UserAuthorizationService; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.jupiter.api.BeforeEach; @@ -25,17 +35,6 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.server.ResponseStatusException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static ch.puzzle.okr.controller.ActionControllerIT.SUCCESSFUL_UPDATE_BODY; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doThrow; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(UserController.class) @@ -46,10 +45,18 @@ class UserControllerIT { private static final String FIRSTNAME_2 = "Bob"; private static final String LASTNAME_2 = "Baumeister"; private static final String EMAIL_2 = "baumeister@puzzle.ch"; - static User userAlice = User.Builder.builder().withId(2L).withFirstname(FIRSTNAME_1).withLastname(LASTNAME_1) - .withEmail(EMAIL_1).build(); - static User userBob = User.Builder.builder().withId(9L).withFirstname(FIRSTNAME_2).withLastname(LASTNAME_2) - .withEmail(EMAIL_2).build(); + static User userAlice = User.Builder.builder() + .withId(2L) + .withFirstname(FIRSTNAME_1) + .withLastname(LASTNAME_1) + .withEmail(EMAIL_1) + .build(); + static User userBob = User.Builder.builder() + .withId(9L) + .withFirstname(FIRSTNAME_2) + .withLastname(LASTNAME_2) + .withEmail(EMAIL_2) + .build(); static List userList = Arrays.asList(userAlice, userBob); static UserDto userAliceDto = new UserDto(2L, 3, FIRSTNAME_1, LASTNAME_1, EMAIL_1, new ArrayList<>(), false); static UserDto userBobDto = new UserDto(9L, 4, FIRSTNAME_2, LASTNAME_2, EMAIL_2, new ArrayList<>(), false); @@ -73,13 +80,16 @@ void shouldGetAllUsers() throws Exception { BDDMockito.given(userAuthorizationService.getAllUsers()).willReturn(userList); mvc.perform(get("/api/v1/users").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(2))) - .andExpect(jsonPath("$[0].id", Is.is(2))).andExpect(jsonPath("$[0].firstname", Is.is(FIRSTNAME_1))) - .andExpect(jsonPath("$[0].lastname", Is.is(LASTNAME_1))) - .andExpect(jsonPath("$[0].email", Is.is(EMAIL_1))).andExpect(jsonPath("$[1].id", Is.is(9))) - .andExpect(jsonPath("$[1].firstname", Is.is(FIRSTNAME_2))) - .andExpect(jsonPath("$[1].lastname", Is.is(LASTNAME_2))) - .andExpect(jsonPath("$[1].email", Is.is(EMAIL_2))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(2))) + .andExpect(jsonPath("$[0].id", Is.is(2))) + .andExpect(jsonPath("$[0].firstname", Is.is(FIRSTNAME_1))) + .andExpect(jsonPath("$[0].lastname", Is.is(LASTNAME_1))) + .andExpect(jsonPath("$[0].email", Is.is(EMAIL_1))) + .andExpect(jsonPath("$[1].id", Is.is(9))) + .andExpect(jsonPath("$[1].firstname", Is.is(FIRSTNAME_2))) + .andExpect(jsonPath("$[1].lastname", Is.is(LASTNAME_2))) + .andExpect(jsonPath("$[1].email", Is.is(EMAIL_2))); } @Test @@ -87,25 +97,26 @@ void shouldGetAllUsersIfNoUserExists() throws Exception { BDDMockito.given(userAuthorizationService.getAllUsers()).willReturn(Collections.emptyList()); mvc.perform(get("/api/v1/users").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnCurrentUser() throws Exception { BDDMockito.given(authorizationService.updateOrAddAuthorizationUser()) - .willReturn(new AuthorizationUser(userAlice)); + .willReturn(new AuthorizationUser(userAlice)); BDDMockito.given(userMapper.toDto(userAlice)).willReturn(userAliceDto); mvc.perform(get("/api/v1/users/current").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()) // - .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // - .andExpect(jsonPath("$.id", Is.is(2))) // - .andExpect(jsonPath("$.version", Is.is(3))) // - .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // - .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // - .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // - .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // - .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); + .andExpect(MockMvcResultMatchers.status().isOk()) // + .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // + .andExpect(jsonPath("$.id", Is.is(2))) // + .andExpect(jsonPath("$.version", Is.is(3))) // + .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // + .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // + .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // + .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // + .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); } @Test @@ -114,15 +125,15 @@ void shouldReturnUserById() throws Exception { BDDMockito.given(userMapper.toDto(userAlice)).willReturn(userAliceDto); mvc.perform(get("/api/v1/users/2").contentType(MediaType.APPLICATION_JSON)) // - .andExpect(MockMvcResultMatchers.status().isOk()) // - .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // - .andExpect(jsonPath("$.id", Is.is(2))) // - .andExpect(jsonPath("$.version", Is.is(3))) // - .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // - .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // - .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // - .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // - .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); + .andExpect(MockMvcResultMatchers.status().isOk()) // + .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // + .andExpect(jsonPath("$.id", Is.is(2))) // + .andExpect(jsonPath("$.version", Is.is(3))) // + .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // + .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // + .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // + .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // + .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); } @Test @@ -131,19 +142,19 @@ void shouldSetOkrChampion() throws Exception { BDDMockito.given(userMapper.toDto(userAlice)).willReturn(userAliceDto); mvc.perform(put("/api/v1/users/2/isokrchampion/true") // - .content(SUCCESSFUL_UPDATE_BODY) // - .contentType(MediaType.APPLICATION_JSON) // - .with(SecurityMockMvcRequestPostProcessors.csrf()) // + .content(SUCCESSFUL_UPDATE_BODY) // + .contentType(MediaType.APPLICATION_JSON) // + .with(SecurityMockMvcRequestPostProcessors.csrf()) // ) // - .andExpect(MockMvcResultMatchers.status().isOk()) // - .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // - .andExpect(jsonPath("$.id", Is.is(2))) // - .andExpect(jsonPath("$.version", Is.is(3))) // - .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // - .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // - .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // - .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // - .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); + .andExpect(MockMvcResultMatchers.status().isOk()) // + .andExpect(jsonPath("$", Matchers.aMapWithSize(7))) // + .andExpect(jsonPath("$.id", Is.is(2))) // + .andExpect(jsonPath("$.version", Is.is(3))) // + .andExpect(jsonPath("$.firstname", Is.is(FIRSTNAME_1))) // + .andExpect(jsonPath("$.lastname", Is.is(LASTNAME_1))) // + .andExpect(jsonPath("$.email", Is.is(EMAIL_1))) // + .andExpect(jsonPath("$.userTeamList", Matchers.empty())) // + .andExpect(jsonPath("$.isOkrChampion", Is.is(false))); } @Test @@ -152,35 +163,35 @@ void shouldCreateUsers() throws Exception { BDDMockito.given(userMapper.toDtos(List.of(userAlice))).willReturn(List.of(userAliceDto)); mvc.perform(post("/api/v1/users/createall") // - .content(SUCCESSFUL_UPDATE_BODY) // - .contentType(MediaType.APPLICATION_JSON) // - .with(SecurityMockMvcRequestPostProcessors.csrf()) // + .content(SUCCESSFUL_UPDATE_BODY) // + .contentType(MediaType.APPLICATION_JSON) // + .with(SecurityMockMvcRequestPostProcessors.csrf()) // ) // - .andExpect(MockMvcResultMatchers.status().isOk()) // - .andExpect(jsonPath("$", Matchers.hasSize(1))) // - .andExpect(jsonPath("$[0].id", Is.is(2))) // - .andExpect(jsonPath("$[0].version", Is.is(3))) // - .andExpect(jsonPath("$[0].firstname", Is.is(FIRSTNAME_1))) // - .andExpect(jsonPath("$[0].lastname", Is.is(LASTNAME_1))) // - .andExpect(jsonPath("$[0].email", Is.is(EMAIL_1))) // - .andExpect(jsonPath("$[0].userTeamList", Matchers.empty())) // - .andExpect(jsonPath("$[0].isOkrChampion", Is.is(false))); + .andExpect(MockMvcResultMatchers.status().isOk()) // + .andExpect(jsonPath("$", Matchers.hasSize(1))) // + .andExpect(jsonPath("$[0].id", Is.is(2))) // + .andExpect(jsonPath("$[0].version", Is.is(3))) // + .andExpect(jsonPath("$[0].firstname", Is.is(FIRSTNAME_1))) // + .andExpect(jsonPath("$[0].lastname", Is.is(LASTNAME_1))) // + .andExpect(jsonPath("$[0].email", Is.is(EMAIL_1))) // + .andExpect(jsonPath("$[0].userTeamList", Matchers.empty())) // + .andExpect(jsonPath("$[0].isOkrChampion", Is.is(false))); } @Test void shouldDeleteUser() throws Exception { mvc.perform(delete("/api/v1/users/10").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); } @DisplayName("should throw exception when user with id cant be found while deleting") @Test void throwExceptionWhenUserWithIdCantBeFoundWhileDeleting() throws Exception { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found")).when(userAuthorizationService) - .deleteEntityById(1000); + .deleteEntityById(1000); mvc.perform(delete("/api/v1/users/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } } \ No newline at end of file diff --git a/backend/src/test/java/ch/puzzle/okr/deserializer/CheckInDeserializerTest.java b/backend/src/test/java/ch/puzzle/okr/deserializer/CheckInDeserializerTest.java index 62145a9cc8..d4b6ab07f5 100644 --- a/backend/src/test/java/ch/puzzle/okr/deserializer/CheckInDeserializerTest.java +++ b/backend/src/test/java/ch/puzzle/okr/deserializer/CheckInDeserializerTest.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.deserializer; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.dto.checkin.CheckInDto; import ch.puzzle.okr.dto.checkin.CheckInMetricDto; import ch.puzzle.okr.dto.checkin.CheckInOrdinalDto; @@ -21,10 +25,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) class CheckInDeserializerTest { @@ -61,9 +61,9 @@ void deserializeShouldReturnCheckInMetricDtoForMetricJson() throws Exception { """; when(keyResultBusinessService.getEntityById(1000L)) // - .thenReturn(KeyResultMetric.Builder.builder() // - .withId(1000L) // - .build()); + .thenReturn(KeyResultMetric.Builder.builder() // + .withId(1000L) // + .build()); JsonParser jsonParser = objectMapper.getFactory().createParser(jsonMetric); DeserializationContext ctxt = mock(DeserializationContext.class); @@ -108,9 +108,9 @@ void deserializeShouldReturnCheckInOrdinalDtoForOrdinalJson() throws Exception { """; when(keyResultBusinessService.getEntityById(1001L)) // - .thenReturn(KeyResultOrdinal.Builder.builder() // - .withId(1001L) // - .build()); + .thenReturn(KeyResultOrdinal.Builder.builder() // + .withId(1001L) // + .build()); JsonParser jsonParser = objectMapper.getFactory().createParser(jsonOrdinal); DeserializationContext ctxt = mock(DeserializationContext.class); diff --git a/backend/src/test/java/ch/puzzle/okr/deserializer/KeyResultDeserializerTest.java b/backend/src/test/java/ch/puzzle/okr/deserializer/KeyResultDeserializerTest.java index b8ddead732..c313e53b05 100644 --- a/backend/src/test/java/ch/puzzle/okr/deserializer/KeyResultDeserializerTest.java +++ b/backend/src/test/java/ch/puzzle/okr/deserializer/KeyResultDeserializerTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.deserializer; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; + import ch.puzzle.okr.dto.keyresult.*; import ch.puzzle.okr.models.Unit; import com.fasterxml.jackson.core.JsonParser; @@ -14,9 +17,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; - @ExtendWith(MockitoExtension.class) public class KeyResultDeserializerTest { diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/ActionMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/ActionMapperTest.java index 9dc733ff5e..07bf6ebf63 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/ActionMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/ActionMapperTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.mapper; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.dto.ActionDto; import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.keyresult.KeyResult; @@ -7,6 +10,7 @@ import ch.puzzle.okr.service.business.KeyResultBusinessService; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -14,11 +18,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class ActionMapperTest { @@ -49,13 +48,13 @@ void setup() { void toDtoShouldMapActionToDto() { // arrange Action action = Action.Builder.builder() // - .withId(ID) // - .withVersion(VERSION) // - .withAction(ACTION) // - .withPriority(PRIORITY) // - .withIsChecked(IS_CHECKED) // - .withKeyResult(keyResult) // - .build(); + .withId(ID) // + .withVersion(VERSION) // + .withAction(ACTION) // + .withPriority(PRIORITY) // + .withIsChecked(IS_CHECKED) // + .withKeyResult(keyResult) // + .build(); action.setWriteable(IS_WRITEABLE); // act @@ -107,12 +106,12 @@ void toActionsWithKeyResultParameterShouldMapListOfDtosToListOfActions() { // arrange KeyResult keyResultParameter = KeyResultMetric.Builder.builder().withId(20L).build(); ActionDto actionDtoWithKeyResultIdIsNull = new ActionDto(ID, // - VERSION, // - ACTION, // - PRIORITY, // - IS_CHECKED, // - null, // keyResultId - IS_WRITEABLE // + VERSION, // + ACTION, // + PRIORITY, // + IS_CHECKED, // + null, // keyResultId + IS_WRITEABLE // ); // act @@ -123,7 +122,8 @@ void toActionsWithKeyResultParameterShouldMapListOfDtosToListOfActions() { assertNotNull(actionList); // the value of the KeyResultId in the ActionDto is null - // the value of the KeyResultId in Action is the value of keyResultParameter ( == 20) + // the value of the KeyResultId in Action is the value of keyResultParameter ( + // == 20) assertListOfActionsAndKeyResultParameter(actionDtoList, actionList, keyResultParameter.getId()); } @@ -133,7 +133,7 @@ private void assertListOfActionsWithKeyResultId(List expectedDtoList, } private void assertListOfActionsAndKeyResultParameter(List expectedDtoList, List actualList, - Long keyResultId) { + Long keyResultId) { assertListsAndFirstAction(expectedDtoList, actualList); assertEquals(keyResultId, actualList.get(0).getKeyResult().getId()); } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/AlignmentSelectionMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/AlignmentSelectionMapperTest.java index 84c1db2ff8..10c7716b60 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/AlignmentSelectionMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/AlignmentSelectionMapperTest.java @@ -1,15 +1,14 @@ package ch.puzzle.okr.mapper; +import static ch.puzzle.okr.test.TestConstants.TEAM_PUZZLE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import ch.puzzle.okr.dto.alignment.AlignmentObjectiveDto; import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.models.alignment.AlignmentSelectionId; -import org.junit.jupiter.api.Test; - import java.util.List; - -import static ch.puzzle.okr.test.TestConstants.TEAM_PUZZLE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; class AlignmentSelectionMapperTest { private final AlignmentSelectionMapper alignmentSelectionMapper = new AlignmentSelectionMapper(); @@ -25,8 +24,13 @@ void toDtoShouldReturnEmptyListWhenNoObjectiveFound() { @Test void toDtoShouldReturnOneElementWhenObjectiveFound() { List alignmentSelections = List.of(AlignmentSelection.Builder.builder() - .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder().withObjectiveId(1L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").build()); + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .build()); List alignmentObjectiveDtos = alignmentSelectionMapper.toDto(alignmentSelections); assertEquals(1, alignmentObjectiveDtos.size()); @@ -36,10 +40,15 @@ void toDtoShouldReturnOneElementWhenObjectiveFound() { @Test void toDtoShouldReturnOneElementWhenObjectiveWithKeyResultFound() { List alignmentSelections = List.of(AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(1L).withKeyResultId(3L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1") - .withKeyResultTitle("Key Result 3").build()); + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .withKeyResultId(3L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 3") + .build()); List alignmentObjectiveDtos = alignmentSelectionMapper.toDto(alignmentSelections); assertEquals(1, alignmentObjectiveDtos.size()); @@ -48,17 +57,26 @@ void toDtoShouldReturnOneElementWhenObjectiveWithKeyResultFound() { @Test void toDtoShouldReturnOneElementWhenObjectiveWithTwoKeyResultsFound() { - List alignmentSelections = List.of( - AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(1L).withKeyResultId(3L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1") - .withKeyResultTitle("Key Result 3").build(), - AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(1L).withKeyResultId(5L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1") - .withKeyResultTitle("Key Result 5").build()); + List alignmentSelections = List.of(AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .withKeyResultId(3L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 3") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .withKeyResultId(5L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 5") + .build()); List alignmentObjectiveDtos = alignmentSelectionMapper.toDto(alignmentSelections); assertEquals(1, alignmentObjectiveDtos.size()); @@ -67,22 +85,36 @@ void toDtoShouldReturnOneElementWhenObjectiveWithTwoKeyResultsFound() { @Test void toDtoShouldReturnOneElementWhenTwoObjectivesWithKeyResultsFound() { - List alignmentSelections = List.of( - AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(1L).withKeyResultId(3L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1") - .withKeyResultTitle("Key Result 3").build(), - AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(5L).withKeyResultId(6L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 5") - .withKeyResultTitle("Key Result 6").build(), - AlignmentSelection.Builder.builder() - .withAlignmentSelectionId( - AlignmentSelectionId.Builder.builder().withObjectiveId(1L).withKeyResultId(9L).build()) - .withTeamId(2L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1") - .withKeyResultTitle("Key Result 9").build()); + List alignmentSelections = List.of(AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .withKeyResultId(3L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 3") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(5L) + .withKeyResultId(6L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 5") + .withKeyResultTitle("Key Result 6") + .build(), + AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.Builder.builder() + .withObjectiveId(1L) + .withKeyResultId(9L) + .build()) + .withTeamId(2L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 9") + .build()); List alignmentObjectiveDtos = alignmentSelectionMapper.toDto(alignmentSelections); assertEquals(2, alignmentObjectiveDtos.size()); diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/CompletedMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/CompletedMapperTest.java index cf764ebc6f..1a28d967ef 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/CompletedMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/CompletedMapperTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.mapper; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import ch.puzzle.okr.dto.CompletedDto; import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.models.Objective; @@ -17,9 +20,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - @ExtendWith(MockitoExtension.class) public class CompletedMapperTest { private static final long COMPLETED_ID = 0L; @@ -50,14 +50,18 @@ void setUp() { void toDtoShouldMapCompletedToDto() { // arrange var completed = Completed.Builder.builder() // - .withId(COMPLETED_ID) // - .withComment(COMPLETED_COMMENT) // - .withObjective(Objective.Builder.builder() // - .withId(OBJECTIVE_ID)// - .withTeam(Team.Builder.builder().withId(NOT_USED_LONG).build()) // - .withQuarter(Quarter.Builder.builder().withId(NOT_USED_LONG).build()) // - .build()) // - .build(); + .withId(COMPLETED_ID) // + .withComment(COMPLETED_COMMENT) // + .withObjective(Objective.Builder.builder() // + .withId(OBJECTIVE_ID)// + .withTeam(Team.Builder.builder() + .withId(NOT_USED_LONG) + .build()) // + .withQuarter(Quarter.Builder.builder() + .withId(NOT_USED_LONG) + .build()) // + .build()) // + .build(); // act var completedDto = completedMapper.toDto(completed); @@ -77,8 +81,13 @@ private void assertCompletedDto(Completed expected, CompletedDto actual) { @Test void toCompletedShouldMapDtoToCompleted() { // arrange - var completedDto = CompletedDtoBuilder.builder().withId(COMPLETED_ID).withComment(COMPLETED_COMMENT) - .withObjectiveDto(ObjectiveDtoBuilder.builder().withId(OBJECTIVE_ID).build()).build(); + var completedDto = CompletedDtoBuilder.builder() + .withId(COMPLETED_ID) + .withComment(COMPLETED_COMMENT) + .withObjectiveDto(ObjectiveDtoBuilder.builder() + .withId(OBJECTIVE_ID) + .build()) + .build(); // act var completed = completedMapper.toCompleted(completedDto); diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/ObjectiveMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/ObjectiveMapperTest.java index 35ce1d1cc7..07f8ff9a22 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/ObjectiveMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/ObjectiveMapperTest.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.mapper; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.dto.ObjectiveDto; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.Quarter; @@ -7,6 +10,8 @@ import ch.puzzle.okr.models.Team; import ch.puzzle.okr.service.business.QuarterBusinessService; import ch.puzzle.okr.service.business.TeamBusinessService; +import java.time.LocalDateTime; +import java.time.Month; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -16,12 +21,6 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import java.time.LocalDateTime; -import java.time.Month; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class ObjectiveMapperTest { @@ -40,9 +39,9 @@ public class ObjectiveMapperTest { private final Team team = Team.Builder.builder().withId(TEAM_ID).build(); private final Quarter quarter = Quarter.Builder.builder() // - .withId(QUARTER_ID) // - .withLabel(QUARTER_LABEL) // - .build(); + .withId(QUARTER_ID) // + .withLabel(QUARTER_LABEL) // + .build(); private ObjectiveMapper objectiveMapper; @@ -62,16 +61,16 @@ void setup() { void toDtoShouldMapObjectiveToDto() { // arrange Objective objective = Objective.Builder.builder() // - .withId(ID) // - .withVersion(VERSION) // - .withTitle(TITLE) // - .withTeam(team) // - .withQuarter(quarter) // - .withDescription(DESCRIPTION) // - .withState(STATE) // - .withCreatedOn(CREATE_DATE_TIME) // - .withModifiedOn(MODIFIED_DATE_TIME) // - .build(); + .withId(ID) // + .withVersion(VERSION) // + .withTitle(TITLE) // + .withTeam(team) // + .withQuarter(quarter) // + .withDescription(DESCRIPTION) // + .withState(STATE) // + .withCreatedOn(CREATE_DATE_TIME) // + .withModifiedOn(MODIFIED_DATE_TIME) // + .build(); objective.setWriteable(IS_WRITEABLE); // act diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/OverviewMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/OverviewMapperTest.java index 374057e987..dea5244667 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/OverviewMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/OverviewMapperTest.java @@ -1,5 +1,12 @@ package ch.puzzle.okr.mapper; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; +import static ch.puzzle.okr.test.TestConstants.TEAM_PUZZLE; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.dto.overview.OverviewDto; import ch.puzzle.okr.dto.overview.OverviewKeyResultDto; @@ -9,20 +16,12 @@ import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.models.overview.OverviewId; import ch.puzzle.okr.test.TestHelper; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; -import static ch.puzzle.okr.test.TestConstants.TEAM_PUZZLE; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.springframework.http.HttpStatus.BAD_REQUEST; - @ExtendWith(MockitoExtension.class) class OverviewMapperTest { @@ -40,7 +39,11 @@ void toDtoShouldReturnEmptyListWhenNoTeamFound() { @Test void toDtoShouldReturnEmptyListWhenTeamFound() { List overviews = List.of(Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withTeamId(2L).build()).withTeamName(TEAM_PUZZLE).build()); + .withOverviewId(OverviewId.Builder.builder() + .withTeamId(2L) + .build()) + .withTeamName(TEAM_PUZZLE) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); @@ -50,8 +53,13 @@ void toDtoShouldReturnEmptyListWhenTeamFound() { @Test void toDtoShouldReturnOneElementWhenObjectiveFound() { List overviews = List.of(Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").build()); + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); @@ -62,10 +70,16 @@ void toDtoShouldReturnOneElementWhenObjectiveFound() { @Test void toDtoShouldReturnOneElementWhenObjectiveWithKeyResultFound() { List overviews = List.of(Overview.Builder.builder() - .withOverviewId( - OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L).withKeyResultId(3L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType(KEY_RESULT_TYPE_METRIC).build()); + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); @@ -76,10 +90,19 @@ void toDtoShouldReturnOneElementWhenObjectiveWithKeyResultFound() { @Test void toDtoShouldReturnOneElementWhenObjectiveWithKeyResultAndCheckInsFound() { List overviews = List.of(Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L).withKeyResultId(3L) - .withCheckInId(4L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withCheckInValue(27.5).withConfidence(5).build()); + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .withCheckInId(4L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withCheckInValue(27.5) + .withConfidence(5) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); @@ -89,17 +112,30 @@ void toDtoShouldReturnOneElementWhenObjectiveWithKeyResultAndCheckInsFound() { @Test void toDtoShouldReturnOneElementWhenObjectiveWithTwoKeyResultAndCheckInFound() { - List overviews = List.of( - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L) - .withKeyResultId(3L).withCheckInId(4L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType(KEY_RESULT_TYPE_ORDINAL).withCheckInZone("COMMIT").build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L) - .withKeyResultId(5L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 5") - .withKeyResultType(KEY_RESULT_TYPE_METRIC).build()); + List overviews = List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .withCheckInId(4L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType(KEY_RESULT_TYPE_ORDINAL) + .withCheckInZone("COMMIT") + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(5L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 5") + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); @@ -109,19 +145,38 @@ void toDtoShouldReturnOneElementWhenObjectiveWithTwoKeyResultAndCheckInFound() { @Test void toDtoShouldReturnOneElementWhenTwoObjectivesWithKeyResultAndCheckInFound() { - List overviews = List.of( - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L) - .withKeyResultId(3L).withCheckInId(4L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType(KEY_RESULT_TYPE_METRIC).withBaseline(20.0).withStretchGoal(37.0) - .withUnit("TCHF").withCheckInValue(27.5).build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(5L).withTeamId(2L) - .withKeyResultId(6L).withCheckInId(7L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 5").withKeyResultTitle("Key Result 6") - .withKeyResultType(KEY_RESULT_TYPE_ORDINAL).withCommitZone("commit").withTargetZone("target") - .withStretchZone("stretch").withCheckInZone("checkIn").build()); + List overviews = List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .withCheckInId(4L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .withBaseline(20.0) + .withStretchGoal(37.0) + .withUnit("TCHF") + .withCheckInValue(27.5) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(5L) + .withTeamId(2L) + .withKeyResultId(6L) + .withCheckInId(7L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 5") + .withKeyResultTitle("Key Result 6") + .withKeyResultType(KEY_RESULT_TYPE_ORDINAL) + .withCommitZone("commit") + .withTargetZone("target") + .withStretchZone("stretch") + .withCheckInZone("checkIn") + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); @@ -147,22 +202,41 @@ void toDtoShouldReturnOneElementWhenTwoObjectivesWithKeyResultAndCheckInFound() @Test void toDtoShouldReturnOneElementWhenTwoTeamsWithObjectivesAndKeyResultsFound() { - List overviews = List.of( - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L) - .withKeyResultId(3L).withCheckInId(4L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType(KEY_RESULT_TYPE_ORDINAL).withCheckInZone("TARGET").build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(5L).withTeamId(4L) - .withKeyResultId(6L).build()) - .withTeamName("/BBT").withObjectiveTitle("Objective 5").withKeyResultTitle("Key Result 6") - .withKeyResultType(KEY_RESULT_TYPE_METRIC).build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(5L).withTeamId(4L) - .withKeyResultId(8L).build()) - .withTeamName("/BBT").withObjectiveTitle("Objective 5").withKeyResultTitle("Key Result 8") - .withKeyResultType(KEY_RESULT_TYPE_ORDINAL).build()); + List overviews = List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .withCheckInId(4L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType(KEY_RESULT_TYPE_ORDINAL) + .withCheckInZone("TARGET") + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(5L) + .withTeamId(4L) + .withKeyResultId(6L) + .build()) + .withTeamName("/BBT") + .withObjectiveTitle("Objective 5") + .withKeyResultTitle("Key Result 6") + .withKeyResultType(KEY_RESULT_TYPE_METRIC) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(5L) + .withTeamId(4L) + .withKeyResultId(8L) + .build()) + .withTeamName("/BBT") + .withObjectiveTitle("Objective 5") + .withKeyResultTitle("Key Result 8") + .withKeyResultType(KEY_RESULT_TYPE_ORDINAL) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(2, overviewDtos.size()); @@ -175,13 +249,21 @@ void toDtoShouldReturnOneElementWhenTwoTeamsWithObjectivesAndKeyResultsFound() { @Test void toDtoShouldThrowExceptionWhenKeyResultTypeNotSupported() { List overviews = List.of(Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(2L).withKeyResultId(3L) - .withCheckInId(4L).build()) - .withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 1").withKeyResultTitle("Key Result 1") - .withKeyResultType("unknown").withCheckInZone("TARGET").build()); + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(2L) + .withKeyResultId(3L) + .withCheckInId(4L) + .build()) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 1") + .withKeyResultTitle("Key Result 1") + .withKeyResultType("unknown") + .withCheckInZone("TARGET") + .build()); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> overviewMapper.toDto(overviews)); + () -> overviewMapper.toDto(overviews)); assertEquals(BAD_REQUEST, exception.getStatusCode()); diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/TeamMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/TeamMapperTest.java index a885626375..d7ae1d6aa8 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/TeamMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/TeamMapperTest.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper; +import static org.junit.jupiter.api.Assertions.*; + import ch.puzzle.okr.dto.TeamDto; import ch.puzzle.okr.models.Team; import org.junit.jupiter.api.DisplayName; @@ -8,8 +10,6 @@ import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; -import static org.junit.jupiter.api.Assertions.*; - @ExtendWith(MockitoExtension.class) public class TeamMapperTest { @@ -26,10 +26,10 @@ public class TeamMapperTest { void toDtoShouldMapTeamToDto() { // arrange Team team = Team.Builder.builder() // - .withId(ID) // - .withVersion(VERSION) // - .withName(NAME) // - .build(); + .withId(ID) // + .withVersion(VERSION) // + .withName(NAME) // + .build(); team.setWriteable(IS_WRITEABLE); // act diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/UserMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/UserMapperTest.java index 3677e06a18..1b8a4c9d3a 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/UserMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/UserMapperTest.java @@ -1,10 +1,13 @@ package ch.puzzle.okr.mapper; +import static org.junit.jupiter.api.Assertions.*; + import ch.puzzle.okr.dto.NewUserDto; import ch.puzzle.okr.dto.UserDto; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.UserTeam; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -12,10 +15,6 @@ import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; - @ExtendWith(MockitoExtension.class) public class UserMapperTest { @@ -33,17 +32,18 @@ public class UserMapperTest { private TeamMapper teamMapper; private final User user = User.Builder.builder() // - .withId(ID) // - .withVersion(VERSION) // - .withFirstname(FIRSTNAME) // - .withLastname(LASTNAME) // - .withEmail(EMAIL) // - .withUserTeamList(List.of(UserTeam.Builder.builder() // - .withId(USER_TEAM_ID) // - .withTeam(Team.Builder.builder().build()) // - .build())) // - .withOkrChampion(IS_OKR_CHAMPION) // - .build(); + .withId(ID) // + .withVersion(VERSION) // + .withFirstname(FIRSTNAME) // + .withLastname(LASTNAME) // + .withEmail(EMAIL) // + .withUserTeamList(List.of(UserTeam.Builder.builder() // + .withId(USER_TEAM_ID) // + .withTeam(Team.Builder.builder() + .build()) // + .build())) // + .withOkrChampion(IS_OKR_CHAMPION) // + .build(); private final NewUserDto userDto = new NewUserDto(FIRSTNAME, LASTNAME, EMAIL); @@ -57,13 +57,13 @@ void setup() { void toDtoWithoutTeamListThrowsException() { // arrange User user = User.Builder.builder() // - .withId(ID) // - .withVersion(VERSION) // - .withFirstname(FIRSTNAME) // - .withLastname(LASTNAME) // - .withEmail(EMAIL) // - .withOkrChampion(IS_OKR_CHAMPION) // - .build(); + .withId(ID) // + .withVersion(VERSION) // + .withFirstname(FIRSTNAME) // + .withLastname(LASTNAME) // + .withEmail(EMAIL) // + .withOkrChampion(IS_OKR_CHAMPION) // + .build(); // act + assert assertThrows(NullPointerException.class, () -> userMapper.toDto(user)); diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMapperTest.java index 514d838491..81ed42beb1 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMapperTest.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.mapper.checkin; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.dto.checkin.CheckInDto; import ch.puzzle.okr.dto.checkin.CheckInMetricDto; import ch.puzzle.okr.dto.checkin.CheckInOrdinalDto; @@ -21,10 +25,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class CheckInMapperTest { @@ -110,8 +110,8 @@ void toDtoShouldThrowExceptionIfCheckInIsNotMetricOrOrdinal() { // act + assert ResponseStatusException responseStatusException = assertThrows( // - ResponseStatusException.class, // - () -> checkInMapper.toDto(checkIn)); + ResponseStatusException.class, // + () -> checkInMapper.toDto(checkIn)); assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode()); } @@ -124,8 +124,8 @@ void toCheckInShouldThrowExceptionIfCheckInIsNotMetricOrOrdinal() { // act + assert ResponseStatusException responseStatusException = assertThrows( // - ResponseStatusException.class, // - () -> checkInMapper.toCheckIn(checkInDto)); + ResponseStatusException.class, // + () -> checkInMapper.toCheckIn(checkInDto)); assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapperTest.java index 138391aa35..9ec42fb3fd 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInMetricMapperTest.java @@ -1,5 +1,12 @@ package ch.puzzle.okr.mapper.checkin; +import static ch.puzzle.okr.mapper.checkin.helper.AssertHelper.assertCheckInMetric; +import static ch.puzzle.okr.mapper.checkin.helper.AssertHelper.assertCheckInMetricDto; +import static ch.puzzle.okr.mapper.checkin.helper.TestDataDtoHelper.checkInMetricDto; +import static ch.puzzle.okr.mapper.checkin.helper.TestDataHelper.checkInMetric; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.dto.checkin.CheckInMetricDto; import ch.puzzle.okr.mapper.checkin.helper.TestDataHelper; import ch.puzzle.okr.models.checkin.CheckIn; @@ -15,13 +22,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import static ch.puzzle.okr.mapper.checkin.helper.AssertHelper.assertCheckInMetric; -import static ch.puzzle.okr.mapper.checkin.helper.AssertHelper.assertCheckInMetricDto; -import static ch.puzzle.okr.mapper.checkin.helper.TestDataDtoHelper.checkInMetricDto; -import static ch.puzzle.okr.mapper.checkin.helper.TestDataHelper.checkInMetric; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class CheckInMetricMapperTest { diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapperTest.java index 76a7900bcf..9fdde46e16 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/CheckInOrdinalMapperTest.java @@ -1,5 +1,12 @@ package ch.puzzle.okr.mapper.checkin; +import static ch.puzzle.okr.mapper.checkin.helper.AssertHelper.assertCheckInOrdinal; +import static ch.puzzle.okr.mapper.checkin.helper.AssertHelper.assertCheckInOrdinalDto; +import static ch.puzzle.okr.mapper.checkin.helper.TestDataDtoHelper.checkInOrdinalDto; +import static ch.puzzle.okr.mapper.checkin.helper.TestDataHelper.checkInOrdinal; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.dto.checkin.CheckInOrdinalDto; import ch.puzzle.okr.mapper.checkin.helper.TestDataHelper; import ch.puzzle.okr.models.checkin.CheckIn; @@ -15,13 +22,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import static ch.puzzle.okr.mapper.checkin.helper.AssertHelper.assertCheckInOrdinal; -import static ch.puzzle.okr.mapper.checkin.helper.AssertHelper.assertCheckInOrdinalDto; -import static ch.puzzle.okr.mapper.checkin.helper.TestDataDtoHelper.checkInOrdinalDto; -import static ch.puzzle.okr.mapper.checkin.helper.TestDataHelper.checkInOrdinal; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class CheckInOrdinalMapperTest { diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/AssertHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/AssertHelper.java index f05c16717b..b28429dab7 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/AssertHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/AssertHelper.java @@ -1,13 +1,13 @@ package ch.puzzle.okr.mapper.checkin.helper; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + import ch.puzzle.okr.dto.checkin.CheckInMetricDto; import ch.puzzle.okr.dto.checkin.CheckInOrdinalDto; import ch.puzzle.okr.models.checkin.CheckInMetric; import ch.puzzle.okr.models.checkin.CheckInOrdinal; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - public class AssertHelper { public static void assertCheckInMetricDto(CheckInMetric expected, CheckInMetricDto actual) { diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataConstants.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataConstants.java index a060a43c11..ad74625cea 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataConstants.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataConstants.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.mapper.checkin.helper; import ch.puzzle.okr.models.checkin.Zone; - import java.time.LocalDateTime; import java.time.Month; diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataDtoHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataDtoHelper.java index f7c7f2ff14..9246a3a10b 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataDtoHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataDtoHelper.java @@ -1,10 +1,10 @@ package ch.puzzle.okr.mapper.checkin.helper; +import static ch.puzzle.okr.mapper.checkin.helper.TestDataConstants.*; + import ch.puzzle.okr.dto.checkin.CheckInMetricDto; import ch.puzzle.okr.dto.checkin.CheckInOrdinalDto; -import static ch.puzzle.okr.mapper.checkin.helper.TestDataConstants.*; - public class TestDataDtoHelper { public static CheckInMetricDto checkInMetricDto() { @@ -16,26 +16,26 @@ public static CheckInOrdinalDto checkInOrdinalDto() { } private static final CheckInMetricDto checkInMetricDto = new CheckInMetricDto(CHECK_IN_ID, // - CHECK_IN_VERSION, // - CHECK_IN_CHANGE_INFO, // - CHECK_IN_INITIATIVES, // - CHECK_IN_CONFIDENCE, // - KEY_RESULT_ID, // - CHECK_IN_CREATE_DATE_TIME, // - CHECK_IN_MODIFIED_DATE_TIME, // - CHECK_IN_METRIC_VALUE, // - CHECK_IN_IS_WRITEABLE // + CHECK_IN_VERSION, // + CHECK_IN_CHANGE_INFO, // + CHECK_IN_INITIATIVES, // + CHECK_IN_CONFIDENCE, // + KEY_RESULT_ID, // + CHECK_IN_CREATE_DATE_TIME, // + CHECK_IN_MODIFIED_DATE_TIME, // + CHECK_IN_METRIC_VALUE, // + CHECK_IN_IS_WRITEABLE // ); private static final CheckInOrdinalDto checkInOrdinalDto = new CheckInOrdinalDto(CHECK_IN_ID, // - CHECK_IN_VERSION, // - CHECK_IN_CHANGE_INFO, // - CHECK_IN_INITIATIVES, // - CHECK_IN_CONFIDENCE, // - KEY_RESULT_ID, // - CHECK_IN_CREATE_DATE_TIME, // - CHECK_IN_MODIFIED_DATE_TIME, // - CHECK_IN_ORDINAL_ZONE, // - CHECK_IN_IS_WRITEABLE // + CHECK_IN_VERSION, // + CHECK_IN_CHANGE_INFO, // + CHECK_IN_INITIATIVES, // + CHECK_IN_CONFIDENCE, // + KEY_RESULT_ID, // + CHECK_IN_CREATE_DATE_TIME, // + CHECK_IN_MODIFIED_DATE_TIME, // + CHECK_IN_ORDINAL_ZONE, // + CHECK_IN_IS_WRITEABLE // ); } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataHelper.java index dc2d43b9c8..95d6355237 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/checkin/helper/TestDataHelper.java @@ -1,13 +1,13 @@ package ch.puzzle.okr.mapper.checkin.helper; +import static ch.puzzle.okr.mapper.checkin.helper.TestDataConstants.*; + import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.models.checkin.CheckInMetric; import ch.puzzle.okr.models.checkin.CheckInOrdinal; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultMetric; -import static ch.puzzle.okr.mapper.checkin.helper.TestDataConstants.*; - public class TestDataHelper { public static KeyResult keyResult() { @@ -25,29 +25,30 @@ public static CheckInOrdinal checkInOrdinal() { } private static final KeyResult keyResult = KeyResultMetric.Builder.builder() // - .withId(KEY_RESULT_ID) // - .build(); + .withId(KEY_RESULT_ID) // + .build(); private static final CheckIn checkInMetric = CheckInMetric.Builder.builder() // - .withId(CHECK_IN_ID) // - .withVersion(CHECK_IN_VERSION) // - .withChangeInfo(CHECK_IN_CHANGE_INFO) // - .withInitiatives(CHECK_IN_INITIATIVES) // - .withConfidence(CHECK_IN_CONFIDENCE) // - .withKeyResult(keyResult) // - .withCreatedOn(CHECK_IN_CREATE_DATE_TIME) // - .withModifiedOn(CHECK_IN_MODIFIED_DATE_TIME) // - .withValue(CHECK_IN_METRIC_VALUE) // - .build(); + .withId(CHECK_IN_ID) // + .withVersion(CHECK_IN_VERSION) // + .withChangeInfo(CHECK_IN_CHANGE_INFO) // + .withInitiatives(CHECK_IN_INITIATIVES) // + .withConfidence(CHECK_IN_CONFIDENCE) // + .withKeyResult(keyResult) // + .withCreatedOn(CHECK_IN_CREATE_DATE_TIME) // + .withModifiedOn(CHECK_IN_MODIFIED_DATE_TIME) // + .withValue(CHECK_IN_METRIC_VALUE) // + .build(); private static final CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder() // - .withId(CHECK_IN_ID) // - .withVersion(CHECK_IN_VERSION) // - .withChangeInfo(CHECK_IN_CHANGE_INFO) // - .withInitiatives(CHECK_IN_INITIATIVES) // - .withConfidence(CHECK_IN_CONFIDENCE) // - .withKeyResult(keyResult) // - .withCreatedOn(CHECK_IN_CREATE_DATE_TIME) // - .withModifiedOn(CHECK_IN_MODIFIED_DATE_TIME) // - .withZone(CHECK_IN_ORDINAL_ZONE).build(); + .withId(CHECK_IN_ID) // + .withVersion(CHECK_IN_VERSION) // + .withChangeInfo(CHECK_IN_CHANGE_INFO) // + .withInitiatives(CHECK_IN_INITIATIVES) // + .withConfidence(CHECK_IN_CONFIDENCE) // + .withKeyResult(keyResult) // + .withCreatedOn(CHECK_IN_CREATE_DATE_TIME) // + .withModifiedOn(CHECK_IN_MODIFIED_DATE_TIME) // + .withZone(CHECK_IN_ORDINAL_ZONE) + .build(); } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapperTest.java index 8ba2235adc..4d1177b072 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMapperTest.java @@ -1,5 +1,12 @@ package ch.puzzle.okr.mapper.keyresult; +import static ch.puzzle.okr.mapper.keyresult.helper.TestDataDtoHelper.keyResultMetricDto; +import static ch.puzzle.okr.mapper.keyresult.helper.TestDataDtoHelper.keyResultOrdinalDto; +import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.keyResultMetric; +import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.keyResultOrdinal; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultMetricDto; import ch.puzzle.okr.dto.keyresult.KeyResultOrdinalDto; @@ -11,6 +18,7 @@ import ch.puzzle.okr.service.business.CheckInBusinessService; import ch.puzzle.okr.service.business.ObjectiveBusinessService; import ch.puzzle.okr.service.business.UserBusinessService; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -21,15 +29,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static ch.puzzle.okr.mapper.keyresult.helper.TestDataDtoHelper.keyResultMetricDto; -import static ch.puzzle.okr.mapper.keyresult.helper.TestDataDtoHelper.keyResultOrdinalDto; -import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.keyResultMetric; -import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.keyResultOrdinal; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - @ExtendWith(MockitoExtension.class) public class KeyResultMapperTest { @@ -46,16 +45,16 @@ public class KeyResultMapperTest { @BeforeEach void setup() { KeyResultMetricMapper keyResultMetricMapper = new KeyResultMetricMapper( // - userBusinessService, // - objectiveBusinessService, // - checkInBusinessService, // - actionMapper); + userBusinessService, // + objectiveBusinessService, // + checkInBusinessService, // + actionMapper); KeyResultOrdinalMapper keyResultOrdinalMapper = new KeyResultOrdinalMapper( // - userBusinessService, // - objectiveBusinessService, // - checkInBusinessService, // - actionMapper); + userBusinessService, // + objectiveBusinessService, // + checkInBusinessService, // + actionMapper); keyResultMapper = new KeyResultMapper(keyResultOrdinalMapper, keyResultMetricMapper); } @@ -124,8 +123,8 @@ void toDtoShouldThrowExceptionIfKeyResultIsNotMetricOrOrdinal() { // act + assert ResponseStatusException responseStatusException = assertThrows( // - ResponseStatusException.class, // - () -> keyResultMapper.toDto(keyResult, actions)); + ResponseStatusException.class, // + () -> keyResultMapper.toDto(keyResult, actions)); assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode()); } @@ -137,8 +136,8 @@ void toKeyResultShouldThrowExceptionIfKeyResultDtoIsNotMetricOrOrdinal() { // act + assert ResponseStatusException responseStatusException = assertThrows( // - ResponseStatusException.class, // - () -> keyResultMapper.toKeyResult(keyResultDto)); + ResponseStatusException.class, // + () -> keyResultMapper.toKeyResult(keyResultDto)); assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode()); } } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapperTest.java index e6efdb524e..7c00f6aaa7 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultMetricMapperTest.java @@ -1,5 +1,11 @@ package ch.puzzle.okr.mapper.keyresult; +import static ch.puzzle.okr.mapper.keyresult.helper.AssertHelper.*; +import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultMetricDto; import ch.puzzle.okr.mapper.ActionMapper; @@ -15,6 +21,7 @@ import ch.puzzle.okr.service.business.UserBusinessService; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -23,14 +30,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - -import static ch.puzzle.okr.mapper.keyresult.helper.AssertHelper.*; -import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.*; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class KeyResultMetricMapperTest { @@ -54,10 +53,10 @@ public class KeyResultMetricMapperTest { void setup() { actionMapper = new ActionMapper(keyResultBusinessService); keyResultMetricMapper = new KeyResultMetricMapper( // - userBusinessService, // - objectiveBusinessService, // - checkInBusinessService, // - actionMapper); + userBusinessService, // + objectiveBusinessService, // + checkInBusinessService, // + actionMapper); } @DisplayName("toDto() should map a KeyResultMetric to a Dto") diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapperTest.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapperTest.java index dbc631e1d5..8fd59853db 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/KeyResultOrdinalMapperTest.java @@ -1,5 +1,11 @@ package ch.puzzle.okr.mapper.keyresult; +import static ch.puzzle.okr.mapper.keyresult.helper.AssertHelper.*; +import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.dto.keyresult.KeyResultOrdinalDto; import ch.puzzle.okr.mapper.ActionMapper; @@ -15,6 +21,7 @@ import ch.puzzle.okr.service.business.UserBusinessService; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -23,14 +30,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - -import static ch.puzzle.okr.mapper.keyresult.helper.AssertHelper.*; -import static ch.puzzle.okr.mapper.keyresult.helper.TestDataHelper.*; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) public class KeyResultOrdinalMapperTest { @@ -55,10 +54,10 @@ public class KeyResultOrdinalMapperTest { void setup() { actionMapper = new ActionMapper(keyResultBusinessService); keyResultOrdinalMapper = new KeyResultOrdinalMapper( // - userBusinessService, // - objectiveBusinessService, // - checkInBusinessService, // - actionMapper); + userBusinessService, // + objectiveBusinessService, // + checkInBusinessService, // + actionMapper); } @DisplayName("toDto() should map a KeyResultOrdinal with CheckIn to a Dto") diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/AssertHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/AssertHelper.java index fe66213e59..6441f5f0dd 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/AssertHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/AssertHelper.java @@ -1,5 +1,10 @@ package ch.puzzle.okr.mapper.keyresult.helper; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; +import static ch.puzzle.okr.mapper.keyresult.helper.TestDataDtoHelper.lastCheckInMetricDto; +import static org.junit.jupiter.api.Assertions.*; + import ch.puzzle.okr.dto.ActionDto; import ch.puzzle.okr.dto.keyresult.*; import ch.puzzle.okr.models.Action; @@ -8,18 +13,12 @@ import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; - import java.util.List; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; -import static ch.puzzle.okr.mapper.keyresult.helper.TestDataDtoHelper.lastCheckInMetricDto; -import static org.junit.jupiter.api.Assertions.*; - public class AssertHelper { public static void assertKeyResultMetricDtoWithCheckIn(KeyResultMetric expected, KeyResultMetricDto actual, - List actions) { + List actions) { assertKeyResultMetricDto(expected, actual, actions); // checkIn is only available on KeyResultMetricDto (and not on KeyResultMetric). // So check actual against the checkInMetricDto from TestDataDtoHelper @@ -28,13 +27,13 @@ public static void assertKeyResultMetricDtoWithCheckIn(KeyResultMetric expected, } public static void assertKeyResultMetricDtoWithoutCheckIn(KeyResultMetric expected, KeyResultMetricDto actual, - List actions) { + List actions) { assertKeyResultMetricDto(expected, actual, actions); assertNull(actual.lastCheckIn()); } private static void assertKeyResultMetricDto(KeyResultMetric expected, KeyResultMetricDto actual, - List actions) { + List actions) { assertEquals(KEY_RESULT_TYPE_METRIC, actual.keyResultType()); assertEquals(expected.getKeyResultType(), actual.keyResultType()); @@ -71,22 +70,23 @@ public static void assertKeyResultMetric(KeyResultMetricDto expected, KeyResultM } public static void assertKeyResultOrdinalDtoWithCheckIn(KeyResultOrdinal expected, KeyResultOrdinalDto actual, - List actions) { + List actions) { assertKeyResultOrdinalDto(expected, actual, actions); assertNotNull(actual.lastCheckIn()); assertCheckInOrdinalDto(TestDataDtoHelper.lastCheckInOrdinalDto(), actual.lastCheckIn()); } public static void assertKeyResultOrdinalDtoWithoutCheckIn(KeyResultOrdinal expected, KeyResultOrdinalDto actual, - List actions) { + List actions) { assertKeyResultOrdinalDto(expected, actual, actions); - // checkIn is only available on KeyResultOrdinalDto (and not on KeyResultOrdinal). + // checkIn is only available on KeyResultOrdinalDto (and not on + // KeyResultOrdinal). // So check actual against the KeyResultOrdinalDto from TestDataDtoHelper assertNull(actual.lastCheckIn()); } private static void assertKeyResultOrdinalDto(KeyResultOrdinal expected, KeyResultOrdinalDto actual, - List actions) { + List actions) { assertEquals(KEY_RESULT_TYPE_ORDINAL, actual.keyResultType()); assertEquals(expected.getKeyResultType(), actual.keyResultType()); @@ -170,7 +170,7 @@ private static void assertOwner(KeyResultUserDto expected, User actual) { } private static void assertCheckInMetricDto(KeyResultLastCheckInMetricDto expected, - KeyResultLastCheckInMetricDto actual) { + KeyResultLastCheckInMetricDto actual) { assertEquals(expected.id(), actual.id()); assertEquals(expected.version(), actual.version()); assertEquals(expected.value(), actual.value()); @@ -181,7 +181,7 @@ private static void assertCheckInMetricDto(KeyResultLastCheckInMetricDto expecte } private static void assertCheckInOrdinalDto(KeyResultLastCheckInOrdinalDto expected, - KeyResultLastCheckInOrdinalDto actual) { + KeyResultLastCheckInOrdinalDto actual) { assertEquals(expected.id(), actual.id()); assertEquals(expected.version(), actual.version()); assertEquals(expected.value(), actual.value()); diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataConstants.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataConstants.java index eff5381a5a..8e51b53ff3 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataConstants.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataConstants.java @@ -3,7 +3,6 @@ import ch.puzzle.okr.models.State; import ch.puzzle.okr.models.Unit; import ch.puzzle.okr.models.checkin.Zone; - import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataDtoHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataDtoHelper.java index ed836d442b..91344c5026 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataDtoHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataDtoHelper.java @@ -1,11 +1,11 @@ package ch.puzzle.okr.mapper.keyresult.helper; -import ch.puzzle.okr.dto.keyresult.*; - import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; import static ch.puzzle.okr.mapper.keyresult.helper.TestDataConstants.*; +import ch.puzzle.okr.dto.keyresult.*; + public class TestDataDtoHelper { public static KeyResultMetricDto keyResultMetricDto() { return keyResultMetricDto; @@ -24,78 +24,85 @@ public static KeyResultLastCheckInOrdinalDto lastCheckInOrdinalDto() { } private static final KeyResultUserDto ownerDto = new KeyResultUserDto( // - USER_ID, // - USER_FIRSTNAME, // - USER_LASTNAME // + USER_ID, // + USER_FIRSTNAME, // + USER_LASTNAME // ); private static final KeyResultQuarterDto quarterDto = new KeyResultQuarterDto( // - QUARTER_ID, // - QUARTER_LABEL, // - QUARTER_START_DATE, // - QUARTER_END_DATE // + QUARTER_ID, // + QUARTER_LABEL, // + QUARTER_START_DATE, // + QUARTER_END_DATE // ); private static final KeyResultObjectiveDto objectiveDto = new KeyResultObjectiveDto( // - OBJECTIVE_ID, // - OBJECTIVE_STATE.name(), // - quarterDto // + OBJECTIVE_ID, // + OBJECTIVE_STATE.name(), // + quarterDto // ); private static final KeyResultLastCheckInMetricDto lastCheckInMetricDto = new KeyResultLastCheckInMetricDto( // - CHECK_IN_ID, // - CHECK_IN_VERSION, // - CHECK_IN_METRIC_VALUE, // - CHECK_IN_CONFIDENCE, // - CHECK_IN_CREATED_ON, // - CHECK_IN_CHANGE_INFO, // - CHECK_IN_INITIATIVES // + CHECK_IN_ID, // + CHECK_IN_VERSION, // + CHECK_IN_METRIC_VALUE, // + CHECK_IN_CONFIDENCE, // + CHECK_IN_CREATED_ON, // + CHECK_IN_CHANGE_INFO, // + CHECK_IN_INITIATIVES // ); private static final KeyResultLastCheckInOrdinalDto lastCheckInOrdinalDto = new KeyResultLastCheckInOrdinalDto( // - CHECK_IN_ID, // - CHECK_IN_VERSION, // - CHECK_IN_ORDINAL_ZONE, // - CHECK_IN_CONFIDENCE, // - CHECK_IN_CREATED_ON, // - CHECK_IN_CHANGE_INFO, // - CHECK_IN_INITIATIVES // + CHECK_IN_ID, // + CHECK_IN_VERSION, // + CHECK_IN_ORDINAL_ZONE, // + CHECK_IN_CONFIDENCE, // + CHECK_IN_CREATED_ON, // + CHECK_IN_CHANGE_INFO, // + CHECK_IN_INITIATIVES // ); private static final KeyResultMetricDto keyResultMetricDto = new KeyResultMetricDto( // - KEY_RESULT_ID, // - KEY_RESULT_VERSION, // - KEY_RESULT_TYPE_METRIC, // - KEY_RESULT_TITLE, // - KEY_RESULT_DESCRIPTION, // - KEY_RESULT_BASELINE, // - KEY_RESULT_STRETCH_GOAL, // - KEY_RESULT_UNIT, // - ownerDto, // - objectiveDto, // - lastCheckInMetricDto, // - CHECK_IN_CREATED_ON, // - CHECK_IN_MODIFIED_ON, // - CHECK_IN_IS_WRITABLE, // - null // actionList; ony used for keyResultMetric + action -> dto BUT NOT FOR dto -> keyResultMetric + KEY_RESULT_ID, // + KEY_RESULT_VERSION, // + KEY_RESULT_TYPE_METRIC, // + KEY_RESULT_TITLE, // + KEY_RESULT_DESCRIPTION, // + KEY_RESULT_BASELINE, // + KEY_RESULT_STRETCH_GOAL, // + KEY_RESULT_UNIT, // + ownerDto, // + objectiveDto, // + lastCheckInMetricDto, // + CHECK_IN_CREATED_ON, // + CHECK_IN_MODIFIED_ON, // + CHECK_IN_IS_WRITABLE, // + null // actionList; ony used for + // keyResultMetric + action + // -> dto BUT NOT FOR dto + // -> keyResultMetric ); private static final KeyResultOrdinalDto keyResultOrdinalDto = new KeyResultOrdinalDto( // - KEY_RESULT_ID, // - KEY_RESULT_VERSION, // - KEY_RESULT_TYPE_ORDINAL, // - KEY_RESULT_TITLE, // - KEY_RESULT_DESCRIPTION, // - KEY_RESULT_COMMIT_ZONE, // - KEY_RESULT_TARGET_ZONE, // - KEY_RESULT_STRETCH_ZONE, // - ownerDto, // - objectiveDto, // - lastCheckInOrdinalDto, // - CHECK_IN_CREATED_ON, // - CHECK_IN_MODIFIED_ON, // - CHECK_IN_IS_WRITABLE, // - null // actionList; ony used for keyResultOrdinal + action -> dto BUT NOT FOR dto -> keyResultOrdinal + KEY_RESULT_ID, // + KEY_RESULT_VERSION, // + KEY_RESULT_TYPE_ORDINAL, // + KEY_RESULT_TITLE, // + KEY_RESULT_DESCRIPTION, // + KEY_RESULT_COMMIT_ZONE, // + KEY_RESULT_TARGET_ZONE, // + KEY_RESULT_STRETCH_ZONE, // + ownerDto, // + objectiveDto, // + lastCheckInOrdinalDto, // + CHECK_IN_CREATED_ON, // + CHECK_IN_MODIFIED_ON, // + CHECK_IN_IS_WRITABLE, // + null // actionList; ony used + // for keyResultOrdinal + // + action -> dto BUT + // NOT FOR dto -> + // keyResultOrdinal ); } diff --git a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataHelper.java b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataHelper.java index 365999229f..dd09d7b5c6 100644 --- a/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/mapper/keyresult/helper/TestDataHelper.java @@ -1,5 +1,7 @@ package ch.puzzle.okr.mapper.keyresult.helper; +import static ch.puzzle.okr.mapper.keyresult.helper.TestDataConstants.*; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.Quarter; @@ -11,8 +13,6 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; -import static ch.puzzle.okr.mapper.keyresult.helper.TestDataConstants.*; - public class TestDataHelper { public static KeyResultMetric keyResultMetric() { @@ -52,86 +52,88 @@ public static Objective objective() { } private static final CheckIn checkInMetric = CheckInMetric.Builder.builder() // - .withId(CHECK_IN_ID) // - .withVersion(CHECK_IN_VERSION) // - .withValue(CHECK_IN_METRIC_VALUE) // - .withConfidence(CHECK_IN_CONFIDENCE) // - .withCreatedOn(CHECK_IN_CREATED_ON) // - .withChangeInfo(CHECK_IN_CHANGE_INFO) // - .withInitiatives(CHECK_IN_INITIATIVES) // - .build(); + .withId(CHECK_IN_ID) // + .withVersion(CHECK_IN_VERSION) // + .withValue(CHECK_IN_METRIC_VALUE) // + .withConfidence(CHECK_IN_CONFIDENCE) // + .withCreatedOn(CHECK_IN_CREATED_ON) // + .withChangeInfo(CHECK_IN_CHANGE_INFO) // + .withInitiatives(CHECK_IN_INITIATIVES) // + .build(); private static final CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder() // - .withId(CHECK_IN_ID) // - .withVersion(CHECK_IN_VERSION) // - .withZone(CHECK_IN_ORDINAL_ZONE) // - .withConfidence(CHECK_IN_CONFIDENCE) // - .withCreatedOn(CHECK_IN_CREATED_ON) // - .withChangeInfo(CHECK_IN_CHANGE_INFO) // - .withInitiatives(CHECK_IN_INITIATIVES) // - .build(); + .withId(CHECK_IN_ID) // + .withVersion(CHECK_IN_VERSION) // + .withZone(CHECK_IN_ORDINAL_ZONE) // + .withConfidence(CHECK_IN_CONFIDENCE) // + .withCreatedOn(CHECK_IN_CREATED_ON) // + .withChangeInfo(CHECK_IN_CHANGE_INFO) // + .withInitiatives(CHECK_IN_INITIATIVES) // + .build(); private static final User owner = User.Builder.builder() // - .withId(USER_ID) // - .withFirstname(USER_FIRSTNAME) // - .withLastname(USER_LASTNAME) // - .build(); + .withId(USER_ID) // + .withFirstname(USER_FIRSTNAME) // + .withLastname(USER_LASTNAME) // + .build(); private static final Quarter quarter = Quarter.Builder.builder() // - .withId(QUARTER_ID) // - .withLabel(QUARTER_LABEL) // - .withStartDate(QUARTER_START_DATE) // - .withEndDate(QUARTER_END_DATE) // - .build(); + .withId(QUARTER_ID) // + .withLabel(QUARTER_LABEL) // + .withStartDate(QUARTER_START_DATE) // + .withEndDate(QUARTER_END_DATE) // + .build(); private static final Objective objective = Objective.Builder.builder() // - .withId(OBJECTIVE_ID) // - .withQuarter(quarter) // - .withState(OBJECTIVE_STATE) // - .build(); + .withId(OBJECTIVE_ID) // + .withQuarter(quarter) // + .withState(OBJECTIVE_STATE) // + .build(); private static final KeyResult keyResultMetric = KeyResultMetric.Builder.builder() // - .withId(KEY_RESULT_ID) // - .withVersion(KEY_RESULT_VERSION) // - .withTitle(KEY_RESULT_TITLE) // - .withDescription(KEY_RESULT_DESCRIPTION) // - .withBaseline(KEY_RESULT_BASELINE) // - .withStretchGoal(KEY_RESULT_STRETCH_GOAL) // - .withUnit(KEY_RESULT_UNIT) // - .withOwner(owner) // - .withObjective(objective) // - .withCreatedOn(CHECK_IN_CREATED_ON) // - .withModifiedOn(CHECK_IN_MODIFIED_ON) // - .build(); + .withId(KEY_RESULT_ID) // + .withVersion(KEY_RESULT_VERSION) // + .withTitle(KEY_RESULT_TITLE) // + .withDescription(KEY_RESULT_DESCRIPTION) // + .withBaseline(KEY_RESULT_BASELINE) // + .withStretchGoal(KEY_RESULT_STRETCH_GOAL) // + .withUnit(KEY_RESULT_UNIT) // + .withOwner(owner) // + .withObjective(objective) // + .withCreatedOn(CHECK_IN_CREATED_ON) // + .withModifiedOn(CHECK_IN_MODIFIED_ON) // + .build(); private static final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() // - .withId(KEY_RESULT_ID) // - .withVersion(KEY_RESULT_VERSION) // - .withTitle(KEY_RESULT_TITLE) // - .withDescription(KEY_RESULT_DESCRIPTION) // - .withCommitZone(KEY_RESULT_COMMIT_ZONE).withTargetZone(KEY_RESULT_TARGET_ZONE) - .withStretchZone(KEY_RESULT_STRETCH_ZONE).withOwner(owner) // - .withObjective(objective) // - .withCreatedOn(CHECK_IN_CREATED_ON) // - .withModifiedOn(CHECK_IN_MODIFIED_ON) // - .build(); + .withId(KEY_RESULT_ID) // + .withVersion(KEY_RESULT_VERSION) // + .withTitle(KEY_RESULT_TITLE) // + .withDescription(KEY_RESULT_DESCRIPTION) // + .withCommitZone(KEY_RESULT_COMMIT_ZONE) + .withTargetZone(KEY_RESULT_TARGET_ZONE) + .withStretchZone(KEY_RESULT_STRETCH_ZONE) + .withOwner(owner) // + .withObjective(objective) // + .withCreatedOn(CHECK_IN_CREATED_ON) // + .withModifiedOn(CHECK_IN_MODIFIED_ON) // + .build(); private static final Action actionForKeyResultMetric = Action.Builder.builder() // - .withId(ACTION_ID) // - .withVersion(ACTION_VERSION) // - .withAction(ACTION_ACTION) // - .withPriority(ACTION_PRIORITY) // - .withIsChecked(ACTION_IS_CHECKED) // - .withKeyResult(keyResultMetric) // - .build(); + .withId(ACTION_ID) // + .withVersion(ACTION_VERSION) // + .withAction(ACTION_ACTION) // + .withPriority(ACTION_PRIORITY) // + .withIsChecked(ACTION_IS_CHECKED) // + .withKeyResult(keyResultMetric) // + .build(); private static final Action actionForKeyResultOrdinal = Action.Builder.builder() // - .withId(ACTION_ID) // - .withVersion(ACTION_VERSION) // - .withAction(ACTION_ACTION) // - .withPriority(ACTION_PRIORITY) // - .withIsChecked(ACTION_IS_CHECKED) // - .withKeyResult(keyResultOrdinal) // - .build(); + .withId(ACTION_ID) // + .withVersion(ACTION_VERSION) // + .withAction(ACTION_ACTION) // + .withPriority(ACTION_PRIORITY) // + .withIsChecked(ACTION_IS_CHECKED) // + .withKeyResult(keyResultOrdinal) // + .build(); } diff --git a/backend/src/test/java/ch/puzzle/okr/models/authorization/AuthorizationUserTest.java b/backend/src/test/java/ch/puzzle/okr/models/authorization/AuthorizationUserTest.java index 2b74f3dc69..29f9392da3 100644 --- a/backend/src/test/java/ch/puzzle/okr/models/authorization/AuthorizationUserTest.java +++ b/backend/src/test/java/ch/puzzle/okr/models/authorization/AuthorizationUserTest.java @@ -1,22 +1,35 @@ package ch.puzzle.okr.models.authorization; -import ch.puzzle.okr.test.TestHelper; +import static org.junit.jupiter.api.Assertions.*; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.UserTeam; -import org.junit.jupiter.api.Test; - +import ch.puzzle.okr.test.TestHelper; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class AuthorizationUserTest { - private final List userTeamList = List.of( - UserTeam.Builder.builder().withTeam(TestHelper.defaultTeam(1L)).withTeamAdmin(true).build(), - UserTeam.Builder.builder().withTeam(TestHelper.defaultTeam(2L)).withTeamAdmin(false).build(), - UserTeam.Builder.builder().withTeam(TestHelper.defaultTeam(3L)).withTeamAdmin(true).build(), - UserTeam.Builder.builder().withTeam(TestHelper.defaultTeam(4L)).withTeamAdmin(false).build(), - UserTeam.Builder.builder().withTeam(TestHelper.defaultTeam(5L)).withTeamAdmin(false).build()); + private final List userTeamList = List.of(UserTeam.Builder.builder() + .withTeam(TestHelper.defaultTeam(1L)) + .withTeamAdmin(true) + .build(), + UserTeam.Builder.builder() + .withTeam(TestHelper.defaultTeam(2L)) + .withTeamAdmin(false) + .build(), + UserTeam.Builder.builder() + .withTeam(TestHelper.defaultTeam(3L)) + .withTeamAdmin(true) + .build(), + UserTeam.Builder.builder() + .withTeam(TestHelper.defaultTeam(4L)) + .withTeamAdmin(false) + .build(), + UserTeam.Builder.builder() + .withTeam(TestHelper.defaultTeam(5L)) + .withTeamAdmin(false) + .build()); private final User user = User.Builder.builder().withUserTeamList(userTeamList).build(); private final AuthorizationUser authorizationUser = new AuthorizationUser(user); diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/CurrentTenantIdentifierResolverImplTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/CurrentTenantIdentifierResolverImplTest.java index 87d82c4c21..d51702037a 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/CurrentTenantIdentifierResolverImplTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/CurrentTenantIdentifierResolverImplTest.java @@ -1,11 +1,11 @@ package ch.puzzle.okr.multitenancy; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + public class CurrentTenantIdentifierResolverImplTest { @DisplayName("current TenantId is TenantId from TenantContext") diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializerTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializerTest.java index 3ab1cb4eb4..b3cdf947af 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializerTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializerTest.java @@ -1,5 +1,10 @@ package ch.puzzle.okr.multitenancy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; + +import java.util.List; +import java.util.Optional; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.configuration.FluentConfiguration; import org.junit.jupiter.api.DisplayName; @@ -7,20 +12,18 @@ import org.mockito.MockedStatic; import org.mockito.Mockito; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; - /** - * Test for FlywayMultitenantMigrationInitializer.migrateFlyway(). The FlywayMultitenantMigrationInitializer constructor - * gets a mock implementation of a TenantConfigProviderInterface, which provides some test data. Inside migrateFlyway(), - * there are two calls to Flyway: Flyway.configure() (a static method) and flyway.migrate() (an instance method). - * Flyway.configure() returns a FluentConfiguration. Then several method calls are made on the FluentConfiguration, - * which also return a FluentConfiguration. The last calls is load(), which returns a Flyway Object. We can mock that - * with a manual Spy FluentConfigurationSpy, which records the methods calls and load() returns a Mockito Mock, which - * does nothing. And later, flyway.migrate() is called on the Mockito Mock, which does nothing. + * Test for FlywayMultitenantMigrationInitializer.migrateFlyway(). The + * FlywayMultitenantMigrationInitializer constructor gets a mock implementation + * of a TenantConfigProviderInterface, which provides some test data. Inside + * migrateFlyway(), there are two calls to Flyway: Flyway.configure() (a static + * method) and flyway.migrate() (an instance method). Flyway.configure() returns + * a FluentConfiguration. Then several method calls are made on the + * FluentConfiguration, which also return a FluentConfiguration. The last calls + * is load(), which returns a Flyway Object. We can mock that with a manual Spy + * FluentConfigurationSpy, which records the methods calls and load() returns a + * Mockito Mock, which does nothing. And later, flyway.migrate() is called on + * the Mockito Mock, which does nothing. */ public class FlywayMultitenantMigrationInitializerTest { @@ -54,7 +57,8 @@ public FluentConfiguration schemas(String... schemas) { return this; } - // the result of load() is used by flyway.migrate(), which we don't test. So load() returns a mock which does + // the result of load() is used by flyway.migrate(), which we don't test. So + // load() returns a mock which does // nothing. @Override public Flyway load() { @@ -68,11 +72,19 @@ public String getLog() { private final TenantConfigProviderInterface providerInterfaceMock = new TenantConfigProviderInterface() { - private final TenantConfigProvider.DataSourceConfig dataSourceConfig = new TenantConfigProvider.DataSourceConfig( - NOT_USED, URL, NAME, PASSWORD, SCHEMA); + private final TenantConfigProvider.DataSourceConfig dataSourceConfig = new TenantConfigProvider.DataSourceConfig(NOT_USED, + URL, + NAME, + PASSWORD, + SCHEMA); private final TenantConfigProvider.TenantConfig tenantConfig = new TenantConfigProvider.TenantConfig(NOT_USED, - new String[] { NOT_USED }, NOT_USED, NOT_USED, NOT_USED, dataSourceConfig); + new String[]{ + NOT_USED}, + NOT_USED, + NOT_USED, + NOT_USED, + dataSourceConfig); @Override public List getTenantConfigs() { @@ -98,8 +110,9 @@ void flywayConfigureShouldReturnFluentConfigurationWhichWeCanAssert() { FluentConfigurationSpy fluentConfiguration = new FluentConfigurationSpy(); mockedStatic.when(Flyway::configure).thenReturn(fluentConfiguration); - FlywayMultitenantMigrationInitializer migrationInitializer = new FlywayMultitenantMigrationInitializer( - providerInterfaceMock, new String[] { SCRIPT_LOCATION }); + FlywayMultitenantMigrationInitializer migrationInitializer = new FlywayMultitenantMigrationInitializer(providerInterfaceMock, + new String[]{ + SCRIPT_LOCATION}); // act migrationInitializer.migrateFlyway(); diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/HibernateContextTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/HibernateContextTest.java index 7dbc3a5b16..14b1933cb0 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/HibernateContextTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/HibernateContextTest.java @@ -1,5 +1,12 @@ package ch.puzzle.okr.multitenancy; +import static ch.puzzle.okr.multitenancy.HibernateContext.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Properties; +import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -8,14 +15,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.springframework.core.env.ConfigurableEnvironment; -import java.util.Properties; -import java.util.stream.Stream; - -import static ch.puzzle.okr.multitenancy.HibernateContext.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class HibernateContextTest { @BeforeEach @@ -38,7 +37,7 @@ void setHibernateConfigShouldThrowExceptionIfDbConfigIsNull() { @ParameterizedTest @MethodSource("invalidDbConfig") void setHibernateConfigShouldThrowExceptionIfDbConfigHasNullOrEmptyValues(String url, String username, - String password, String tenant) { + String password, String tenant) { // arrange DbConfig dbConfig = new DbConfig(url, username, password, tenant); @@ -50,14 +49,14 @@ void setHibernateConfigShouldThrowExceptionIfDbConfigHasNullOrEmptyValues(String private static Stream invalidDbConfig() { return Stream.of( // - Arguments.of(null, "username", "password", "multiTenancy"), // - Arguments.of("", "username", "password", "multiTenancy"), // - Arguments.of("url", null, "password", "multiTenancy"), // - Arguments.of("url", "", "password", "multiTenancy"), // - Arguments.of("url", "username", null, "multiTenancy"), // - Arguments.of("url", "username", "", "multiTenancy"), // - Arguments.of("url", "username", "password", null), // - Arguments.of("url", "username", "password", "")); + Arguments.of(null, "username", "password", "multiTenancy"), // + Arguments.of("", "username", "password", "multiTenancy"), // + Arguments.of("url", null, "password", "multiTenancy"), // + Arguments.of("url", "", "password", "multiTenancy"), // + Arguments.of("url", "username", null, "multiTenancy"), // + Arguments.of("url", "username", "", "multiTenancy"), // + Arguments.of("url", "username", "password", null), // + Arguments.of("url", "username", "password", "")); } @DisplayName("extractAndSetHibernateConfig() should extract hibernate properties from environment and set it") @@ -108,7 +107,7 @@ void getHibernateConfigShouldReturnHibernateConfigAsPropertiesIfDbConfigIsValid( } private void assertProperties(String url, String username, String password, String multiTenancy, - Properties properties) { + Properties properties) { assertEquals(url, properties.get(HIBERNATE_CONNECTION_URL)); assertEquals(username, properties.get(HIBERNATE_CONNECTION_USERNAME)); diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderInternalsTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderInternalsTest.java index e8bc0dc7b0..d160620805 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderInternalsTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderInternalsTest.java @@ -1,15 +1,14 @@ package ch.puzzle.okr.multitenancy; +import static org.mockito.Mockito.mock; + import ch.puzzle.okr.exception.ConnectionProviderException; +import java.util.Properties; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.Properties; - -import static org.mockito.Mockito.mock; - public class SchemaMultiTenantConnectionProviderInternalsTest { private static final String TENANT_ID = "pitc"; diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderTest.java index e9a97a6d14..cb1b61be46 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/SchemaMultiTenantConnectionProviderTest.java @@ -1,16 +1,15 @@ package ch.puzzle.okr.multitenancy; -import ch.puzzle.okr.test.SpringIntegrationTest; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import ch.puzzle.okr.test.SpringIntegrationTest; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; @SpringIntegrationTest public class SchemaMultiTenantConnectionProviderTest { diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/TenantConfigProviderTestIT.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/TenantConfigProviderTestIT.java index 940473d020..5d2248fff5 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/TenantConfigProviderTestIT.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/TenantConfigProviderTestIT.java @@ -1,6 +1,12 @@ package ch.puzzle.okr.multitenancy; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.test.SpringIntegrationTest; +import java.text.MessageFormat; +import java.util.List; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -10,13 +16,6 @@ import org.springframework.boot.SpringBootConfiguration; import org.springframework.core.env.Environment; -import java.text.MessageFormat; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.when; - @SpringIntegrationTest @SpringBootConfiguration public class TenantConfigProviderTestIT { @@ -32,7 +31,7 @@ public class TenantConfigProviderTestIT { private static final String CHAMPION_EMAILS_2 = "b@pitc.ch"; private static final String CHAMPION_EMAILS = CHAMPION_EMAILS_1 + "," + CHAMPION_EMAILS_2; - private final String[] tenantIds = { "pitc", "acme" }; + private final String[] tenantIds = {"pitc", "acme"}; @Mock private Environment env; @@ -87,7 +86,7 @@ public void testGetTenantConfigs() { @DisplayName("getTenantConfigById returns for an existing TenantId the TenantConfig as Optional") @ParameterizedTest - @CsvSource({ "pitc, acme" }) + @CsvSource({"pitc, acme"}) void testGetTenantConfigByIdForExistingTenantId(String tenantId) { TenantConfigProvider configProvider = new TenantConfigProvider(tenantIds, env); Optional config = configProvider.getTenantConfigById(tenantId); @@ -97,7 +96,7 @@ void testGetTenantConfigByIdForExistingTenantId(String tenantId) { @DisplayName("getTenantConfigById returns for a non existing TenantId an empty Optional") @ParameterizedTest - @CsvSource({ "PITC-London" }) + @CsvSource({"PITC-London"}) void testGetTenantConfigByIdForNonExistingTenantId(String nonExistingTenantId) { TenantConfigProvider configProvider = new TenantConfigProvider(tenantIds, env); Optional config = configProvider.getTenantConfigById(nonExistingTenantId); @@ -106,7 +105,7 @@ void testGetTenantConfigByIdForNonExistingTenantId(String nonExistingTenantId) { @DisplayName("getJwkSetUri returns for an existing TenantId the JwkSetUri as Optional") @ParameterizedTest - @CsvSource({ "pitc", "acme" }) + @CsvSource({"pitc", "acme"}) void testGetJwkSetUriForExistingTenantId(String tenantId) { // arrange TenantConfigProvider configProvider = new TenantConfigProvider(tenantIds, env); @@ -121,7 +120,7 @@ void testGetJwkSetUriForExistingTenantId(String tenantId) { @DisplayName("getJwkSetUri returns for a non existing TenantId an empty Optional") @ParameterizedTest - @CsvSource({ "PITC-London" }) + @CsvSource({"PITC-London"}) void testGetJwkSetUriForNonExistingTenantId(String nonExistingTenantId) { TenantConfigProvider configProvider = new TenantConfigProvider(tenantIds, env); Optional jwkSetUri = configProvider.getJwkSetUri(nonExistingTenantId); @@ -139,7 +138,7 @@ private void assertTenantConfigProvider(TenantConfigProvider.TenantConfig tenant assertEquals(prefix(tenantId) + DATASOURCE_PASSWORD, tenantConfig.dataSourceConfig().password()); assertEquals(prefix(tenantId) + DATASOURCE_SCHEMA, tenantConfig.dataSourceConfig().schema()); - assertArrayEquals(new String[] { CHAMPION_EMAILS_1, CHAMPION_EMAILS_2 }, tenantConfig.okrChampionEmails()); + assertArrayEquals(new String[]{CHAMPION_EMAILS_1, CHAMPION_EMAILS_2}, tenantConfig.okrChampionEmails()); assertEquals(DRIVER_CLASS_NAME, tenantConfig.dataSourceConfig().driverClassName()); } diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTest.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTest.java index 9d5a393af0..bb03de6736 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTest.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTest.java @@ -1,23 +1,23 @@ package ch.puzzle.okr.multitenancy.customization; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - public class TenantClientCustomizationProviderTest { @DisplayName("extractCssNameFromPropertyName() should return css name for valid property name") @ParameterizedTest - @CsvSource({ "pitc", "acme" }) + @CsvSource({"pitc", "acme"}) void extractCssNameFromPropertyNameShouldReturnCssNameForValidPropertyName(String tenantId) { // arrange String propertyNameWithTenant = "okr.tenants." + tenantId - + ".clientcustomization.customstyles.my-css-property-name"; - TenantClientCustomizationProvider provider = new TenantClientCustomizationProvider(new String[] {}, null); + + ".clientcustomization.customstyles.my-css-property-name"; + TenantClientCustomizationProvider provider = new TenantClientCustomizationProvider(new String[]{}, null); // act String cssName = provider.extractCssNameFromPropertyName(propertyNameWithTenant, tenantId); @@ -31,10 +31,10 @@ void extractCssNameFromPropertyNameShouldReturnCssNameForValidPropertyName(Strin void extractCssNameFromPropertyNameShouldThrowIllegalArgumentExceptionForInvalidPropertyName() { // arrange String propertyNameWithoutTenant = "okr.tenants.clientcustomization.customstyles.my-css-property-name"; - TenantClientCustomizationProvider provider = new TenantClientCustomizationProvider(new String[] {}, null); + TenantClientCustomizationProvider provider = new TenantClientCustomizationProvider(new String[]{}, null); // act + assert assertThrows(IllegalArgumentException.class, - () -> provider.extractCssNameFromPropertyName(propertyNameWithoutTenant, "pitc")); + () -> provider.extractCssNameFromPropertyName(propertyNameWithoutTenant, "pitc")); } } diff --git a/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTestIT.java b/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTestIT.java index f1c5806aea..068cb2822f 100644 --- a/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTestIT.java +++ b/backend/src/test/java/ch/puzzle/okr/multitenancy/customization/TenantClientCustomizationProviderTestIT.java @@ -1,6 +1,11 @@ package ch.puzzle.okr.multitenancy.customization; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.test.SpringIntegrationTest; +import java.text.MessageFormat; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; @@ -8,12 +13,6 @@ import org.mockito.Mock; import org.springframework.core.env.Environment; -import java.text.MessageFormat; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.when; - @SpringIntegrationTest public class TenantClientCustomizationProviderTestIT { private static final String LOGO = "logo"; @@ -26,7 +25,7 @@ public class TenantClientCustomizationProviderTestIT { private static final String CUSTOM_STYLE_NAME = "okr-topbar-background-color"; private static final String CUSTOM_STYLE_VALUE = "css-custom-value"; - private final String[] tenantIds = { "pitc", "acme" }; + private final String[] tenantIds = {"pitc", "acme"}; @Mock private Environment env; @@ -45,8 +44,9 @@ private void setupPropertiesForTenantWithId(String id) { mockProperty("okr.tenants.{0}.clientcustomization.favicon", FAVICON, id); mockProperty("okr.tenants.{0}.clientcustomization.title", TITLE, id); mockProperty("okr.tenants.{0}.clientcustomization.helpSiteUrl", HELP_SITE_URL, id); - mockProperty("okr.tenants.{0}.clientcustomization.customstyles.okr-topbar-background-color", CUSTOM_STYLE_VALUE, - id); + mockProperty("okr.tenants.{0}.clientcustomization.customstyles.okr-topbar-background-color", + CUSTOM_STYLE_VALUE, + id); } private void mockProperty(String propertyName, String propertyValue, String tenantId) { @@ -60,7 +60,7 @@ private String prefix(String tenantId) { @DisplayName("getTenantClientCustomizationsById() should return TenantClientCustomization") @ParameterizedTest - @CsvSource({ "pitc", "acme" }) + @CsvSource({"pitc", "acme"}) void getTenantClientCustomizationsByIdShouldReturnTenantClientCustomization(String tenantId) { // arrange TenantClientCustomizationProvider provider = new TenantClientCustomizationProvider(tenantIds, env); diff --git a/backend/src/test/java/ch/puzzle/okr/security/AuthenticationEventsTest.java b/backend/src/test/java/ch/puzzle/okr/security/AuthenticationEventsTest.java index f73c3ecf83..371c3a3b33 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/AuthenticationEventsTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/AuthenticationEventsTest.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.security; +import static ch.puzzle.okr.multitenancy.TenantContext.DEFAULT_TENANT_ID; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.multitenancy.TenantContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -8,10 +12,6 @@ import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.jwt.Jwt; -import static ch.puzzle.okr.multitenancy.TenantContext.DEFAULT_TENANT_ID; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; - public class AuthenticationEventsTest { public static final String TENANT_FROM_TOKEN = "pitc"; @@ -54,7 +54,7 @@ private void assertTenantFromTokenIsInTenantContext() { } private void verifyGetTenantFromTokenIsCalledWithTokenFromAuthenticationSuccessEvent(JwtHelper jwtHelper, - Jwt token) { + Jwt token) { verify(jwtHelper).getTenantFromToken(token); } diff --git a/backend/src/test/java/ch/puzzle/okr/security/JwtHelperTest.java b/backend/src/test/java/ch/puzzle/okr/security/JwtHelperTest.java index 35f0367478..b6ee45e17d 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/JwtHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/JwtHelperTest.java @@ -1,23 +1,22 @@ package ch.puzzle.okr.security; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantConfigProvider; import com.nimbusds.jwt.JWTClaimsSet; import jakarta.persistence.EntityNotFoundException; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.security.oauth2.jwt.Jwt; - import java.text.ParseException; import java.util.Map; import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.springframework.http.HttpStatus.BAD_REQUEST; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.security.oauth2.jwt.Jwt; public class JwtHelperTest { @@ -38,13 +37,18 @@ void getUserFromJwtExtractsUserDataFromToken() { // arrange Jwt tokenWithUserDataMock = mock(Jwt.class); when(tokenWithUserDataMock.getClaims()).thenReturn(Map.of( // - TOKEN_CLAIMS_KEY_FIRSTNAME, HANS, // - TOKEN_CLAIMS_KEY_LASTNAME, MUSTER, // - TOKEN_CLAIMS_KEY_EMAIL, EMAIL // + TOKEN_CLAIMS_KEY_FIRSTNAME, + HANS, // + TOKEN_CLAIMS_KEY_LASTNAME, + MUSTER, // + TOKEN_CLAIMS_KEY_EMAIL, + EMAIL // )); JwtHelper jwtHelper = new JwtHelper(null, // - TOKEN_CLAIMS_KEY_FIRSTNAME, TOKEN_CLAIMS_KEY_LASTNAME, TOKEN_CLAIMS_KEY_EMAIL); + TOKEN_CLAIMS_KEY_FIRSTNAME, + TOKEN_CLAIMS_KEY_LASTNAME, + TOKEN_CLAIMS_KEY_EMAIL); // act User userFromToken = jwtHelper.getUserFromJwt(tokenWithUserDataMock); @@ -63,7 +67,9 @@ void getUserFromJwtThrowsExceptionIfTokenNotContainsUserData() { Jwt tokenWithNoUserDataMock = mock(Jwt.class); JwtHelper jwtHelper = new JwtHelper(null, // - TOKEN_CLAIMS_KEY_FIRSTNAME, TOKEN_CLAIMS_KEY_LASTNAME, TOKEN_CLAIMS_KEY_EMAIL); + TOKEN_CLAIMS_KEY_FIRSTNAME, + TOKEN_CLAIMS_KEY_LASTNAME, + TOKEN_CLAIMS_KEY_EMAIL); // act + assert OkrResponseStatusException okrResponseStatusException = // @@ -82,9 +88,12 @@ void getTenantFromTokenReturnsTenantIfTenantFoundInTenantConfigProvider() { TenantConfigProvider tenantConfigProviderMock = mock(TenantConfigProvider.class); when(tenantConfigProviderMock.getTenantConfigById(PITC)).thenReturn(Optional.of( // - new TenantConfigProvider.TenantConfig(PITC, // - new String[] {}, "jwkSetUri", "issuerUrl", // - "clientId", null) // + new TenantConfigProvider.TenantConfig(PITC, // + new String[]{}, + "jwkSetUri", + "issuerUrl", // + "clientId", + null) // )); JwtHelper jwtHelper = new JwtHelper(tenantConfigProviderMock, null, null, null); @@ -120,9 +129,12 @@ void getTenantFromJWTClaimsSetReturnsTenantIfTenantFoundInTenantConfigProvider() TenantConfigProvider tenantConfigProviderWithDataMock = mock(TenantConfigProvider.class); when(tenantConfigProviderWithDataMock.getTenantConfigById(PITC)).thenReturn(Optional.of( // - new TenantConfigProvider.TenantConfig(PITC, // - new String[] {}, "jwkSetUri", "issuerUrl", // - "clientId", null) // + new TenantConfigProvider.TenantConfig(PITC, // + new String[]{}, + "jwkSetUri", + "issuerUrl", // + "clientId", + null) // )); JwtHelper jwtHelper = new JwtHelper(tenantConfigProviderWithDataMock, null, null, null); diff --git a/backend/src/test/java/ch/puzzle/okr/security/TenantJWSKeySelectorTest.java b/backend/src/test/java/ch/puzzle/okr/security/TenantJWSKeySelectorTest.java index f02c34d5c1..7343fd3bce 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/TenantJWSKeySelectorTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/TenantJWSKeySelectorTest.java @@ -1,21 +1,20 @@ package ch.puzzle.okr.security; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.multitenancy.TenantConfigProvider; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.KeySourceException; import com.nimbusds.jose.proc.JWSKeySelector; import com.nimbusds.jose.proc.SecurityContext; import com.nimbusds.jwt.JWTClaimsSet; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - import java.security.Key; import java.util.List; import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; public class TenantJWSKeySelectorTest { private static final String PITC = "pitc"; @@ -40,7 +39,9 @@ void selectKeysThrowsExceptionIfTenantConfigIsNotFound() { // act + assert TenantJWSKeySelector selector = new TenantJWSKeySelector(emptyTenantConfigProviderMock, jwtHelperMock); IllegalArgumentException illegalArgumentException = assertThrows(IllegalArgumentException.class, // - () -> selector.selectKeys(jwsHeaderMock, jwtClaimsSetMock, securityContext)); + () -> selector.selectKeys(jwsHeaderMock, + jwtClaimsSetMock, + securityContext)); assertEquals(UNKNOWN_TENANT, illegalArgumentException.getLocalizedMessage()); } diff --git a/backend/src/test/java/ch/puzzle/okr/security/TenantJwtIssuerValidatorTest.java b/backend/src/test/java/ch/puzzle/okr/security/TenantJwtIssuerValidatorTest.java index 7c675c4204..f7d0f7f738 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/TenantJwtIssuerValidatorTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/TenantJwtIssuerValidatorTest.java @@ -1,19 +1,18 @@ package ch.puzzle.okr.security; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.multitenancy.TenantConfigProvider; +import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtIssuerValidator; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class TenantJwtIssuerValidatorTest { private static final String PITC = "pitc"; @@ -49,12 +48,16 @@ void validateReturnOAuth2TokenValidatorResultIfTenantConfigWithIssuerUrlIsFound( TenantConfigProvider tenantConfigProviderWithPitcConfig = mock(TenantConfigProvider.class); when(tenantConfigProviderWithPitcConfig.getTenantConfigById(PITC)).thenReturn(Optional.of( // - new TenantConfigProvider.TenantConfig( // - PITC, new String[] {}, "jwkSetUri", // - ISSUER_URL, "clientId", null))); - - TenantJwtIssuerValidator tenantJwtIssuerValidator = new TenantJwtIssuerValidator( - tenantConfigProviderWithPitcConfig, jwtHelper) { + new TenantConfigProvider.TenantConfig( // + PITC, + new String[]{}, + "jwkSetUri", // + ISSUER_URL, + "clientId", + null))); + + TenantJwtIssuerValidator tenantJwtIssuerValidator = new TenantJwtIssuerValidator(tenantConfigProviderWithPitcConfig, + jwtHelper) { @Override JwtIssuerValidator createValidator(String issuer) { diff --git a/backend/src/test/java/ch/puzzle/okr/security/helper/ClaimHelperTest.java b/backend/src/test/java/ch/puzzle/okr/security/helper/ClaimHelperTest.java index 0a3850bf1f..596aea6808 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/helper/ClaimHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/helper/ClaimHelperTest.java @@ -1,15 +1,5 @@ package ch.puzzle.okr.security.helper; -import com.nimbusds.jwt.JWTClaimsSet; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import java.text.ParseException; -import java.util.Optional; - import static ch.puzzle.okr.security.JwtHelper.CLAIM_ISS; import static ch.puzzle.okr.security.JwtHelper.CLAIM_TENANT; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -17,6 +7,15 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.nimbusds.jwt.JWTClaimsSet; +import java.text.ParseException; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + public class ClaimHelperTest { private static final String PITC = "pitc"; @@ -85,7 +84,7 @@ void getTenantFromClaimsSetUsingClaimTenantReturnEmptyIfParsingOfClaimFailed() t @DisplayName("getTenantFromClaimsSetUsingClaimIss() return tenant if claim iss is found") @ParameterizedTest - @ValueSource(strings = { "https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc" }) + @ValueSource(strings = {"https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc"}) void getTenantFromClaimsSetUsingClaimIssReturnTenantIfClaimIssFound(String issUrl) throws ParseException { // arrange JWTClaimsSet claimsSetMock = mock(JWTClaimsSet.class); diff --git a/backend/src/test/java/ch/puzzle/okr/security/helper/TokenHelperTest.java b/backend/src/test/java/ch/puzzle/okr/security/helper/TokenHelperTest.java index 0b9c2215ce..6a9fc4a459 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/helper/TokenHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/helper/TokenHelperTest.java @@ -1,14 +1,5 @@ package ch.puzzle.okr.security.helper; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.security.oauth2.jwt.Jwt; - -import java.util.Optional; - import static ch.puzzle.okr.security.JwtHelper.CLAIM_ISS; import static ch.puzzle.okr.security.JwtHelper.CLAIM_TENANT; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -16,6 +7,14 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.security.oauth2.jwt.Jwt; + public class TokenHelperTest { private static final String PITC = "pitc"; @@ -70,7 +69,7 @@ void getTenantFromTokenUsingClaimTenantReturnEmptyIfClaimTenantFoundButValueIsNu @DisplayName("getTenantFromTokenUsingClaimIss() return tenant if claim iss is found") @ParameterizedTest - @ValueSource(strings = { "https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc" }) + @ValueSource(strings = {"https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc"}) void getTenantFromTokenUsingClaimIssReturnTenantIfClaimIssFound(String issUrl) { // arrange Jwt tokenMock = mock(Jwt.class); diff --git a/backend/src/test/java/ch/puzzle/okr/security/helper/UrlHelperTest.java b/backend/src/test/java/ch/puzzle/okr/security/helper/UrlHelperTest.java index 76f71a918e..b4a1b1266b 100644 --- a/backend/src/test/java/ch/puzzle/okr/security/helper/UrlHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/security/helper/UrlHelperTest.java @@ -1,21 +1,20 @@ package ch.puzzle.okr.security.helper; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; - public class UrlHelperTest { private static final String PITC = "pitc"; @DisplayName("extractTenantFromIssUrl() return tenant if Url contains slash") @ParameterizedTest - @ValueSource(strings = { "https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc" }) + @ValueSource(strings = {"https://sso.puzzle.ch/auth/realms/pitc", "http://localhost:8544/realms/pitc"}) void extractTenantFromIssUrlReturnTenantIfUrlContainSlash(String issUrl) { // arrange diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/ActionAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/ActionAuthorizationServiceTest.java index 7e113dea5d..58bcedefe1 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/ActionAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/ActionAuthorizationServiceTest.java @@ -1,10 +1,18 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; +import static org.springframework.http.HttpStatus.UNAUTHORIZED; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.business.ActionBusinessService; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -15,15 +23,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.*; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; - @ExtendWith(MockitoExtension.class) class ActionAuthorizationServiceTest { @InjectMocks @@ -35,14 +34,24 @@ class ActionAuthorizationServiceTest { private final AuthorizationUser authorizationUser = defaultAuthorizationUser(); private final KeyResult keyResult = KeyResultMetric.Builder.builder().withId(10L).withTitle("KR Title").build(); - private final Action action1 = Action.Builder.builder().withId(1L).withAction("Neue Katze").withIsChecked(false) - .withPriority(0).withKeyResult(keyResult).build(); - private final Action action2 = Action.Builder.builder().withId(2L).withAction("Neues Lama").withIsChecked(true) - .withPriority(1).withKeyResult(keyResult).build(); + private final Action action1 = Action.Builder.builder() + .withId(1L) + .withAction("Neue Katze") + .withIsChecked(false) + .withPriority(0) + .withKeyResult(keyResult) + .build(); + private final Action action2 = Action.Builder.builder() + .withId(2L) + .withAction("Neues Lama") + .withIsChecked(true) + .withPriority(1) + .withKeyResult(keyResult) + .build(); private final List actionList = List.of(action1, action2); @ParameterizedTest - @ValueSource(booleans = { true, false }) + @ValueSource(booleans = {true, false}) void getActionsByKeyResultShouldReturnListOfActions(boolean isWriteable) { keyResult.setWriteable(isWriteable); when(actionBusinessService.getActionsByKeyResultId(anyLong())).thenReturn(actionList); @@ -71,11 +80,13 @@ void createEntityShouldReturnCreatedActionWhenAuthorized() { void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(actionList.get(0).getKeyResult(), authorizationUser); + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, + reason)).when(authorizationService) + .hasRoleCreateOrUpdate(actionList.get(0).getKeyResult(), + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> actionAuthorizationService.createEntities(actionList)); + () -> actionAuthorizationService.createEntities(actionList)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -93,11 +104,13 @@ void updateEntitiesShouldUpdateActionWhenAuthorized() { void updateEntitiesShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(actionList.get(0).getKeyResult(), authorizationUser); + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, + reason)).when(authorizationService) + .hasRoleCreateOrUpdate(actionList.get(0).getKeyResult(), + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> actionAuthorizationService.updateEntities(actionList)); + () -> actionAuthorizationService.updateEntities(actionList)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -117,11 +130,12 @@ void deleteEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 8L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleDeleteByActionId(id, authorizationUser); + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, + reason)).when(authorizationService) + .hasRoleDeleteByActionId(id, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> actionAuthorizationService.deleteActionByActionId(id)); + () -> actionAuthorizationService.deleteActionByActionId(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationServiceIT.java index 4f0e3c77e4..87690bfad0 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationRegistrationServiceIT.java @@ -1,22 +1,21 @@ package ch.puzzle.okr.service.authorization; -import ch.puzzle.okr.test.TestHelper; +import static ch.puzzle.okr.SpringCachingConfig.AUTHORIZATION_USER_CACHE; +import static ch.puzzle.okr.test.TestHelper.defaultUser; +import static org.junit.jupiter.api.Assertions.*; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.service.persistence.UserPersistenceService; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; +import java.util.Optional; import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; -import java.util.Optional; - -import static ch.puzzle.okr.SpringCachingConfig.AUTHORIZATION_USER_CACHE; -import static ch.puzzle.okr.test.TestHelper.defaultUser; -import static org.junit.jupiter.api.Assertions.*; - @SpringIntegrationTest class AuthorizationRegistrationServiceIT { @Autowired @@ -87,10 +86,11 @@ void registerAuthorizationUserShouldAddAuthorizationUserToCache() { void registerAuthorizationUser_shouldSetOkrChampionsToFalse() { // arrange User user = User.Builder.builder() // - .withFirstname("Richard") // - .withLastname("Eberhard") // - .withEmail("richard.eberhard@puzzle.ch") // email not found in application-integration-test.properties - .build(); + .withFirstname("Richard") // + .withLastname("Eberhard") // + .withEmail("richard.eberhard@puzzle.ch") // email not found in + // application-integration-test.properties + .build(); userPersistenceService.getOrCreateUser(user); // updates input user with id from DB !!! @@ -109,11 +109,14 @@ void registerAuthorizationUser_shouldSetOkrChampionsToFalse() { } /* - * Special test setup.
 - the user wunderland@puzzle.ch is an existing user in the H2 db (created via
-     * V100_0_0__TestData.sql) - the user wunderland@puzzle.ch is also defined in
-     * application-integration-test.properties as user champion - with this combination we can test, that the user in
-     * the db (which has initial isOkrChampion == false) is after calling updateOrAddAuthorizationUser() a user
-     * champion. - the OkrChampion status must manually be reset (in the tearDown method) 
+ * Special test setup.
 - the user wunderland@puzzle.ch is an existing user
+     * in the H2 db (created via V100_0_0__TestData.sql) - the user
+     * wunderland@puzzle.ch is also defined in
+     * application-integration-test.properties as user champion - with this
+     * combination we can test, that the user in the db (which has initial
+     * isOkrChampion == false) is after calling updateOrAddAuthorizationUser() a
+     * user champion. - the OkrChampion status must manually be reset (in the
+     * tearDown method) 
*/ @Test @DisplayName("registerAuthorizationUser for a user with an email defined in the application-integration-test.properties should set OkrChampions to true") @@ -123,14 +126,15 @@ void registerAuthorizationUserShouldSetOkrChampionsToTrue() { // act // load user from db (by email) and set OkrChampion status based on property - // "okr.tenants.pitc.user.champion.emails" from application-integration-test.properties file - AuthorizationUser processedUser = authorizationRegistrationService - .updateOrAddAuthorizationUser(User.Builder.builder() // - .withFirstname("Alice") // - .withLastname("Wunderland") // - .withEmail(EMAIL_WUNDERLAND) // user.champion.emails from - // application-integration-test.properties - .build()); + // "okr.tenants.pitc.user.champion.emails" from + // application-integration-test.properties file + AuthorizationUser processedUser = authorizationRegistrationService.updateOrAddAuthorizationUser(User.Builder.builder() // + .withFirstname("Alice") // + .withLastname("Wunderland") // + .withEmail(EMAIL_WUNDERLAND) // user.champion.emails + // from + // application-integration-test.properties + .build()); // assert assertTrue(processedUser.user().isOkrChampion()); @@ -141,19 +145,19 @@ void registerAuthorizationUserShouldSetOkrChampionsToTrue() { void registerAuthorizationUser_shouldSetFirstnameAndLastnameFromToken() { // arrange User user = User.Builder.builder() // - .withFirstname("Richard") // - .withLastname("Eberhard") // - .withEmail("richard.eberhard@puzzle.ch") // - .build(); + .withFirstname("Richard") // + .withLastname("Eberhard") // + .withEmail("richard.eberhard@puzzle.ch") // + .build(); userPersistenceService.save(user); String firstNameFromToken = "Richu"; String lastNameFromToken = "von Gunten"; User userFromToken = User.Builder.builder() // - .withFirstname(firstNameFromToken) // - .withLastname(lastNameFromToken) // - .withEmail("richard.eberhard@puzzle.ch") // - .build(); + .withFirstname(firstNameFromToken) // + .withLastname(lastNameFromToken) // + .withEmail("richard.eberhard@puzzle.ch") // + .build(); // act authorizationRegistrationService.updateOrAddAuthorizationUser(userFromToken); diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationServiceTest.java index af6812b245..1c4b821009 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/AuthorizationServiceTest.java @@ -1,5 +1,16 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.ErrorKey.*; +import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; +import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteForTeam; +import static ch.puzzle.okr.test.TestHelper.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; +import static org.springframework.http.HttpStatus.UNAUTHORIZED; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -13,6 +24,8 @@ import ch.puzzle.okr.security.JwtHelper; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.test.TestHelper; +import java.util.Collection; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -24,20 +37,6 @@ import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.oauth2.jwt.Jwt; -import java.util.Collection; -import java.util.List; - -import static ch.puzzle.okr.ErrorKey.*; -import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteAndReadAll; -import static ch.puzzle.okr.service.authorization.AuthorizationService.hasRoleWriteForTeam; -import static ch.puzzle.okr.test.TestHelper.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; - @ExtendWith(MockitoExtension.class) class AuthorizationServiceTest { @InjectMocks @@ -50,11 +49,11 @@ class AuthorizationServiceTest { JwtHelper jwtHelper; private final List adminTeams = List.of(Team.Builder.builder().withName("Team 1").withId(1L).build(), - Team.Builder.builder().withName("Team 2").withId(2L).build()); + Team.Builder.builder().withName("Team 2").withId(2L).build()); private final List memberTeams = List.of(Team.Builder.builder().withName("Team 3").withId(3L).build(), - Team.Builder.builder().withName("Team 4").withId(4L).build()); + Team.Builder.builder().withName("Team 4").withId(4L).build()); private final List otherTeams = List.of(Team.Builder.builder().withName("Team 5").withId(5L).build(), - Team.Builder.builder().withName("Team 6").withId(6L).build()); + Team.Builder.builder().withName("Team 6").withId(6L).build()); private final User user = defaultUserWithTeams(1L, adminTeams, memberTeams); private final User okrChampion = defaultOkrChampion(1L); @@ -112,8 +111,9 @@ void getAuthorizationUserShouldReturnAuthorizationUser() { void hasRoleReadByObjectiveIdShouldPassThroughWhenPermitted() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveById(eq(id), eq(authorizationUser), any())) - .thenReturn(new Objective()); + when(objectivePersistenceService.findObjectiveById(eq(id), + eq(authorizationUser), + any())).thenReturn(new Objective()); authorizationService.hasRoleReadByObjectiveId(id, authorizationUser); } @@ -123,13 +123,15 @@ void hasRoleReadByKeyResultIdShouldThrowExceptionWhenObjectiveNotFound() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "KeyResult"); + "KeyResult"); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), eq(authorizationUser), any())) - .thenThrow(expectedException); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), + eq(authorizationUser), + any())).thenThrow(expectedException); OkrResponseStatusException actualException = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleReadByKeyResultId(id, authorizationUser)); + () -> authorizationService.hasRoleReadByKeyResultId(id, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_READ, "KeyResult")); @@ -143,9 +145,10 @@ void hasRoleReadByKeyResultIdShouldPassThroughWhenPermitted() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "KeyResult"); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), eq(authorizationUser), any())) - .thenReturn(new Objective()); + "KeyResult"); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), + eq(authorizationUser), + any())).thenReturn(new Objective()); authorizationService.hasRoleReadByKeyResultId(id, authorizationUser); } @@ -156,12 +159,14 @@ void hasRoleReadByCheckInIdShouldThrowExceptionWhenObjectiveNotFound() { AuthorizationUser authorizationUser = new AuthorizationUser(user); OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "Check-in"); - when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())) - .thenThrow(expectedException); + "Check-in"); + when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), + eq(authorizationUser), + any())).thenThrow(expectedException); OkrResponseStatusException actualException = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleReadByCheckInId(id, authorizationUser)); + () -> authorizationService.hasRoleReadByCheckInId(id, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_READ, "Check-in")); @@ -175,10 +180,11 @@ void hasRoleReadByCheckInIdShouldPassThroughWhenPermitted() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "Check-in"); + "Check-in"); - when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())) - .thenReturn(new Objective()); + when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), + eq(authorizationUser), + any())).thenReturn(new Objective()); authorizationService.hasRoleReadByCheckInId(id, authorizationUser); } @@ -214,7 +220,8 @@ void hasRoleCreateOrUpdateShouldThrowExceptionWhenNotInTeam() { AuthorizationUser authorizationUser = new AuthorizationUser(user); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleCreateOrUpdate(objective, authorizationUser)); + () -> authorizationService.hasRoleCreateOrUpdate(objective, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_WRITE, "Objective")); @@ -229,8 +236,9 @@ void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedForKeyResults() { KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrChampion); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), + eq(authorizationUser), + any())).thenReturn(objective); authorizationService.hasRoleCreateOrUpdate(keyResult, authorizationUser); } @@ -242,8 +250,9 @@ void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedAsAdminForKeyResults() KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), + eq(authorizationUser), + any())).thenReturn(objective); authorizationService.hasRoleCreateOrUpdate(keyResult, authorizationUser); } @@ -255,11 +264,13 @@ void hasRoleCreateOrUpdateShouldThrowExceptionWhenNotAuthorizedForKeyResults() { KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), + eq(authorizationUser), + any())).thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleCreateOrUpdate(keyResult, authorizationUser)); + () -> authorizationService.hasRoleCreateOrUpdate(keyResult, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_WRITE, "KeyResult")); @@ -277,7 +288,8 @@ void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedAsAdminForTeamCheckIns( AuthorizationUser authorizationUser = new AuthorizationUser(user); when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), - eq(authorizationUser), any())).thenReturn(objective); + eq(authorizationUser), + any())).thenReturn(objective); authorizationService.hasRoleCreateOrUpdate(checkIn, authorizationUser); } @@ -291,7 +303,8 @@ void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedAsMemberForTeamCheckIns AuthorizationUser authorizationUser = new AuthorizationUser(user); when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), - eq(authorizationUser), any())).thenReturn(objective); + eq(authorizationUser), + any())).thenReturn(objective); authorizationService.hasRoleCreateOrUpdate(checkIn, authorizationUser); } @@ -305,10 +318,12 @@ void hasRoleCreateOrUpdateShouldThrowExceptionWhenNotInTeamForTeamCheckIns() { AuthorizationUser authorizationUser = new AuthorizationUser(user); when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), - eq(authorizationUser), any())).thenReturn(objective); + eq(authorizationUser), + any())).thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleCreateOrUpdate(checkIn, authorizationUser)); + () -> authorizationService.hasRoleCreateOrUpdate(checkIn, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_WRITE, "Check-in")); @@ -359,7 +374,8 @@ void hasRoleCreateOrUpdateByObjectiveIdShouldThrowExceptionWhenNotInTeam() { when(objectivePersistenceService.findObjectiveById(eq(id), eq(authorizationUser), any())).thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleCreateOrUpdateByObjectiveId(id, authorizationUser)); + () -> authorizationService.hasRoleCreateOrUpdateByObjectiveId(id, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_WRITE, "Objective")); @@ -410,8 +426,9 @@ void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedToWriteAllKeyResults() { KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrChampion); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), + eq(authorizationUser), + any())).thenReturn(objective); assertTrue(authorizationService.hasRoleWriteForTeam(keyResult, authorizationUser)); } @@ -423,8 +440,9 @@ void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedAsAdminForKeyResults() { KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), + eq(authorizationUser), + any())).thenReturn(objective); assertTrue(authorizationService.hasRoleWriteForTeam(keyResult, authorizationUser)); } @@ -435,8 +453,9 @@ void hasRoleWriteForTeamShouldReturnFalseWhenNotAuthorizedToWriteKeyResults() { KeyResult keyResult = KeyResultMetric.Builder.builder().withObjective(objective).build(); AuthorizationUser authorizationUser = mockAuthorizationUser(user); - when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), eq(authorizationUser), - any())).thenReturn(objective); + when(objectivePersistenceService.findObjectiveById(eq(keyResult.getObjective().getId()), + eq(authorizationUser), + any())).thenReturn(objective); assertFalse(authorizationService.hasRoleWriteForTeam(keyResult, authorizationUser)); } @@ -449,7 +468,8 @@ void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedToWriteAllCheckIns() { AuthorizationUser authorizationUser = new AuthorizationUser(okrChampion); when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), - eq(authorizationUser), any())).thenReturn(objective); + eq(authorizationUser), + any())).thenReturn(objective); assertTrue(authorizationService.hasRoleWriteForTeam(checkIn, authorizationUser)); } @@ -463,7 +483,8 @@ void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedAsAdminForCheckIns() { AuthorizationUser authorizationUser = new AuthorizationUser(user); when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), - eq(authorizationUser), any())).thenReturn(objective); + eq(authorizationUser), + any())).thenReturn(objective); assertTrue(authorizationService.hasRoleWriteForTeam(checkIn, authorizationUser)); } @@ -476,7 +497,8 @@ void hasRoleWriteForTeamShouldReturnFalseWhenNotAuthorizedToWriteCheckIns() { AuthorizationUser authorizationUser = mockAuthorizationUser(user); when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), - eq(authorizationUser), any())).thenReturn(objective); + eq(authorizationUser), + any())).thenReturn(objective); assertFalse(authorizationService.hasRoleWriteForTeam(checkIn, authorizationUser)); } @@ -498,8 +520,9 @@ void hasRoleDeleteByKeyResultIdShouldPassThroughWhenAuthorizedForAllTeamsKeyResu Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(1L).build()).build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrChampion); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), eq(authorizationUser), any())) - .thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), + eq(authorizationUser), + any())).thenReturn(objective); authorizationService.hasRoleDeleteByKeyResultId(id, authorizationUser); } @@ -510,8 +533,9 @@ void hasRoleDeleteByCheckInIdShouldPassThroughWhenAuthorizedAsAdminForTeamCheckI Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(1L).build()).build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())) - .thenReturn(objective); + when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), + eq(authorizationUser), + any())).thenReturn(objective); authorizationService.hasRoleDeleteByCheckInId(id, authorizationUser); } @@ -522,8 +546,9 @@ void hasRoleDeleteByCheckInIdShouldPassThroughWhenAuthorizedAsMemberForTeamCheck Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(1L).build()).build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())) - .thenReturn(objective); + when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), + eq(authorizationUser), + any())).thenReturn(objective); authorizationService.hasRoleDeleteByCheckInId(id, authorizationUser); } @@ -531,11 +556,13 @@ void hasRoleDeleteByCheckInIdShouldPassThroughWhenAuthorizedAsMemberForTeamCheck @Test void hasRoleDeleteByKeyResultIdShouldPassThroughWhenOkrChampion() { var otherTeamId = otherTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(otherTeamId).build()) - .build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder().withId(otherTeamId).build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrChampion); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(1L), eq(authorizationUser), any())) - .thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(1L), + eq(authorizationUser), + any())).thenReturn(objective); authorizationService.hasRoleDeleteByKeyResultId(1L, authorizationUser); } @@ -543,11 +570,13 @@ void hasRoleDeleteByKeyResultIdShouldPassThroughWhenOkrChampion() { @Test void hasRoleDeleteByKeyResultIdShouldPassThroughWhenAdmin() { var otherTeamId = adminTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(otherTeamId).build()) - .build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder().withId(otherTeamId).build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(1L), eq(authorizationUser), any())) - .thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(1L), + eq(authorizationUser), + any())).thenReturn(objective); authorizationService.hasRoleDeleteByKeyResultId(1L, authorizationUser); } @@ -555,11 +584,13 @@ void hasRoleDeleteByKeyResultIdShouldPassThroughWhenAdmin() { @Test void hasRoleDeleteByKeyResultIdShouldPassThroughWhenMember() { var otherTeamId = memberTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(otherTeamId).build()) - .build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder().withId(otherTeamId).build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(1L), eq(authorizationUser), any())) - .thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(1L), + eq(authorizationUser), + any())).thenReturn(objective); authorizationService.hasRoleDeleteByKeyResultId(1L, authorizationUser); } @@ -567,14 +598,17 @@ void hasRoleDeleteByKeyResultIdShouldPassThroughWhenMember() { @Test void hasRoleDeleteByKeyResultIdShouldThrowExceptionWhenNotInTeam() { var otherTeamId = otherTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(otherTeamId).build()) - .build(); + Objective objective = Objective.Builder.builder() + .withTeam(Team.Builder.builder().withId(otherTeamId).build()) + .build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(1L), eq(authorizationUser), any())) - .thenReturn(objective); + when(objectivePersistenceService.findObjectiveByKeyResultId(eq(1L), + eq(authorizationUser), + any())).thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleDeleteByKeyResultId(1L, authorizationUser)); + () -> authorizationService.hasRoleDeleteByKeyResultId(1L, + authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_DELETE, "KeyResult")); diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationServiceTest.java index c2cf02731e..3d3d906ba1 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/CheckInAuthorizationServiceTest.java @@ -1,5 +1,12 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.test.CheckInTestHelpers.checkInMetric; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; +import static org.springframework.http.HttpStatus.UNAUTHORIZED; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.service.business.CheckInBusinessService; @@ -11,13 +18,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import static ch.puzzle.okr.test.CheckInTestHelpers.checkInMetric; -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.when; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; - @ExtendWith(MockitoExtension.class) class CheckInAuthorizationServiceTest { @InjectMocks @@ -56,10 +56,11 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleReadByCheckInId(id, authorizationUser); + .hasRoleReadByCheckInId(id, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> checkInAuthorizationService.getEntityById(id)); + () -> checkInAuthorizationService.getEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -78,10 +79,11 @@ void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(checkInMetric, authorizationUser); + .hasRoleCreateOrUpdate(checkInMetric, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> checkInAuthorizationService.createEntity(checkInMetric)); + () -> checkInAuthorizationService.createEntity(checkInMetric)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -102,10 +104,12 @@ void updateEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(checkInMetric, authorizationUser); + .hasRoleCreateOrUpdate(checkInMetric, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> checkInAuthorizationService.updateEntity(id, checkInMetric)); + () -> checkInAuthorizationService.updateEntity(id, + checkInMetric)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -123,11 +127,12 @@ void deleteEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleDeleteByCheckInId(id, authorizationUser); + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, + reason)).when(authorizationService) + .hasRoleDeleteByCheckInId(id, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> checkInAuthorizationService.deleteEntityById(id)); + () -> checkInAuthorizationService.deleteEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationServiceTest.java index 2358188144..4bb78e2e60 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/CompletedAuthorizationServiceTest.java @@ -1,5 +1,12 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; +import static org.springframework.http.HttpStatus.UNAUTHORIZED; + import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.authorization.AuthorizationUser; @@ -12,13 +19,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.when; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; - @ExtendWith(MockitoExtension.class) class CompletedAuthorizationServiceTest { @InjectMocks @@ -30,8 +30,13 @@ class CompletedAuthorizationServiceTest { private final AuthorizationUser authorizationUser = defaultAuthorizationUser(); private final Long objectiveId = 12L; - private final Completed newCompleted = Completed.Builder.builder().withId(5L) - .withObjective(Objective.Builder.builder().withId(objectiveId).withTitle("Completed 1").build()).build(); + private final Completed newCompleted = Completed.Builder.builder() + .withId(5L) + .withObjective(Objective.Builder.builder() + .withId(objectiveId) + .withTitle("Completed 1") + .build()) + .build(); @Test void createCompletedShouldReturnObjectiveWhenAuthorized() { @@ -46,11 +51,12 @@ void createCompletedShouldReturnObjectiveWhenAuthorized() { void createCompletedShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdateByObjectiveId(objectiveId, authorizationUser); + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, + reason)).when(authorizationService) + .hasRoleCreateOrUpdateByObjectiveId(objectiveId, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> completedAuthorizationService.createCompleted(newCompleted)); + () -> completedAuthorizationService.createCompleted(newCompleted)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -66,11 +72,12 @@ void deleteCompletedByObjectiveIdShouldPassThroughWhenAuthorized() { void deleteCompletedByObjectiveIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleDeleteByObjectiveId(objectiveId, authorizationUser); + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, + reason)).when(authorizationService) + .hasRoleDeleteByObjectiveId(objectiveId, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> completedAuthorizationService.deleteCompletedByObjectiveId(objectiveId)); + () -> completedAuthorizationService.deleteCompletedByObjectiveId(objectiveId)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationServiceTest.java index 2888e08a8a..5133cbed65 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/KeyResultAuthorizationServiceTest.java @@ -1,10 +1,21 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.test.KeyResultTestHelpers.checkIn1; +import static ch.puzzle.okr.test.KeyResultTestHelpers.metricKeyResult; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; +import static org.springframework.http.HttpStatus.BAD_REQUEST; +import static org.springframework.http.HttpStatus.UNAUTHORIZED; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultWithActionList; import ch.puzzle.okr.service.business.KeyResultBusinessService; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -14,18 +25,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static ch.puzzle.okr.test.KeyResultTestHelpers.checkIn1; -import static ch.puzzle.okr.test.KeyResultTestHelpers.metricKeyResult; -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.when; -import static org.springframework.http.HttpStatus.BAD_REQUEST; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; - @ExtendWith(MockitoExtension.class) class KeyResultAuthorizationServiceTest { @InjectMocks @@ -50,10 +49,11 @@ void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(metricKeyResult, authorizationUser); + .hasRoleCreateOrUpdate(metricKeyResult, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.createEntity(metricKeyResult)); + () -> keyResultAuthorizationService.createEntity(metricKeyResult)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -84,11 +84,12 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleReadByKeyResultId(id, authorizationUser); + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, + reason)).when(authorizationService) + .hasRoleReadByKeyResultId(id, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.getEntityById(id)); + () -> keyResultAuthorizationService.getEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -97,11 +98,14 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { void updateEntitiesShouldReturnUpdatedKeyResultWhenAuthorized() { Long id = 13L; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(keyResultBusinessService.updateEntities(id, metricKeyResult, List.of())) - .thenReturn(new KeyResultWithActionList(metricKeyResult, List.of())); - - KeyResultWithActionList KeyResult = keyResultAuthorizationService.updateEntities(id, metricKeyResult, - List.of()); + when(keyResultBusinessService.updateEntities(id, + metricKeyResult, + List.of())).thenReturn(new KeyResultWithActionList(metricKeyResult, + List.of())); + + KeyResultWithActionList KeyResult = keyResultAuthorizationService.updateEntities(id, + metricKeyResult, + List.of()); assertEquals(metricKeyResult, KeyResult.keyResult()); } @@ -111,10 +115,13 @@ void updateEntitiesShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(metricKeyResult, authorizationUser); + .hasRoleCreateOrUpdate(metricKeyResult, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.updateEntities(id, metricKeyResult, List.of())); + () -> keyResultAuthorizationService.updateEntities(id, + metricKeyResult, + List.of())); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -122,10 +129,12 @@ void updateEntitiesShouldThrowExceptionWhenNotAuthorized() { @Test void updateEntityShouldThrowException() { ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.updateEntity(1L, metricKeyResult)); + () -> keyResultAuthorizationService.updateEntity(1L, + metricKeyResult)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertEquals("unsupported method in class " + KeyResultAuthorizationService.class.getSimpleName() - + ", use updateEntities() instead", exception.getReason()); + + ", use updateEntities() instead", + exception.getReason()); } @Test @@ -141,11 +150,12 @@ void deleteEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleDeleteByKeyResultId(id, authorizationUser); + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, + reason)).when(authorizationService) + .hasRoleDeleteByKeyResultId(id, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.deleteEntityById(id)); + () -> keyResultAuthorizationService.deleteEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationServiceTest.java index 04b72412f9..d642c81f48 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/ObjectiveAuthorizationServiceTest.java @@ -1,5 +1,11 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; +import static org.springframework.http.HttpStatus.UNAUTHORIZED; + import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.ObjectiveBusinessService; @@ -12,12 +18,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.when; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; - @ExtendWith(MockitoExtension.class) class ObjectiveAuthorizationServiceTest { @InjectMocks @@ -44,10 +44,11 @@ void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(newObjective, authorizationUser); + .hasRoleCreateOrUpdate(newObjective, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.createEntity(newObjective)); + () -> objectiveAuthorizationService.createEntity(newObjective)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -78,11 +79,12 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleReadByObjectiveId(id, authorizationUser); + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, + reason)).when(authorizationService) + .hasRoleReadByObjectiveId(id, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.getEntityById(id)); + () -> objectiveAuthorizationService.getEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -103,10 +105,12 @@ void updateEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(newObjective, authorizationUser); + .hasRoleCreateOrUpdate(newObjective, + authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.updateEntity(id, newObjective)); + () -> objectiveAuthorizationService.updateEntity(id, + newObjective)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -131,11 +135,12 @@ void deleteEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleDeleteByObjectiveId(id, authorizationUser); + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, + reason)).when(authorizationService) + .hasRoleDeleteByObjectiveId(id, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.deleteEntityById(id)); + () -> objectiveAuthorizationService.deleteEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -150,11 +155,13 @@ void duplicateEntityShouldThrowExceptionWhenNotAuthorized() { when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) - .hasRoleCreateOrUpdate(objective, authorizationUser); + .hasRoleCreateOrUpdate(objective, + authorizationUser); // act ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.duplicateEntity(idExistingObjective, objective)); + () -> objectiveAuthorizationService.duplicateEntity(idExistingObjective, + objective)); // assert assertEquals(UNAUTHORIZED, exception.getStatusCode()); @@ -168,18 +175,22 @@ void duplicateEntityShouldReturnDuplicatedObjectiveWhenAuthorized() { Long idExistingObjective = 13L; Objective newObjectiveWithoutKeyResults = Objective.Builder.builder() // - .withTitle("Objective without KeyResults").build(); + .withTitle("Objective without KeyResults") + .build(); Objective newObjectiveWithKeyResults = Objective.Builder.builder() // - .withId(42L).withTitle("Objective with Id and KeyResults").build(); + .withId(42L) + .withTitle("Objective with Id and KeyResults") + .build(); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(objectiveBusinessService.duplicateObjective(idExistingObjective, newObjectiveWithoutKeyResults, - authorizationUser)).thenReturn(newObjectiveWithKeyResults); + when(objectiveBusinessService.duplicateObjective(idExistingObjective, + newObjectiveWithoutKeyResults, + authorizationUser)).thenReturn(newObjectiveWithKeyResults); // act Objective objective = objectiveAuthorizationService.duplicateEntity(idExistingObjective, - newObjectiveWithoutKeyResults); + newObjectiveWithoutKeyResults); // assert assertEquals(newObjectiveWithKeyResults, objective); diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationServiceTest.java index e2ced700f8..d655c7045d 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/OverviewAuthorizationServiceTest.java @@ -1,9 +1,18 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.test.TestHelper.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.models.overview.OverviewId; import ch.puzzle.okr.service.business.OverviewBusinessService; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -13,16 +22,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class OverviewAuthorizationServiceTest { @Mock @@ -35,12 +34,17 @@ class OverviewAuthorizationServiceTest { private final long adminTeamId = 5L; private final long memberTeamId = 6L; - private final AuthorizationUser authorizationUser = new AuthorizationUser( - defaultUserWithTeams(1L, List.of(defaultTeam(adminTeamId)), List.of(defaultTeam(memberTeamId)))); + private final AuthorizationUser authorizationUser = new AuthorizationUser(defaultUserWithTeams(1L, + List.of(defaultTeam(adminTeamId)), + List.of(defaultTeam(memberTeamId)))); private final AuthorizationUser okrChampionUser = new AuthorizationUser(defaultOkrChampion(2L)); private final Overview overview = Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(adminTeamId).build()) - .withObjectiveTitle("Objective 1").build(); + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(1L) + .withTeamId(adminTeamId) + .build()) + .withObjectiveTitle("Objective 1") + .build(); @DisplayName("getFilteredOverview() should do nothing when OverviewId is null") @Test @@ -50,8 +54,10 @@ void getFilteredOverviewShouldDoNothingWhenOverviewIdIsNull() { when(overviewWithoutOverviewId.getOverviewId()).thenReturn(null); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(overviewBusinessService.getFilteredOverview(any(), any(), any(), eq(authorizationUser))) - .thenReturn(List.of(overviewWithoutOverviewId)); + when(overviewBusinessService.getFilteredOverview(any(), + any(), + any(), + eq(authorizationUser))).thenReturn(List.of(overviewWithoutOverviewId)); // act overviewAuthorizationService.getFilteredOverview(1L, List.of(5L), ""); @@ -70,8 +76,10 @@ void getFilteredOverviewShouldDoNothingWhenTeamIdIsNull() { when(overviewWithoutTeamId.getOverviewId()).thenReturn(overviewId); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(overviewBusinessService.getFilteredOverview(any(), any(), any(), eq(authorizationUser))) - .thenReturn(List.of(overviewWithoutTeamId)); + when(overviewBusinessService.getFilteredOverview(any(), + any(), + any(), + eq(authorizationUser))).thenReturn(List.of(overviewWithoutTeamId)); // act overviewAuthorizationService.getFilteredOverview(1L, List.of(5L), ""); @@ -90,8 +98,10 @@ void getFilteredOverviewShouldDoNothingWhenObjectiveIdIsNull() { when(overviewWithoutObjectiveId.getOverviewId()).thenReturn(overviewId); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(overviewBusinessService.getFilteredOverview(any(), any(), any(), eq(authorizationUser))) - .thenReturn(List.of(overviewWithoutObjectiveId)); + when(overviewBusinessService.getFilteredOverview(any(), + any(), + any(), + eq(authorizationUser))).thenReturn(List.of(overviewWithoutObjectiveId)); // act overviewAuthorizationService.getFilteredOverview(1L, List.of(5L), ""); @@ -144,13 +154,12 @@ void getFilteredOverviewShouldReturnEmptyListWhenNotAuthorized() { } @ParameterizedTest - @ValueSource(booleans = { true, false }) + @ValueSource(booleans = {true, false}) void hasWriteAllAccessShouldReturnHasRoleWriteAll(boolean hasRoleWriteAll) { if (hasRoleWriteAll) { when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(okrChampionUser); } else { - when(authorizationService.updateOrAddAuthorizationUser()) - .thenReturn(mockAuthorizationUser(defaultUser(adminTeamId))); + when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(mockAuthorizationUser(defaultUser(adminTeamId))); } assertEquals(hasRoleWriteAll, overviewAuthorizationService.hasWriteAllAccess()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/TeamAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/TeamAuthorizationServiceTest.java index 6fb9ec4f34..5cf70a2c4b 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/TeamAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/TeamAuthorizationServiceTest.java @@ -1,9 +1,17 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.test.TestHelper.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; +import static org.springframework.http.HttpStatus.UNAUTHORIZED; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.TeamBusinessService; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -13,15 +21,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; - @ExtendWith(MockitoExtension.class) class TeamAuthorizationServiceTest { @@ -34,12 +33,15 @@ class TeamAuthorizationServiceTest { private final AuthorizationUser okrChampionUser = new AuthorizationUser(defaultOkrChampion(1L)); private final Team teamUnderTest = Team.Builder.builder().withId(5L).withName("Team").build(); - private final AuthorizationUser adminUser = new AuthorizationUser( - defaultUserWithTeams(1L, List.of(teamUnderTest), List.of())); - private final AuthorizationUser memberUser = new AuthorizationUser( - defaultUserWithTeams(1L, List.of(), List.of(teamUnderTest))); - private final AuthorizationUser userWithNoTeams = new AuthorizationUser( - defaultUserWithTeams(1L, List.of(), List.of())); + private final AuthorizationUser adminUser = new AuthorizationUser(defaultUserWithTeams(1L, + List.of(teamUnderTest), + List.of())); + private final AuthorizationUser memberUser = new AuthorizationUser(defaultUserWithTeams(1L, + List.of(), + List.of(teamUnderTest))); + private final AuthorizationUser userWithNoTeams = new AuthorizationUser(defaultUserWithTeams(1L, + List.of(), + List.of())); @Test void createEntityShouldReturnTeam() { @@ -75,7 +77,8 @@ void updateEntityShouldThrowExceptionWhenAuthorizedAsMemberUser() { Long id = 13L; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(memberUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> teamAuthorizationService.updateEntity(teamUnderTest, id)); + () -> teamAuthorizationService.updateEntity(teamUnderTest, + id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals("NOT_AUTHORIZED_TO_WRITE", exception.getReason()); } @@ -85,7 +88,8 @@ void updateEntityShouldThrowExceptionWhenAuthorizedAsUserWithNoTeams() { Long id = 13L; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(userWithNoTeams); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> teamAuthorizationService.updateEntity(teamUnderTest, id)); + () -> teamAuthorizationService.updateEntity(teamUnderTest, + id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals("NOT_AUTHORIZED_TO_WRITE", exception.getReason()); } @@ -118,13 +122,13 @@ void deleteEntityByIdShouldThrowExceptionWhenAuthorizedAsUserWithNoTeams() { when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(userWithNoTeams); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> teamAuthorizationService.deleteEntity(id)); + () -> teamAuthorizationService.deleteEntity(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals("NOT_AUTHORIZED_TO_DELETE", exception.getReason()); } @ParameterizedTest - @ValueSource(booleans = { true, false }) + @ValueSource(booleans = {true, false}) void getAllTeamsShouldReturnAllTeams(boolean isWriteable) { List teamList = List.of(teamUnderTest, teamUnderTest); if (isWriteable) { @@ -151,8 +155,9 @@ void addUsersToTeam_shouldCallTeamBusinessService() { var adminTeamId = 1L; var adminTeam = defaultTeam(adminTeamId); var usersList = List.of(1L, 2L); - when(authorizationService.updateOrAddAuthorizationUser()) - .thenReturn(new AuthorizationUser(defaultUserWithTeams(1L, List.of(adminTeam), List.of()))); + when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(new AuthorizationUser(defaultUserWithTeams(1L, + List.of(adminTeam), + List.of()))); teamAuthorizationService.addUsersToTeam(adminTeamId, usersList); verify(teamBusinessService, times(1)).addUsersToTeam(adminTeamId, usersList); diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/UserAuthorizationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/UserAuthorizationServiceTest.java index e1c8a23229..03e38ecd6c 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/UserAuthorizationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/UserAuthorizationServiceTest.java @@ -1,9 +1,14 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.test.TestHelper.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.service.business.UserBusinessService; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -11,12 +16,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) public class UserAuthorizationServiceTest { @Mock @@ -80,7 +79,7 @@ void setOkrChampion_shouldThrowErrorIfLoggedInUserIsNotOkrChampion() { when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(new AuthorizationUser(loggedInUser)); assertThrows(OkrResponseStatusException.class, - () -> userAuthorizationService.setIsOkrChampion(user.getId(), true)); + () -> userAuthorizationService.setIsOkrChampion(user.getId(), true)); } @Test @@ -105,7 +104,7 @@ void createUsers_shouldThrowErrorIfLoggedInUserIsNotOkrChampion() { when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(new AuthorizationUser(loggedInUser)); assertThrows(OkrResponseStatusException.class, - () -> userAuthorizationService.createUsers(List.of(user, user2))); + () -> userAuthorizationService.createUsers(List.of(user, user2))); } @DisplayName("isUserMemberOfTeams() should return false if user is not member of teams") diff --git a/backend/src/test/java/ch/puzzle/okr/service/authorization/UserUpdateHelperTest.java b/backend/src/test/java/ch/puzzle/okr/service/authorization/UserUpdateHelperTest.java index 958eaac311..d3c3e510ca 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/authorization/UserUpdateHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/authorization/UserUpdateHelperTest.java @@ -1,13 +1,13 @@ package ch.puzzle.okr.service.authorization; +import static org.junit.jupiter.api.Assertions.*; + import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantConfigProvider; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - public class UserUpdateHelperTest { private AuthorizationRegistrationService.UserUpdateHelper helper; @@ -21,16 +21,16 @@ void setup() { void updateUserFromWithTokenData() { // arrange User userFromDB = User.Builder.builder() // - .withId(23L) // - .withFirstname("firstname_from_db") // - .withLastname("lastname_from_db") // - .withEmail("a@b.ch") // - .build(); + .withId(23L) // + .withFirstname("firstname_from_db") // + .withLastname("lastname_from_db") // + .withEmail("a@b.ch") // + .build(); User userFromToken = User.Builder.builder() // - .withFirstname("firstname_from_token") // - .withLastname("lastname_from_token") // - .build(); + .withFirstname("firstname_from_token") // + .withLastname("lastname_from_token") // + .build(); // act User updatedUser = helper.setFirstLastNameFromToken(userFromDB, userFromToken); @@ -47,7 +47,12 @@ void updateUserAsNoChampion() { // arrange User noChampionUser = User.Builder.builder().withEmail("no@champions.ch").build(); TenantConfigProvider.TenantConfig tenantConfig = new TenantConfigProvider.TenantConfig(null, // - new String[] { "yes@champions.ch" }, null, null, null, null); + new String[]{ + "yes@champions.ch"}, + null, + null, + null, + null); // act User updatedUser = helper.setOkrChampionFromProperties(noChampionUser, tenantConfig); @@ -61,7 +66,12 @@ void updateUserAsChampion() { // arrange User championUser = User.Builder.builder().withEmail("yes@champions.ch").build(); TenantConfigProvider.TenantConfig tenantConfig = new TenantConfigProvider.TenantConfig(null, // - new String[] { "yes@champions.ch" }, null, null, null, null); + new String[]{ + "yes@champions.ch"}, + null, + null, + null, + null); // act User updatedUser = helper.setOkrChampionFromProperties(championUser, tenantConfig); diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/ActionBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/ActionBusinessServiceTest.java index 41e8151e4c..e684bb1f48 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/ActionBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/ActionBusinessServiceTest.java @@ -1,5 +1,11 @@ package ch.puzzle.okr.service.business; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.Unit; import ch.puzzle.okr.models.authorization.AuthorizationUser; @@ -7,20 +13,13 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.persistence.ActionPersistenceService; import ch.puzzle.okr.service.validation.ActionValidationService; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertIterableEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class ActionBusinessServiceTest { private static final AuthorizationUser authorizationUser = defaultAuthorizationUser(); @@ -32,12 +31,27 @@ class ActionBusinessServiceTest { @InjectMocks private ActionBusinessService actionBusinessService; - private KeyResult metricKeyResult = KeyResultMetric.Builder.builder().withBaseline(10D).withStretchGoal(50D) - .withUnit(Unit.CHF).withId(8L).withTitle("Keyresult Metric").build(); - private Action action1 = Action.Builder.builder().withId(1L).withAction("Neue Katze").withIsChecked(false) - .withPriority(0).withKeyResult(metricKeyResult).build(); - private Action action2 = Action.Builder.builder().withId(2L).withAction("Neues Lama").withIsChecked(true) - .withPriority(1).withKeyResult(metricKeyResult).build(); + private KeyResult metricKeyResult = KeyResultMetric.Builder.builder() + .withBaseline(10D) + .withStretchGoal(50D) + .withUnit(Unit.CHF) + .withId(8L) + .withTitle("Keyresult Metric") + .build(); + private Action action1 = Action.Builder.builder() + .withId(1L) + .withAction("Neue Katze") + .withIsChecked(false) + .withPriority(0) + .withKeyResult(metricKeyResult) + .build(); + private Action action2 = Action.Builder.builder() + .withId(2L) + .withAction("Neues Lama") + .withIsChecked(true) + .withPriority(1) + .withKeyResult(metricKeyResult) + .build(); private List actionList = List.of(action1, action2); @Test @@ -78,8 +92,12 @@ void shouldUpdateMultipleActionsNoKeyResult() { @Test void shouldCreateActionWhenUpdateWithNoId() { - Action action = Action.Builder.builder().withAction("Neue Katze").withPriority(0).withIsChecked(false) - .withKeyResult(metricKeyResult).build(); + Action action = Action.Builder.builder() + .withAction("Neue Katze") + .withPriority(0) + .withIsChecked(false) + .withKeyResult(metricKeyResult) + .build(); actionBusinessService.updateEntities(List.of(action)); verify(actionPersistenceService, times(1)).save(action); @@ -95,10 +113,18 @@ void shouldUpdateMultipleActionsNormal() { @Test void shouldCreateMultipleActions() { - Action newAction1 = Action.Builder.builder().withAction("Neuer Drucker").withKeyResult(metricKeyResult) - .withPriority(0).withIsChecked(false).build(); - Action newAction2 = Action.Builder.builder().withAction("Neues Papier").withKeyResult(metricKeyResult) - .withPriority(1).withIsChecked(false).build(); + Action newAction1 = Action.Builder.builder() + .withAction("Neuer Drucker") + .withKeyResult(metricKeyResult) + .withPriority(0) + .withIsChecked(false) + .build(); + Action newAction2 = Action.Builder.builder() + .withAction("Neues Papier") + .withKeyResult(metricKeyResult) + .withPriority(1) + .withIsChecked(false) + .build(); when(actionPersistenceService.save(newAction1)).thenReturn(action1); when(actionPersistenceService.save(newAction2)).thenReturn(action2); @@ -112,8 +138,12 @@ void shouldCreateMultipleActions() { @Test void shouldCreateOneAction() { - Action newAction1 = Action.Builder.builder().withAction("Neuer Drucker").withKeyResult(metricKeyResult) - .withPriority(0).withIsChecked(false).build(); + Action newAction1 = Action.Builder.builder() + .withAction("Neuer Drucker") + .withKeyResult(metricKeyResult) + .withPriority(0) + .withIsChecked(false) + .build(); when(actionPersistenceService.save(newAction1)).thenReturn(action1); List createdActions = actionBusinessService.createEntities(List.of(newAction1)); diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessServiceTest.java index 29b57b5aed..b84a9e9460 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentSelectionBusinessServiceTest.java @@ -1,20 +1,19 @@ package ch.puzzle.okr.service.business; +import static ch.puzzle.okr.test.TestConstants.TEAM_PUZZLE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.models.alignment.AlignmentSelectionId; import ch.puzzle.okr.service.persistence.AlignmentSelectionPersistenceService; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; - -import static ch.puzzle.okr.test.TestConstants.TEAM_PUZZLE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class AlignmentSelectionBusinessServiceTest { @@ -24,9 +23,15 @@ class AlignmentSelectionBusinessServiceTest { AlignmentSelectionPersistenceService alignmentSelectionPersistenceService; private static AlignmentSelection createAlignmentSelection() { - return AlignmentSelection.Builder.builder().withAlignmentSelectionId(AlignmentSelectionId.of(9L, 15L)) - .withTeamId(5L).withTeamName(TEAM_PUZZLE).withObjectiveTitle("Objective 9").withQuarterId(2L) - .withQuarterLabel("GJ 23/24-Q1").withKeyResultTitle("Key Result 15").build(); + return AlignmentSelection.Builder.builder() + .withAlignmentSelectionId(AlignmentSelectionId.of(9L, 15L)) + .withTeamId(5L) + .withTeamName(TEAM_PUZZLE) + .withObjectiveTitle("Objective 9") + .withQuarterId(2L) + .withQuarterLabel("GJ 23/24-Q1") + .withKeyResultTitle("Key Result 15") + .build(); } @Test diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/CheckInBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/CheckInBusinessServiceTest.java index 9a6d397863..57fe67a677 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/CheckInBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/CheckInBusinessServiceTest.java @@ -1,5 +1,10 @@ package ch.puzzle.okr.service.business; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.models.Unit; import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.authorization.AuthorizationUser; @@ -18,11 +23,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class CheckInBusinessServiceTest { private static final AuthorizationUser authorizationUser = defaultAuthorizationUser(); @@ -36,18 +36,41 @@ class CheckInBusinessServiceTest { @InjectMocks private CheckInBusinessService checkInBusinessService; - private User user = User.Builder.builder().withEmail("Email").withFirstname("Firstname").withLastname("Lastname") - .build(); - private KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder().withCommitZone("Baum") - .withStretchZone("Wald").withId(7L).withTitle("Keyresult Ordinal").build(); - private KeyResult metricKeyResult = KeyResultMetric.Builder.builder().withBaseline(10D).withStretchGoal(50D) - .withUnit(Unit.CHF).withId(8L).withTitle("Keyresult Metric").build(); - private CheckIn checkInMetric = CheckInMetric.Builder.builder().withValue(30D).withId(1L).withConfidence(5) - .withChangeInfo("ChangeInfo1").withInitiatives("Initiatives1").withCreatedBy(user) - .withKeyResult(metricKeyResult).build(); - private CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder().withZone(Zone.COMMIT).withConfidence(5) - .withChangeInfo("ChangeInfo2").withInitiatives("Initiatives2").withCreatedBy(user) - .withKeyResult(ordinalKeyResult).build(); + private User user = User.Builder.builder() + .withEmail("Email") + .withFirstname("Firstname") + .withLastname("Lastname") + .build(); + private KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder() + .withCommitZone("Baum") + .withStretchZone("Wald") + .withId(7L) + .withTitle("Keyresult Ordinal") + .build(); + private KeyResult metricKeyResult = KeyResultMetric.Builder.builder() + .withBaseline(10D) + .withStretchGoal(50D) + .withUnit(Unit.CHF) + .withId(8L) + .withTitle("Keyresult Metric") + .build(); + private CheckIn checkInMetric = CheckInMetric.Builder.builder() + .withValue(30D) + .withId(1L) + .withConfidence(5) + .withChangeInfo("ChangeInfo1") + .withInitiatives("Initiatives1") + .withCreatedBy(user) + .withKeyResult(metricKeyResult) + .build(); + private CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder() + .withZone(Zone.COMMIT) + .withConfidence(5) + .withChangeInfo("ChangeInfo2") + .withInitiatives("Initiatives2") + .withCreatedBy(user) + .withKeyResult(ordinalKeyResult) + .build(); @Test void shouldGetMetricCheckIn() { @@ -132,8 +155,8 @@ void shouldDeleteCheckIn() { @Test void shouldGetCheckInsByKeyResultId() { checkInBusinessService.getCheckInsByKeyResultId(this.metricKeyResult.getId()); - verify(checkInPersistenceService, times(1)) - .getCheckInsByKeyResultIdOrderByCheckInDateDesc(this.metricKeyResult.getId()); + verify(checkInPersistenceService, + times(1)).getCheckInsByKeyResultIdOrderByCheckInDateDesc(this.metricKeyResult.getId()); } @Test diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/CompletedBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/CompletedBusinessServiceTest.java index 0302b92e97..8234aa9f3b 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/CompletedBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/CompletedBusinessServiceTest.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.service.business; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.service.persistence.CompletedPersistenceService; @@ -12,10 +16,6 @@ import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class CompletedBusinessServiceTest { @Mock @@ -23,9 +23,14 @@ class CompletedBusinessServiceTest { @Mock CompletedValidationService validator; - Completed successfulCompleted = Completed.Builder.builder().withId(1L) - .withObjective(Objective.Builder.builder().withId(3L).withTitle("Gute Lernende").build()) - .withComment("Wir haben es gut geschafft").build(); + Completed successfulCompleted = Completed.Builder.builder() + .withId(1L) + .withObjective(Objective.Builder.builder() + .withId(3L) + .withTitle("Gute Lernende") + .build()) + .withComment("Wir haben es gut geschafft") + .build(); @InjectMocks @Spy @@ -36,9 +41,12 @@ void saveSuccessFulCompleted() { Mockito.when(completedPersistenceService.save(any())).thenReturn(successfulCompleted); Completed completed = Completed.Builder.builder() - .withObjective(Objective.Builder.builder().withId(4L) - .withTitle("Build a company culture that kills the competition.").build()) - .withComment("Das ist gut").build(); + .withObjective(Objective.Builder.builder() + .withId(4L) + .withTitle("Build a company culture that kills the competition.") + .build()) + .withComment("Das ist gut") + .build(); Completed savedCompleted = completedBusinessService.createCompleted(completed); verify(completedPersistenceService, times(1)).save(completed); @@ -47,8 +55,12 @@ void saveSuccessFulCompleted() { @Test void shouldBePossibleToSaveCompletedWithoutComment() { - Completed completed = Completed.Builder.builder().withObjective(Objective.Builder.builder().withId(4L) - .withTitle("Build a company culture that kills the competition.").build()).build(); + Completed completed = Completed.Builder.builder() + .withObjective(Objective.Builder.builder() + .withId(4L) + .withTitle("Build a company culture that kills the competition.") + .build()) + .build(); Mockito.when(completedPersistenceService.save(any())).thenReturn(successfulCompleted); diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceIT.java index 13e46094a9..9961235289 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceIT.java @@ -1,6 +1,12 @@ package ch.puzzle.okr.service.business; -import ch.puzzle.okr.test.TestHelper; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.Unit; @@ -17,6 +23,9 @@ import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.service.authorization.AuthorizationService; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; +import java.time.LocalDateTime; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -24,16 +33,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.List; - -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - @SpringIntegrationTest class KeyResultBusinessServiceIT { private static final String KEY_RESULT_UPDATED = "Updated Key Result"; @@ -56,20 +55,31 @@ class KeyResultBusinessServiceIT { private AuthorizationService authorizationService; private static KeyResult createKeyResultMetric(Long id) { - return KeyResultMetric.Builder.builder().withBaseline(3.0).withStretchGoal(5.0).withUnit(Unit.FTE).withId(id) - .withTitle("Title").withCreatedBy(User.Builder.builder().withId(1L).build()) - .withOwner(User.Builder.builder().withId(1L).build()) - .withObjective(Objective.Builder.builder().withId(4L).build()).withCreatedOn(LocalDateTime.now()) - .build(); + return KeyResultMetric.Builder.builder() + .withBaseline(3.0) + .withStretchGoal(5.0) + .withUnit(Unit.FTE) + .withId(id) + .withTitle("Title") + .withCreatedBy(User.Builder.builder().withId(1L).build()) + .withOwner(User.Builder.builder().withId(1L).build()) + .withObjective(Objective.Builder.builder().withId(4L).build()) + .withCreatedOn(LocalDateTime.now()) + .build(); } private static KeyResult createKeyResultOrdinal(Long id) { - return KeyResultOrdinal.Builder.builder().withCommitZone("Hamster").withTargetZone("Katze").withId(id) - .withTitle("Ordinal KeyResult").withStretchZone("ZOO") - .withCreatedBy(User.Builder.builder().withId(1L).build()) - .withOwner(User.Builder.builder().withId(1L).build()) - .withObjective(Objective.Builder.builder().withId(4L).build()).withCreatedOn(LocalDateTime.now()) - .build(); + return KeyResultOrdinal.Builder.builder() + .withCommitZone("Hamster") + .withTargetZone("Katze") + .withId(id) + .withTitle("Ordinal KeyResult") + .withStretchZone("ZOO") + .withCreatedBy(User.Builder.builder().withId(1L).build()) + .withOwner(User.Builder.builder().withId(1L).build()) + .withObjective(Objective.Builder.builder().withId(4L).build()) + .withCreatedOn(LocalDateTime.now()) + .build(); } private static CheckIn createCheckInMetric(KeyResult keyResult) { @@ -77,18 +87,29 @@ private static CheckIn createCheckInMetric(KeyResult keyResult) { } private static CheckIn createCheckInOrdinal(KeyResult keyResult) { - return CheckInOrdinal.Builder.builder().withKeyResult(keyResult).withConfidence(5).withZone(Zone.COMMIT) - .build(); + return CheckInOrdinal.Builder.builder() + .withKeyResult(keyResult) + .withConfidence(5) + .withZone(Zone.COMMIT) + .build(); } private static Action createAction1(KeyResult keyResult) { - return Action.Builder.builder().withIsChecked(false).withAction("Neuer Drucker").withPriority(0) - .withKeyResult(keyResult).build(); + return Action.Builder.builder() + .withIsChecked(false) + .withAction("Neuer Drucker") + .withPriority(0) + .withKeyResult(keyResult) + .build(); } private static Action createAction2(KeyResult keyResult) { - return Action.Builder.builder().withIsChecked(false).withAction("Neues Papier").withPriority(0) - .withKeyResult(keyResult).build(); + return Action.Builder.builder() + .withIsChecked(false) + .withAction("Neues Papier") + .withPriority(0) + .withKeyResult(keyResult) + .build(); } @BeforeEach @@ -135,7 +156,8 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeMetric() { createdKeyResult.setTitle(KEY_RESULT_UPDATED); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(createdKeyResult.getId(), - createdKeyResult, List.of()); + createdKeyResult, + List.of()); assertSameKeyResult(createdKeyResult, updatedKeyResult.keyResult()); } @@ -148,7 +170,8 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeMetricWithActionList() { action2 = actionBusinessService.createEntity(createAction2(createdKeyResult)); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(createdKeyResult.getId(), - createdKeyResult, List.of(action1, action2)); + createdKeyResult, + List.of(action1, action2)); assertSameKeyResult(createdKeyResult, updatedKeyResult.keyResult()); assertSameActions(List.of(action1, action2), updatedKeyResult); @@ -160,7 +183,8 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeOrdinal() { createdKeyResult.setTitle(KEY_RESULT_UPDATED); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(createdKeyResult.getId(), - createdKeyResult, List.of()); + createdKeyResult, + List.of()); assertSameKeyResult(createdKeyResult, updatedKeyResult.keyResult()); } @@ -168,12 +192,13 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeOrdinal() { @Test void updateEntitiesShouldRecreateKeyResultMetric() { KeyResult savedKeyResult = keyResultBusinessService.createEntity(createKeyResultOrdinal(null), - authorizationUser); + authorizationUser); Long createdKeyResultId = savedKeyResult.getId(); KeyResult changedKeyResult = createKeyResultMetric(savedKeyResult.getId()); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + changedKeyResult, + List.of()); createdKeyResult = updatedKeyResult.keyResult(); assertRecreatedKeyResult(updatedKeyResult.keyResult(), createdKeyResultId); @@ -182,14 +207,15 @@ void updateEntitiesShouldRecreateKeyResultMetric() { @Test void updateEntitiesShouldRecreateKeyResultMetricWithActionList() { KeyResult savedKeyResult = keyResultBusinessService.createEntity(createKeyResultOrdinal(null), - authorizationUser); + authorizationUser); action1 = actionBusinessService.createEntity(createAction1(savedKeyResult)); action2 = actionBusinessService.createEntity(createAction2(savedKeyResult)); KeyResult changedKeyResult = createKeyResultMetric(savedKeyResult.getId()); Long createdKeyResultId = changedKeyResult.getId(); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of(action1, action2)); + changedKeyResult, + List.of(action1, action2)); createdKeyResult = updatedKeyResult.keyResult(); assertRecreatedKeyResult(updatedKeyResult.keyResult(), createdKeyResultId); @@ -199,12 +225,13 @@ void updateEntitiesShouldRecreateKeyResultMetricWithActionList() { @Test void updateEntitiesShouldRecreateKeyResultOrdinal() { KeyResult savedKeyResult = keyResultBusinessService.createEntity(createKeyResultMetric(null), - authorizationUser); + authorizationUser); Long createdKeyResultId = savedKeyResult.getId(); KeyResult changedKeyResult = createKeyResultOrdinal(savedKeyResult.getId()); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + changedKeyResult, + List.of()); createdKeyResult = updatedKeyResult.keyResult(); assertRecreatedKeyResult(updatedKeyResult.keyResult(), createdKeyResultId); @@ -218,7 +245,8 @@ void updateEntitiesShouldUpdateKeyResultWithDifferentTypeAndCheckInMetric() { KeyResult changedKeyResult = createKeyResultMetric(createdKeyResult.getId()); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + changedKeyResult, + List.of()); assertUpdatedKeyResult(changedKeyResult, updatedKeyResult.keyResult()); } @@ -235,7 +263,8 @@ void updateEntitiesShouldUpdateKeyResultWithDifferentTypeAndCheckInMetricWithAct action2.setChecked(true); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of(action1, action2)); + changedKeyResult, + List.of(action1, action2)); assertUpdatedKeyResult(changedKeyResult, updatedKeyResult.keyResult()); assertUpdatedActions(List.of(action1, action2), updatedKeyResult); @@ -249,7 +278,8 @@ void updateEntitiesShouldUpdateKeyResultWithDifferentTypeAndCheckInOrdinal() { KeyResult changedKeyResult = createKeyResultOrdinal(createdKeyResult.getId()); KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + changedKeyResult, + List.of()); assertUpdatedKeyResult(changedKeyResult, updatedKeyResult.keyResult()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceTest.java index d23d3b61d8..34e60ab3a8 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/KeyResultBusinessServiceTest.java @@ -1,5 +1,10 @@ package ch.puzzle.okr.service.business; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.User; @@ -12,6 +17,8 @@ import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; import ch.puzzle.okr.service.validation.KeyResultValidationService; +import java.util.Collections; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,14 +29,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.Collections; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class KeyResultBusinessServiceTest { private static final AuthorizationUser authorizationUser = defaultAuthorizationUser(); @@ -61,21 +60,49 @@ void setup() { objective = Objective.Builder.builder().withId(5L).withTitle("Objective 1").build(); - metricKeyResult = KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(7.0).withId(5L) - .withTitle("Keyresult Metric").withObjective(objective).withOwner(user).withCreatedBy(user).build(); - ordinalKeyResult = KeyResultOrdinal.Builder.builder().withCommitZone("Baum").withStretchZone("Wald").withId(7L) - .withTitle("Keyresult Ordinal").withObjective(objective).withOwner(user).withCreatedBy(user).build(); - - checkIn1 = CheckInMetric.Builder.builder().withId(1L).withKeyResult(metricKeyResult).withCreatedBy(user) - .build(); - checkIn2 = CheckInOrdinal.Builder.builder().withId(2L).withKeyResult(ordinalKeyResult).withCreatedBy(user) - .build(); - checkIn3 = CheckInOrdinal.Builder.builder().withId(3L).withKeyResult(ordinalKeyResult).withCreatedBy(user) - .build(); + metricKeyResult = KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(7.0) + .withId(5L) + .withTitle("Keyresult Metric") + .withObjective(objective) + .withOwner(user) + .withCreatedBy(user) + .build(); + ordinalKeyResult = KeyResultOrdinal.Builder.builder() + .withCommitZone("Baum") + .withStretchZone("Wald") + .withId(7L) + .withTitle("Keyresult Ordinal") + .withObjective(objective) + .withOwner(user) + .withCreatedBy(user) + .build(); + + checkIn1 = CheckInMetric.Builder.builder() + .withId(1L) + .withKeyResult(metricKeyResult) + .withCreatedBy(user) + .build(); + checkIn2 = CheckInOrdinal.Builder.builder() + .withId(2L) + .withKeyResult(ordinalKeyResult) + .withCreatedBy(user) + .build(); + checkIn3 = CheckInOrdinal.Builder.builder() + .withId(3L) + .withKeyResult(ordinalKeyResult) + .withCreatedBy(user) + .build(); keyResults = List.of(metricKeyResult, ordinalKeyResult); checkIns = List.of(checkIn1, checkIn2, checkIn3); - Action action = Action.Builder.builder().withId(3L).withAction("Neues Haus").withPriority(1).withIsChecked(true) - .withKeyResult(metricKeyResult).build(); + Action action = Action.Builder.builder() + .withId(3L) + .withAction("Neues Haus") + .withPriority(1) + .withIsChecked(true) + .withKeyResult(metricKeyResult) + .build(); actions = List.of(action, action); } @@ -99,8 +126,10 @@ void shouldGetOrdinalKeyResultById() { @Test void shouldThrowExceptionWhenDefaultMethodUsed() { - IllegalCallerException exception = assertThrows(IllegalCallerException.class, () -> keyResultBusinessService - .updateEntity(metricKeyResult.getId(), metricKeyResult, authorizationUser)); + IllegalCallerException exception = assertThrows(IllegalCallerException.class, + () -> keyResultBusinessService.updateEntity(metricKeyResult.getId(), + metricKeyResult, + authorizationUser)); assertEquals("unsupported method 'updateEntity' use updateEntities() instead", exception.getMessage()); } @@ -108,8 +137,10 @@ void shouldThrowExceptionWhenDefaultMethodUsed() { @Test void shouldEditMetricKeyResultWhenNoTypeChange() { List emptyList = Collections.emptyList(); - KeyResult newKeyresult = spy( - KeyResultMetric.Builder.builder().withId(1L).withTitle("Keyresult Metric update").build()); + KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder() + .withId(1L) + .withTitle("Keyresult Metric update") + .build()); Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(metricKeyResult); Mockito.when(keyResultPersistenceService.updateEntity(any())).thenReturn(newKeyresult); doNothing().when(newKeyresult).setModifiedOn(any()); @@ -125,8 +156,10 @@ void shouldEditMetricKeyResultWhenNoTypeChange() { @Test void shouldEditOrdinalKeyResultWhenNoTypeChange() { List emptyList = Collections.emptyList(); - KeyResult newKeyresult = spy( - KeyResultOrdinal.Builder.builder().withId(1L).withTitle("Keyresult Ordinal update").build()); + KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder() + .withId(1L) + .withTitle("Keyresult Ordinal update") + .build()); Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(ordinalKeyResult); Mockito.when(keyResultPersistenceService.updateEntity(any())).thenReturn(newKeyresult); doNothing().when(newKeyresult).setModifiedOn(any()); @@ -142,8 +175,10 @@ void shouldEditOrdinalKeyResultWhenNoTypeChange() { @Test void shouldEditMetricKeyResultWhenATypeChange() { List emptyList = Collections.emptyList(); - KeyResult newKeyresult = spy( - KeyResultMetric.Builder.builder().withId(1L).withTitle("Keyresult Metric update").build()); + KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder() + .withId(1L) + .withTitle("Keyresult Metric update") + .build()); Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(ordinalKeyResult); Mockito.when(keyResultPersistenceService.recreateEntity(any(), any())).thenReturn(newKeyresult); Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())).thenReturn(emptyList); @@ -161,8 +196,10 @@ void shouldEditMetricKeyResultWhenATypeChange() { @Test void shouldEditOrdinalKeyResultWhenATypeChange() { List emptyList = Collections.emptyList(); - KeyResult newKeyresult = spy( - KeyResultOrdinal.Builder.builder().withId(1L).withTitle("Keyresult Ordinal update").build()); + KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder() + .withId(1L) + .withTitle("Keyresult Ordinal update") + .build()); Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(metricKeyResult); Mockito.when(keyResultPersistenceService.recreateEntity(any(), any())).thenReturn(newKeyresult); Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())).thenReturn(emptyList); @@ -179,8 +216,10 @@ void shouldEditOrdinalKeyResultWhenATypeChange() { @Test void shouldOnlyEditCoupleOfAttributesFromMetricKeyResultWhenATypeChangeAndCheckIns() { List emptyList = checkIns; - KeyResult newKeyresult = spy( - KeyResultMetric.Builder.builder().withId(1L).withTitle("Keyresult Metric update").build()); + KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder() + .withId(1L) + .withTitle("Keyresult Metric update") + .build()); Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(ordinalKeyResult); Mockito.when(keyResultPersistenceService.updateEntity(any())).thenReturn(newKeyresult); Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())).thenReturn(emptyList); @@ -197,8 +236,10 @@ void shouldOnlyEditCoupleOfAttributesFromMetricKeyResultWhenATypeChangeAndCheckI @Test void shouldOnlyEditCoupleOfAttributesFromOrdinalKeyResultWhenATypeChangeAndCheckIns() { List emptyList = checkIns; - KeyResult newKeyresult = spy( - KeyResultOrdinal.Builder.builder().withId(1L).withTitle("Keyresult Ordinal update").build()); + KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder() + .withId(1L) + .withTitle("Keyresult Ordinal update") + .build()); Mockito.when(keyResultPersistenceService.findById(1L)).thenReturn(metricKeyResult); Mockito.when(keyResultPersistenceService.updateEntity(any())).thenReturn(newKeyresult); Mockito.when(checkInBusinessService.getCheckInsByKeyResultId(any())).thenReturn(emptyList); @@ -214,8 +255,13 @@ void shouldOnlyEditCoupleOfAttributesFromOrdinalKeyResultWhenATypeChangeAndCheck @Test void saveMetricKeyResult() { - KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(8.0).withId(1L) - .withTitle("Keyresult Metric save").withDescription("The description").build()); + KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(8.0) + .withId(1L) + .withTitle("Keyresult Metric save") + .withDescription("The description") + .build()); Mockito.when(keyResultPersistenceService.save(any())).thenReturn(newKeyresult); doNothing().when(newKeyresult).setCreatedOn(any()); @@ -226,9 +272,13 @@ void saveMetricKeyResult() { @Test void saveOrdinalKeyResult() { - KeyResult newKeyresult = spy( - KeyResultOrdinal.Builder.builder().withCommitZone("Eine Pflanze").withTargetZone("Ein Baum").withId(1L) - .withTitle("Keyresult ordinal save").withDescription("The description").build()); + KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder() + .withCommitZone("Eine Pflanze") + .withTargetZone("Ein Baum") + .withId(1L) + .withTitle("Keyresult ordinal save") + .withDescription("The description") + .build()); Mockito.when(keyResultPersistenceService.save(any())).thenReturn(newKeyresult); doNothing().when(newKeyresult).setCreatedOn(any()); @@ -239,8 +289,12 @@ void saveOrdinalKeyResult() { @Test void shouldBePossibleToSaveMetricKeyResultWithoutDescription() { - KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(8.0).withId(1L) - .withTitle("Keyresult Metric save").build()); + KeyResult newKeyresult = spy(KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(8.0) + .withId(1L) + .withTitle("Keyresult Metric save") + .build()); Mockito.when(keyResultPersistenceService.save(any())).thenReturn(newKeyresult); doNothing().when(newKeyresult).setCreatedOn(any()); @@ -251,8 +305,12 @@ void shouldBePossibleToSaveMetricKeyResultWithoutDescription() { @Test void shouldBePossibleToSaveOrdinalKeyResultWithoutDescription() { - KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder().withCommitZone("Eine Pflanze") - .withTargetZone("Ein Baum").withId(1L).withTitle("Keyresult ordinal save").build()); + KeyResult newKeyresult = spy(KeyResultOrdinal.Builder.builder() + .withCommitZone("Eine Pflanze") + .withTargetZone("Ein Baum") + .withId(1L) + .withTitle("Keyresult ordinal save") + .build()); Mockito.when(keyResultPersistenceService.save(any())).thenReturn(newKeyresult); doNothing().when(newKeyresult).setCreatedOn(any()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/ObjectiveBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/ObjectiveBusinessServiceTest.java index ce4db63f9c..34db287532 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/ObjectiveBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/ObjectiveBusinessServiceTest.java @@ -1,5 +1,13 @@ package ch.puzzle.okr.service.business; +import static ch.puzzle.okr.models.State.DRAFT; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; +import static org.springframework.http.HttpStatus.NOT_FOUND; + import ch.puzzle.okr.models.*; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.keyresult.KeyResult; @@ -7,6 +15,8 @@ import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.service.validation.ObjectiveValidationService; +import java.time.LocalDateTime; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -18,17 +28,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static ch.puzzle.okr.models.State.DRAFT; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; -import static org.springframework.http.HttpStatus.NOT_FOUND; - @ExtendWith(MockitoExtension.class) class ObjectiveBusinessServiceTest { private static final AuthorizationUser authorizationUser = defaultAuthorizationUser(); @@ -46,14 +45,28 @@ class ObjectiveBusinessServiceTest { private final Team team1 = Team.Builder.builder().withId(1L).withName("Team1").build(); private final Quarter quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build(); - private final User user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); + private final User user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); private final Objective objective = Objective.Builder.builder().withId(5L).withTitle("Objective 1").build(); - private final Objective fullObjective = Objective.Builder.builder().withTitle("FullObjective1").withCreatedBy(user) - .withTeam(team1).withQuarter(quarter).withDescription("This is our description") - .withModifiedOn(LocalDateTime.MAX).build(); - private final KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder().withCommitZone("Baum") - .withStretchZone("Wald").withId(5L).withTitle("Keyresult Ordinal").withObjective(objective).build(); + private final Objective fullObjective = Objective.Builder.builder() + .withTitle("FullObjective1") + .withCreatedBy(user) + .withTeam(team1) + .withQuarter(quarter) + .withDescription("This is our description") + .withModifiedOn(LocalDateTime.MAX) + .build(); + private final KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder() + .withCommitZone("Baum") + .withStretchZone("Wald") + .withId(5L) + .withTitle("Keyresult Ordinal") + .withObjective(objective) + .build(); private final List keyResultList = List.of(ordinalKeyResult, ordinalKeyResult, ordinalKeyResult); @Test @@ -87,9 +100,15 @@ void shouldNotFindTheObjective() { @Test void shouldSaveANewObjective() { - Objective objective = spy(Objective.Builder.builder().withTitle("Received Objective").withTeam(team1) - .withQuarter(quarter).withDescription("The description").withModifiedOn(null).withModifiedBy(null) - .withState(DRAFT).build()); + Objective objective = spy(Objective.Builder.builder() + .withTitle("Received Objective") + .withTeam(team1) + .withQuarter(quarter) + .withDescription("The description") + .withModifiedOn(null) + .withModifiedBy(null) + .withState(DRAFT) + .build()); doNothing().when(objective).setCreatedOn(any()); @@ -103,8 +122,12 @@ void shouldSaveANewObjective() { @Test void shouldNotThrowResponseStatusExceptionWhenPuttingNullId() { - Objective objective1 = Objective.Builder.builder().withId(null).withTitle("Title") - .withDescription("Description").withModifiedOn(LocalDateTime.now()).build(); + Objective objective1 = Objective.Builder.builder() + .withId(null) + .withTitle("Title") + .withDescription("Description") + .withModifiedOn(LocalDateTime.now()) + .build(); when(objectiveBusinessService.createEntity(objective1, authorizationUser)).thenReturn(fullObjective); Objective savedObjective = objectiveBusinessService.createEntity(objective1, authorizationUser); @@ -114,20 +137,39 @@ void shouldNotThrowResponseStatusExceptionWhenPuttingNullId() { } @ParameterizedTest - @ValueSource(booleans = { false, true }) + @ValueSource(booleans = {false, true}) void updateEntityShouldHandleQuarterCorrectly(boolean hasKeyResultAnyCheckIns) { Long id = 27L; String title = "Received Objective"; String description = "The description"; Quarter changedQuarter = Quarter.Builder.builder().withId(2L).withLabel("another quarter").build(); - Objective savedObjective = Objective.Builder.builder().withId(id).withTitle(title).withTeam(team1) - .withQuarter(quarter).withDescription(null).withModifiedOn(null).withModifiedBy(null).build(); - Objective changedObjective = Objective.Builder.builder().withId(id).withTitle(title).withTeam(team1) - .withQuarter(changedQuarter).withDescription(description).withModifiedOn(null).withModifiedBy(null) - .build(); - Objective updatedObjective = Objective.Builder.builder().withId(id).withTitle(title).withTeam(team1) - .withQuarter(hasKeyResultAnyCheckIns ? quarter : changedQuarter).withDescription(description) - .withModifiedOn(null).withModifiedBy(null).build(); + Objective savedObjective = Objective.Builder.builder() + .withId(id) + .withTitle(title) + .withTeam(team1) + .withQuarter(quarter) + .withDescription(null) + .withModifiedOn(null) + .withModifiedBy(null) + .build(); + Objective changedObjective = Objective.Builder.builder() + .withId(id) + .withTitle(title) + .withTeam(team1) + .withQuarter(changedQuarter) + .withDescription(description) + .withModifiedOn(null) + .withModifiedBy(null) + .build(); + Objective updatedObjective = Objective.Builder.builder() + .withId(id) + .withTitle(title) + .withTeam(team1) + .withQuarter(hasKeyResultAnyCheckIns ? quarter : changedQuarter) + .withDescription(description) + .withModifiedOn(null) + .withModifiedBy(null) + .build(); when(objectivePersistenceService.findById(any())).thenReturn(savedObjective); when(keyResultBusinessService.getAllKeyResultsByObjective(savedObjective.getId())).thenReturn(keyResultList); @@ -135,12 +177,13 @@ void updateEntityShouldHandleQuarterCorrectly(boolean hasKeyResultAnyCheckIns) { when(objectivePersistenceService.save(changedObjective)).thenReturn(updatedObjective); boolean isImUsed = objectiveBusinessService.isImUsed(changedObjective); - Objective updatedEntity = objectiveBusinessService.updateEntity(changedObjective.getId(), changedObjective, - authorizationUser); + Objective updatedEntity = objectiveBusinessService.updateEntity(changedObjective.getId(), + changedObjective, + authorizationUser); assertEquals(hasKeyResultAnyCheckIns, isImUsed); assertEquals(hasKeyResultAnyCheckIns ? savedObjective.getQuarter() : changedObjective.getQuarter(), - updatedEntity.getQuarter()); + updatedEntity.getQuarter()); assertEquals(changedObjective.getDescription(), updatedEntity.getDescription()); assertEquals(changedObjective.getTitle(), updatedEntity.getTitle()); } @@ -159,32 +202,33 @@ void shouldDeleteObjectiveAndAssociatedKeyResults() { void shouldDuplicateObjective() { // arrange Objective sourceObjective = Objective.Builder.builder() // - .withId(23L) // - .withTitle("Objective 1") // - .build(); + .withId(23L) // + .withTitle("Objective 1") // + .build(); KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() // - .withTitle("Ordinal 1") // - .withObjective(sourceObjective) // - .build(); + .withTitle("Ordinal 1") // + .withObjective(sourceObjective) // + .build(); KeyResult keyResultMetric = KeyResultMetric.Builder.builder() // - .withTitle("Metric 1") // - .withObjective(sourceObjective) // - .withUnit(Unit.FTE) // - .build(); + .withTitle("Metric 1") // + .withObjective(sourceObjective) // + .withUnit(Unit.FTE) // + .build(); // new Objective with no KeyResults Objective newObjective = Objective.Builder.builder() // - .withId(42L) // - .withTitle("Objective 2") // - .build(); + .withId(42L) // + .withTitle("Objective 2") // + .build(); when(objectivePersistenceService.save(any())).thenReturn(newObjective); - when(keyResultBusinessService.getAllKeyResultsByObjective(anyLong())) - .thenReturn(List.of(keyResultOrdinal, keyResultMetric)); + when(keyResultBusinessService.getAllKeyResultsByObjective(anyLong())).thenReturn(List.of(keyResultOrdinal, + keyResultMetric)); // act Objective duplicatedObjective = objectiveBusinessService.duplicateObjective(sourceObjective.getId(), - newObjective, authorizationUser); + newObjective, + authorizationUser); // assert assertNotEquals(sourceObjective.getId(), duplicatedObjective.getId()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/OverviewBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/OverviewBusinessServiceTest.java index 546a65df47..0a5b4f05a4 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/OverviewBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/OverviewBusinessServiceTest.java @@ -1,11 +1,22 @@ package ch.puzzle.okr.service.business; +import static ch.puzzle.okr.test.OverviewTestHelper.QUARTER_ID; +import static ch.puzzle.okr.test.OverviewTestHelper.teamIds; +import static ch.puzzle.okr.test.TestHelper.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.models.overview.OverviewId; import ch.puzzle.okr.service.persistence.OverviewPersistenceService; import ch.puzzle.okr.service.validation.OverviewValidationService; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -14,18 +25,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; - -import static ch.puzzle.okr.test.OverviewTestHelper.QUARTER_ID; -import static ch.puzzle.okr.test.OverviewTestHelper.teamIds; -import static ch.puzzle.okr.test.TestHelper.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class OverviewBusinessServiceTest { @@ -49,34 +48,61 @@ private static List createOverviews() { private static List createOverviews(AuthorizationUser authorizationUser) { long index = 1L; - List overviews = new ArrayList<>(List.of( - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(index++).withTeamId(111L).build()) - .withObjectiveTitle("Another Team Objective A").withTeamName("team-111") - .withObjectiveCreatedOn(LocalDateTime.of(2023, 10, 21, 18, 33)).build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(index++).withTeamId(222L).build()) - .withObjectiveTitle("Another Team Objective B").withTeamName("team-222") - .withObjectiveCreatedOn(LocalDateTime.of(2023, 10, 1, 8, 53)).build())); + List overviews = new ArrayList<>(List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(index++) + .withTeamId(111L) + .build()) + .withObjectiveTitle("Another Team Objective A") + .withTeamName("team-111") + .withObjectiveCreatedOn(LocalDateTime.of(2023, + 10, + 21, + 18, + 33)) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(index++) + .withTeamId(222L) + .build()) + .withObjectiveTitle("Another Team Objective B") + .withTeamName("team-222") + .withObjectiveCreatedOn(LocalDateTime.of(2023, + 10, + 1, + 8, + 53)) + .build())); for (Long teamId : authorizationUser.extractTeamIds()) { - overviews - .addAll((List.of( - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(index++) - .withTeamId(teamId).build()) - .withObjectiveTitle("ZZZ Objective").withTeamName("firstLevelTeam-" + teamId) - .withObjectiveCreatedOn(LocalDateTime.of(2023, 12, 10, 18, 33)).build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(index++) - .withTeamId(teamId).build()) - .withObjectiveTitle("AAA Objective").withTeamName("firstLevelTeam-" + teamId) - .withObjectiveCreatedOn(LocalDateTime.of(2023, 9, 10, 18, 33)).build(), - Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withObjectiveId(index++) - .withTeamId(teamId).build()) - .withObjectiveTitle("AAA Objective").withTeamName("firstLevelTeam-" + teamId) - .withObjectiveCreatedOn(LocalDateTime.of(2023, 9, 10, 18, 33)).build()))); + overviews.addAll((List.of(Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(index++) + .withTeamId(teamId) + .build()) + .withObjectiveTitle("ZZZ Objective") + .withTeamName("firstLevelTeam-" + teamId) + .withObjectiveCreatedOn(LocalDateTime.of(2023, 12, 10, 18, 33)) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(index++) + .withTeamId(teamId) + .build()) + .withObjectiveTitle("AAA Objective") + .withTeamName("firstLevelTeam-" + teamId) + .withObjectiveCreatedOn(LocalDateTime.of(2023, 9, 10, 18, 33)) + .build(), + Overview.Builder.builder() + .withOverviewId(OverviewId.Builder.builder() + .withObjectiveId(index++) + .withTeamId(teamId) + .build()) + .withObjectiveTitle("AAA Objective") + .withTeamName("firstLevelTeam-" + teamId) + .withObjectiveCreatedOn(LocalDateTime.of(2023, 9, 10, 18, 33)) + .build()))); } return overviews; } @@ -123,64 +149,76 @@ void getFilteredOverviewShouldReturnEmptyListOfOverviewsWhenTeamIdsAreNull() { verify(overviewValidationService, times(1)).validateOnGet(QUARTER_ID, List.of()); verify(quarterBusinessService, never()).getCurrentQuarter(); verify(overviewPersistenceService, never()).getFilteredOverview(QUARTER_ID, List.of(), "", authorizationUser); - verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), anyList(), anyString(), - eq(authorizationUser)); + verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), + anyList(), + anyString(), + eq(authorizationUser)); } @Test void getFilteredOverviewShouldReturnExceptionWhenQuarterIdIsNonExistent() { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)).when(overviewValidationService) - .validateOnGet(eq(QUARTER_ID), anyList()); + .validateOnGet(eq(QUARTER_ID), anyList()); assertThrows(ResponseStatusException.class, - () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, List.of(), "", authorizationUser)); + () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, List.of(), "", authorizationUser)); verify(quarterBusinessService, never()).getCurrentQuarter(); verify(overviewValidationService, never()).validateOnGet(QUARTER_ID, teamIds); - verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), anyList(), anyString(), - eq(authorizationUser)); + verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), + anyList(), + anyString(), + eq(authorizationUser)); } @Test void getFilteredOverviewShouldReturnExceptionWhenTeamIdIsNonExistent() { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)).when(overviewValidationService) - .validateOnGet(QUARTER_ID, teamIds); + .validateOnGet(QUARTER_ID, teamIds); assertThrows(ResponseStatusException.class, - () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, teamIds, "", authorizationUser)); + () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, teamIds, "", authorizationUser)); verify(quarterBusinessService, never()).getCurrentQuarter(); verify(overviewValidationService, never()).validateQuarter(QUARTER_ID); verify(overviewValidationService, times(1)).validateOnGet(QUARTER_ID, teamIds); - verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), anyList(), any(), - eq(authorizationUser)); + verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), + anyList(), + any(), + eq(authorizationUser)); } @Test void getFilteredOverviewShouldThrowExceptionWhenTeamIdIsNonExistent() { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)).when(overviewValidationService) - .validateOnGet(QUARTER_ID, teamIds); + .validateOnGet(QUARTER_ID, teamIds); assertThrows(ResponseStatusException.class, - () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, teamIds, "", authorizationUser)); + () -> overviewBusinessService.getFilteredOverview(QUARTER_ID, teamIds, "", authorizationUser)); verify(quarterBusinessService, never()).getCurrentQuarter(); verify(overviewValidationService, times(1)).validateOnGet(QUARTER_ID, teamIds); - verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), anyList(), anyString(), - eq(authorizationUser)); + verify(overviewPersistenceService, never()).getFilteredOverview(anyLong(), + anyList(), + anyString(), + eq(authorizationUser)); } @Test void getFilteredOverviewShouldReturnSortedListUserTeamsFirst() { Long firstLevelTeamId = 5L; AuthorizationUser user = mockAuthorizationUser(defaultUser(13L)); - when(overviewPersistenceService.getFilteredOverview(QUARTER_ID, teamIds, null, user)) - .thenReturn(createOverviews(user)); + when(overviewPersistenceService.getFilteredOverview(QUARTER_ID, + teamIds, + null, + user)).thenReturn(createOverviews(user)); List overviews = overviewBusinessService.getFilteredOverview(QUARTER_ID, teamIds, null, user); - assertThat(List.of(OverviewId.of(1L, 4L, null, null), OverviewId.of(1L, 5L, null, null), - OverviewId.of(1L, 3L, null, null), OverviewId.of(111L, 1L, null, null), - OverviewId.of(222L, 2L, null, null))).hasSameElementsAs(getOverviewIds(overviews)); + assertThat(List.of(OverviewId.of(1L, 4L, null, null), + OverviewId.of(1L, 5L, null, null), + OverviewId.of(1L, 3L, null, null), + OverviewId.of(111L, 1L, null, null), + OverviewId.of(222L, 2L, null, null))).hasSameElementsAs(getOverviewIds(overviews)); } private List getOverviewIds(List overviews) { diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/QuarterBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/QuarterBusinessServiceTest.java index 479620ad3d..6da80f520c 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/QuarterBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/QuarterBusinessServiceTest.java @@ -1,8 +1,21 @@ package ch.puzzle.okr.service.business; +import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; +import static ch.puzzle.okr.test.TestConstants.BACK_LOG_QUARTER_ID; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.service.persistence.QuarterPersistenceService; import ch.puzzle.okr.service.validation.QuarterValidationService; +import java.time.LocalDate; +import java.time.YearMonth; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -16,20 +29,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; -import java.time.LocalDate; -import java.time.YearMonth; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; - -import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; -import static ch.puzzle.okr.test.TestConstants.BACK_LOG_QUARTER_ID; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class QuarterBusinessServiceTest { @Mock @@ -74,14 +73,24 @@ void shouldCallGetQuarters() { @Test void shouldGetBacklogQuarter() { - Quarter realQuarter1 = Quarter.Builder.builder().withId(1L).withLabel("GJ-22/23-Q3") - .withStartDate(LocalDate.of(2022, 4, 1)).withEndDate(LocalDate.of(2022, 7, 31)).build(); - Quarter realQuarter2 = Quarter.Builder.builder().withId(2L).withLabel("GJ-22/23-Q4") - .withStartDate(LocalDate.of(2022, 8, 1)).withEndDate(LocalDate.of(2022, 11, 30)).build(); + Quarter realQuarter1 = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ-22/23-Q3") + .withStartDate(LocalDate.of(2022, 4, 1)) + .withEndDate(LocalDate.of(2022, 7, 31)) + .build(); + Quarter realQuarter2 = Quarter.Builder.builder() + .withId(2L) + .withLabel("GJ-22/23-Q4") + .withStartDate(LocalDate.of(2022, 8, 1)) + .withEndDate(LocalDate.of(2022, 11, 30)) + .build(); List quarterList = new ArrayList<>(Arrays.asList(realQuarter1, realQuarter2)); - Quarter backlogQuarter = Quarter.Builder.builder().withId(BACK_LOG_QUARTER_ID).withLabel(BACK_LOG_QUARTER_LABEL) - .build(); + Quarter backlogQuarter = Quarter.Builder.builder() + .withId(BACK_LOG_QUARTER_ID) + .withLabel(BACK_LOG_QUARTER_LABEL) + .build(); when(quarterPersistenceService.getMostCurrentQuarters()).thenReturn(quarterList); when(quarterPersistenceService.findByLabel(BACK_LOG_QUARTER_LABEL)).thenReturn(backlogQuarter); @@ -93,7 +102,7 @@ void shouldGetBacklogQuarter() { } @ParameterizedTest - @ValueSource(ints = { 1, 2, 4, 5, 7, 8, 10, 11 }) + @ValueSource(ints = {1, 2, 4, 5, 7, 8, 10, 11}) void shouldNotGenerateQuarterIfNotLastMonth(int month) { ReflectionTestUtils.setField(quarterBusinessService, "quarterStart", 7); @@ -103,7 +112,7 @@ void shouldNotGenerateQuarterIfNotLastMonth(int month) { } @ParameterizedTest - @ValueSource(ints = { 3, 6, 9, 12 }) + @ValueSource(ints = {3, 6, 9, 12}) void shouldGenerateQuarterIfLastMonth(int month) { ReflectionTestUtils.setField(quarterBusinessService, "quarterStart", 7); @@ -114,17 +123,17 @@ void shouldGenerateQuarterIfLastMonth(int month) { private static Stream generateQuarterParams() { return Stream.of(Arguments.of(7, "GJ xx/yy-Qzz", YearMonth.of(2030, 3), "GJ 30/31-Q1"), - Arguments.of(7, "GJ xx/yy-Qzz", YearMonth.of(2030, 9), "GJ 30/31-Q3"), - Arguments.of(5, "GJ xx/yy-Qzz", YearMonth.of(2030, 4), "GJ 30/31-Q2"), - Arguments.of(1, "GJ xx-Qzz", YearMonth.of(2030, 9), "GJ 31-Q1"), - Arguments.of(1, "GJ xxxx-Qzz", YearMonth.of(2030, 6), "GJ 2030-Q4"), - Arguments.of(2, "xx-yy-xxxx-yyyy-Qzz", YearMonth.of(2030, 1), "30-31-2030-2031-Q2")); + Arguments.of(7, "GJ xx/yy-Qzz", YearMonth.of(2030, 9), "GJ 30/31-Q3"), + Arguments.of(5, "GJ xx/yy-Qzz", YearMonth.of(2030, 4), "GJ 30/31-Q2"), + Arguments.of(1, "GJ xx-Qzz", YearMonth.of(2030, 9), "GJ 31-Q1"), + Arguments.of(1, "GJ xxxx-Qzz", YearMonth.of(2030, 6), "GJ 2030-Q4"), + Arguments.of(2, "xx-yy-xxxx-yyyy-Qzz", YearMonth.of(2030, 1), "30-31-2030-2031-Q2")); } @ParameterizedTest @MethodSource("generateQuarterParams") void shouldGenerateCorrectQuarter(int quarterStart, String quarterFormat, YearMonth currentYearMonth, - String expectedLabel) { + String expectedLabel) { ReflectionTestUtils.setField(quarterBusinessService, "quarterStart", quarterStart); ReflectionTestUtils.setField(quarterBusinessService, "quarterFormat", quarterFormat); @@ -134,8 +143,12 @@ void shouldGenerateCorrectQuarter(int quarterStart, String quarterFormat, YearMo int monthsToNextQuarterEnd = 6; LocalDate expectedEnd = currentYearMonth.plusMonths(monthsToNextQuarterEnd).atEndOfMonth(); - Quarter expectedQuarter = Quarter.Builder.builder().withId(null).withLabel(expectedLabel) - .withStartDate(expectedStart).withEndDate(expectedEnd).build(); + Quarter expectedQuarter = Quarter.Builder.builder() + .withId(null) + .withLabel(expectedLabel) + .withStartDate(expectedStart) + .withEndDate(expectedEnd) + .build(); Mockito.when(quarterBusinessService.getCurrentYearMonth()).thenReturn(currentYearMonth); @@ -145,12 +158,30 @@ void shouldGenerateCorrectQuarter(int quarterStart, String quarterFormat, YearMo } private static Stream getQuartersParams() { - return Stream.of(Arguments.of(5, 1, 3), Arguments.of(5, 2, 4), Arguments.of(5, 3, 4), Arguments.of(5, 4, 4), - Arguments.of(5, 5, 1), Arguments.of(5, 6, 1), Arguments.of(5, 7, 1), Arguments.of(5, 8, 2), - Arguments.of(5, 9, 2), Arguments.of(5, 10, 2), Arguments.of(5, 11, 3), Arguments.of(5, 12, 3), - Arguments.of(10, 1, 2), Arguments.of(10, 2, 2), Arguments.of(10, 3, 2), Arguments.of(10, 4, 3), - Arguments.of(10, 5, 3), Arguments.of(10, 6, 3), Arguments.of(10, 7, 4), Arguments.of(10, 8, 4), - Arguments.of(10, 9, 4), Arguments.of(10, 10, 1), Arguments.of(10, 11, 1), Arguments.of(10, 12, 1)); + return Stream.of(Arguments.of(5, 1, 3), + Arguments.of(5, 2, 4), + Arguments.of(5, 3, 4), + Arguments.of(5, 4, 4), + Arguments.of(5, 5, 1), + Arguments.of(5, 6, 1), + Arguments.of(5, 7, 1), + Arguments.of(5, 8, 2), + Arguments.of(5, 9, 2), + Arguments.of(5, 10, 2), + Arguments.of(5, 11, 3), + Arguments.of(5, 12, 3), + Arguments.of(10, 1, 2), + Arguments.of(10, 2, 2), + Arguments.of(10, 3, 2), + Arguments.of(10, 4, 3), + Arguments.of(10, 5, 3), + Arguments.of(10, 6, 3), + Arguments.of(10, 7, 4), + Arguments.of(10, 8, 4), + Arguments.of(10, 9, 4), + Arguments.of(10, 10, 1), + Arguments.of(10, 11, 1), + Arguments.of(10, 12, 1)); } @ParameterizedTest(name = "Start month={0}, current month={1} => quarter={2}") diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/TeamBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/TeamBusinessServiceTest.java index e5586543ec..e0e7a6ac46 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/TeamBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/TeamBusinessServiceTest.java @@ -1,5 +1,12 @@ package ch.puzzle.okr.service.business; +import static ch.puzzle.okr.models.State.DRAFT; +import static ch.puzzle.okr.models.State.SUCCESSFUL; +import static ch.puzzle.okr.test.TestHelper.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -12,6 +19,8 @@ import ch.puzzle.okr.service.persistence.UserPersistenceService; import ch.puzzle.okr.service.persistence.UserTeamPersistenceService; import ch.puzzle.okr.service.validation.TeamValidationService; +import java.util.ArrayList; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,16 +30,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.mock.mockito.MockBean; -import java.util.ArrayList; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.*; -import static ch.puzzle.okr.models.State.DRAFT; -import static ch.puzzle.okr.models.State.SUCCESSFUL; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class TeamBusinessServiceTest { @MockBean @@ -65,19 +64,36 @@ class TeamBusinessServiceTest { @BeforeEach void setUp() { this.team1 = Team.Builder.builder().withId(1L).withName("Team 1").build(); - this.team1.setUserTeamList(List.of( - UserTeam.Builder.builder().withTeam(team1).withUser(defaultUser(2L)).withTeamAdmin(true).build(), - UserTeam.Builder.builder().withTeam(team1).withUser(defaultUser(3L)).withTeamAdmin(false).build())); + this.team1.setUserTeamList(List.of(UserTeam.Builder.builder() + .withTeam(team1) + .withUser(defaultUser(2L)) + .withTeamAdmin(true) + .build(), + UserTeam.Builder.builder() + .withTeam(team1) + .withUser(defaultUser(3L)) + .withTeamAdmin(false) + .build())); this.team2 = Team.Builder.builder().withId(2L).withName("Team 2").build(); - this.team2.setUserTeamList(List.of( - UserTeam.Builder.builder().withTeam(team2).withUser(defaultUser(4L)).withTeamAdmin(true).build(), - UserTeam.Builder.builder().withTeam(team2).withUser(defaultUser(5L)).withTeamAdmin(true).build())); + this.team2.setUserTeamList(List.of(UserTeam.Builder.builder() + .withTeam(team2) + .withUser(defaultUser(4L)) + .withTeamAdmin(true) + .build(), + UserTeam.Builder.builder() + .withTeam(team2) + .withUser(defaultUser(5L)) + .withTeamAdmin(true) + .build())); this.team3 = Team.Builder.builder().withId(3L).withName("Team 3").build(); this.team3.setUserTeamList(List.of()); this.teamWithIdNull = Team.Builder.builder().withName("Team with id null").build(); this.objective = Objective.Builder.builder().withId(5L).withTitle("Objective 1").withState(DRAFT).build(); - this.objectiveCompleted = Objective.Builder.builder().withId(6L).withTitle("Objective 1").withState(SUCCESSFUL) - .build(); + this.objectiveCompleted = Objective.Builder.builder() + .withId(6L) + .withTitle("Objective 1") + .withState(SUCCESSFUL) + .build(); this.objectiveList = List.of(objective, objective, objective, objectiveCompleted); } @@ -107,11 +123,18 @@ void getAllTeamsSortedShouldReturnSortedListUserTeamsFirst() { Team notUserTeam2 = Team.Builder.builder().withId(3L).withName("NOTUserTeam2").withVersion(1).build(); List teams = List.of(notUserTeam, userTeam, notUserTeam2); User user = defaultUser(13L); - List userTeamList = List - .of(UserTeam.Builder.builder().withUser(user).withTeam(userTeam).withId(1L).build()); - AuthorizationUser authUser = new AuthorizationUser(User.Builder.builder().withId(user.getId()) - .withFirstname(user.getFirstname()).withLastname(user.getLastname()).withEmail(user.getEmail()) - .withUserTeamList(userTeamList).build()); + List userTeamList = List.of(UserTeam.Builder.builder() + .withUser(user) + .withTeam(userTeam) + .withId(1L) + .build()); + AuthorizationUser authUser = new AuthorizationUser(User.Builder.builder() + .withId(user.getId()) + .withFirstname(user.getFirstname()) + .withLastname(user.getLastname()) + .withEmail(user.getEmail()) + .withUserTeamList(userTeamList) + .build()); when(teamPersistenceService.findAll()).thenReturn(teams); List sortedList = teamBusinessService.getAllTeams(authUser); @@ -146,8 +169,11 @@ void shouldUpdateTeam() { @Test void shouldDeleteTeamAndItsObjectives() { var team = defaultTeam(1L); - team.setUserTeamList( - List.of(UserTeam.Builder.builder().withTeam(team).withUser(new User()).withId(1L).build())); + team.setUserTeamList(List.of(UserTeam.Builder.builder() + .withTeam(team) + .withUser(new User()) + .withId(1L) + .build())); when(objectiveBusinessService.getEntitiesByTeamId(team.getId())).thenReturn(objectiveList); when(teamPersistenceService.findById(team.getId())).thenReturn(team); @@ -192,7 +218,7 @@ void removeUserFromTeam_shouldRemoveUser() { teamBusinessService.removeUserFromTeam(team2.getId(), user.getId()); assertEquals(2, user.getUserTeamList().size()); assertEquals(user.getUserTeamList().stream().map(ut -> ut.getTeam().getId()).toList(), - List.of(team1.getId(), team3.getId())); + List.of(team1.getId(), team3.getId())); verify(cacheService, times(1)).emptyAuthorizationUsersCache(); } @@ -212,8 +238,8 @@ void removeUserFromTeam_shouldThrowExceptionWhenLastAdminShouldBeRemoved() { when(teamPersistenceService.findById(team1.getId())).thenReturn(team1); assertThrows(OkrResponseStatusException.class, - () -> teamBusinessService.removeUserFromTeam(team1.getId(), user.getId()), - ErrorKey.TRIED_TO_DELETE_LAST_ADMIN.toString()); + () -> teamBusinessService.removeUserFromTeam(team1.getId(), user.getId()), + ErrorKey.TRIED_TO_DELETE_LAST_ADMIN.toString()); } @Test @@ -235,7 +261,7 @@ void updateOrAddTeamMembership_shouldThrowExceptionIfLastAdminShouldBeRemoved() when(userPersistenceService.findById(user.getId())).thenReturn(user); assertThrows(OkrResponseStatusException.class, - () -> teamBusinessService.updateOrAddTeamMembership(team1.getId(), user.getId(), false)); + () -> teamBusinessService.updateOrAddTeamMembership(team1.getId(), user.getId(), false)); } @Test diff --git a/backend/src/test/java/ch/puzzle/okr/service/business/UserBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/UserBusinessServiceTest.java index 70fadedb2d..28206deaef 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/UserBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/UserBusinessServiceTest.java @@ -1,11 +1,17 @@ package ch.puzzle.okr.service.business; -import ch.puzzle.okr.test.TestHelper; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.service.CacheService; import ch.puzzle.okr.service.persistence.UserPersistenceService; import ch.puzzle.okr.service.validation.UserValidationService; +import ch.puzzle.okr.test.TestHelper; +import java.util.Arrays; +import java.util.List; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -17,13 +23,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.Arrays; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class UserBusinessServiceTest { @Mock @@ -39,18 +38,18 @@ class UserBusinessServiceTest { @BeforeEach void setUp() { User userAlice = User.Builder.builder() // - .withId(2L) // - .withFirstname("Alice") // - .withLastname("Wunderland") // - .withEmail("wunderland@puzzle.ch") // - .build(); + .withId(2L) // + .withFirstname("Alice") // + .withLastname("Wunderland") // + .withEmail("wunderland@puzzle.ch") // + .build(); User userBob = User.Builder.builder() // - .withId(9L) // - .withFirstname("Bob") // - .withLastname("Baumeister") // - .withEmail("baumeister@puzzle.ch") // - .build(); + .withId(9L) // + .withFirstname("Bob") // + .withLastname("Baumeister") // + .withEmail("baumeister@puzzle.ch") // + .build(); userList = Arrays.asList(userAlice, userBob); } @@ -81,8 +80,12 @@ void shouldReturnEmptyUsers() throws ResponseStatusException { @Test void shouldReturnSingleUserWhenFindingOwnerByValidId() { - User owner = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); + User owner = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); Mockito.when(userPersistenceService.findById(any())).thenReturn(owner); User returnedUser = userBusinessService.getUserById(1L); @@ -95,8 +98,12 @@ void shouldReturnSingleUserWhenFindingOwnerByValidId() { @Test void getOrCreateUserShouldReturnSingleUserWhenUserFound() { - User newUser = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); + User newUser = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); Mockito.when(userPersistenceService.getOrCreateUser(any())).thenReturn(newUser); User returnedUser = userBusinessService.getOrCreateUser(newUser); @@ -109,8 +116,12 @@ void getOrCreateUserShouldReturnSingleUserWhenUserFound() { @Test void getOrCreateUserShouldReturnSavedUserWhenUserNotFound() { - User newUser = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); + User newUser = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); Mockito.when(userPersistenceService.getOrCreateUser(newUser)).thenReturn(newUser); User returnedUser = userBusinessService.getOrCreateUser(newUser); @@ -123,13 +134,18 @@ void getOrCreateUserShouldReturnSavedUserWhenUserNotFound() { @Test void getOrCreateUserShouldThrowResponseStatusExceptionWhenInvalidUser() { - User newUser = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); + User newUser = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); Mockito.doThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Not allowed to give an id")) - .when(validationService).validateOnGetOrCreate(newUser); + .when(validationService) + .validateOnGetOrCreate(newUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> userBusinessService.getOrCreateUser(newUser)); + () -> userBusinessService.getOrCreateUser(newUser)); assertEquals(HttpStatus.BAD_REQUEST, exception.getStatusCode()); assertEquals("Not allowed to give an id", exception.getReason()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceIT.java index e0ba905289..74b220470a 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceIT.java @@ -1,8 +1,12 @@ package ch.puzzle.okr.service.clientconfig; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrowsExactly; + import ch.puzzle.okr.dto.ClientConfigDto; import ch.puzzle.okr.test.SpringIntegrationTest; import jakarta.persistence.EntityNotFoundException; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -10,11 +14,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrowsExactly; - @SpringIntegrationTest @SpringBootTest() class ClientConfigServiceIT { @@ -25,7 +24,7 @@ class ClientConfigServiceIT { @ParameterizedTest @MethodSource("tenantConfigs") void getConfigBasedOnActiveEnv_validSubdomain_returnsCorrectTenantConfig(String hostname, String activeProfile, - String issuer, String clientId) { + String issuer, String clientId) { // arrange + act ClientConfigDto clientConfig = clientConfigService.getConfigBasedOnActiveEnv(hostname); @@ -37,15 +36,20 @@ void getConfigBasedOnActiveEnv_validSubdomain_returnsCorrectTenantConfig(String } private static Stream tenantConfigs() { - return Stream.of( - Arguments.of("pitc.okr.puzzle.ch", "prod", "http://localhost:8544/realms/pitc", "pitc_okr_staging"), - Arguments.of("acme.okr.puzzle.ch", "prod", "http://localhost:8544/realms/pitc", "acme_okr_staging")); + return Stream.of(Arguments.of("pitc.okr.puzzle.ch", + "prod", + "http://localhost:8544/realms/pitc", + "pitc_okr_staging"), + Arguments.of("acme.okr.puzzle.ch", + "prod", + "http://localhost:8544/realms/pitc", + "acme_okr_staging")); } @Test void getConfigBasedOnActiveEnv_invalidSubdomain_throwsException() { assertThrowsExactly(EntityNotFoundException.class, - () -> clientConfigService.getConfigBasedOnActiveEnv("foobar.okr.puzzle.ch")); + () -> clientConfigService.getConfigBasedOnActiveEnv("foobar.okr.puzzle.ch")); } @Test diff --git a/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceTest.java index 98daa385e4..db9c489924 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/clientconfig/ClientConfigServiceTest.java @@ -1,26 +1,25 @@ package ch.puzzle.okr.service.clientconfig; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.dto.ClientConfigDto; import ch.puzzle.okr.multitenancy.TenantConfigProvider; import ch.puzzle.okr.multitenancy.customization.TenantClientCustomization; import ch.puzzle.okr.multitenancy.customization.TenantClientCustomizationProvider; import jakarta.persistence.EntityNotFoundException; +import java.util.HashMap; +import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import java.util.HashMap; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class ClientConfigServiceTest { @DisplayName("getConfigBasedOnActiveEnv() should be successful when tenant is configured properly") @ParameterizedTest - @CsvSource({ "pitc,pitc.ork.ch", "acme,acme-ork.ch" }) + @CsvSource({"pitc,pitc.ork.ch", "acme,acme-ork.ch"}) void getConfigBasedOnActiveEnvShouldBeSuccessfulWhenTenantIsConfiguredProperly(String tenant, String hostname) { // arrange TenantConfigProvider.TenantConfig tenantConfig = getTenantConfig(tenant); @@ -36,9 +35,9 @@ void getConfigBasedOnActiveEnvShouldBeSuccessfulWhenTenantIsConfiguredProperly(S @DisplayName("getConfigBasedOnActiveEnv() should throw exception if client customization is not found") @ParameterizedTest - @CsvSource({ "pitc,pitc.okr.ch,pitc", "acme,acme-okr.ch,acme-okr" }) + @CsvSource({"pitc,pitc.okr.ch,pitc", "acme,acme-okr.ch,acme-okr"}) void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientCustomizationIsNotFound(String tenant, String hostname, - String subdomain) { + String subdomain) { // arrange TenantConfigProvider.TenantConfig tenantConfig = getTenantConfig(tenant); ClientConfigService service = getClientConfig(tenantConfig, tenant); @@ -53,9 +52,9 @@ void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientCustomizationIsNotFoun @DisplayName("getConfigBasedOnActiveEnv() should throw exception if client config is not found") @ParameterizedTest - @CsvSource({ "pitc,pitc.okr.ch,pitc", "acme,acme-okr.ch,acme-okr" }) + @CsvSource({"pitc,pitc.okr.ch,pitc", "acme,acme-okr.ch,acme-okr"}) void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientConfigIsNotFound(String tenant, String hostname, - String subdomain) { + String subdomain) { // arrange TenantClientCustomization tenantCustomization = getTenantClientCustomization(tenant); ClientConfigService service = getClientConfig(tenantCustomization, tenant); @@ -69,7 +68,7 @@ void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientConfigIsNotFound(Strin } private ClientConfigService getClientConfig(TenantConfigProvider.TenantConfig tenantConfig, - TenantClientCustomization tenantClientCustomization, String tenantId) { + TenantClientCustomization tenantClientCustomization, String tenantId) { return mockClientConfigService(tenantConfig, tenantClientCustomization, tenantId); } @@ -82,38 +81,39 @@ private ClientConfigService getClientConfig(TenantConfigProvider.TenantConfig te } private ClientConfigService mockClientConfigService(TenantConfigProvider.TenantConfig tenantConfig, - TenantClientCustomization tenantCustomization, String tenantId) { + TenantClientCustomization tenantCustomization, + String tenantId) { TenantClientCustomizationProvider tenantCustomizationProvider = mock(TenantClientCustomizationProvider.class); when(tenantCustomizationProvider.getTenantClientCustomizationsById(tenantId)) // - .thenReturn(Optional.ofNullable(tenantCustomization)); + .thenReturn(Optional.ofNullable(tenantCustomization)); TenantConfigProvider tenantConfigProvider = mock(TenantConfigProvider.class); when(tenantConfigProvider.getTenantConfigById(tenantId)) // - .thenReturn(Optional.ofNullable(tenantConfig)); + .thenReturn(Optional.ofNullable(tenantConfig)); return new ClientConfigService(tenantCustomizationProvider, tenantConfigProvider); } private TenantConfigProvider.TenantConfig getTenantConfig(String tenantId) { return new TenantConfigProvider.TenantConfig( // - prefix(tenantId) + "tenantId", // - new String[] {}, // - prefix(tenantId) + "jwkSetUri", // - prefix(tenantId) + "issuerUrl", // - prefix(tenantId) + "clientId", // - null); + prefix(tenantId) + "tenantId", // + new String[]{}, // + prefix(tenantId) + "jwkSetUri", // + prefix(tenantId) + "issuerUrl", // + prefix(tenantId) + "clientId", // + null); } private TenantClientCustomization getTenantClientCustomization(String tenantId) { return new TenantClientCustomization( // - prefix(tenantId) + "favicon", // - prefix(tenantId) + "logo", // - prefix(tenantId) + "triangles", // - prefix(tenantId) + "backgroundLogo", // - prefix(tenantId) + "title", // - prefix(tenantId) + "helpSiteUrl", // - new HashMap<>()); + prefix(tenantId) + "favicon", // + prefix(tenantId) + "logo", // + prefix(tenantId) + "triangles", // + prefix(tenantId) + "backgroundLogo", // + prefix(tenantId) + "title", // + prefix(tenantId) + "helpSiteUrl", // + new HashMap<>()); } private void assertClientConfigDto(ClientConfigDto clientConfigDto, String tenant) { diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/ActionPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/ActionPersistenceServiceIT.java index b8e62b6a63..8199450f71 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/ActionPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/ActionPersistenceServiceIT.java @@ -1,6 +1,9 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Action; @@ -8,18 +11,14 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; - @SpringIntegrationTest class ActionPersistenceServiceIT { Action createdAction; @@ -31,11 +30,21 @@ private static Action createAction(Long id) { } private static Action createAction(Long id, int version) { - return Action.Builder.builder().withId(id).withVersion(version).withAction("Neue Katze").withPriority(0) - .withIsChecked(false) - .withKeyResult(KeyResultMetric.Builder.builder().withBaseline(1.0).withStretchGoal(13.0).withId(8L) - .withObjective(Objective.Builder.builder().withId(1L).build()).build()) - .build(); + return Action.Builder.builder() + .withId(id) + .withVersion(version) + .withAction("Neue Katze") + .withPriority(0) + .withIsChecked(false) + .withKeyResult(KeyResultMetric.Builder.builder() + .withBaseline(1.0) + .withStretchGoal(13.0) + .withId(8L) + .withObjective(Objective.Builder.builder() + .withId(1L) + .build()) + .build()) + .build(); } private static final String UPDATED_ACTION = "Updated Action"; @@ -94,7 +103,7 @@ void updateActionShouldThrowExceptionWhenAlreadyUpdated() { changedAction.setAction(UPDATED_ACTION); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> actionPersistenceService.save(changedAction)); + () -> actionPersistenceService.save(changedAction)); List expectedErrors = List.of(new ErrorDto("DATA_HAS_BEEN_UPDATED", List.of("Action"))); assertEquals(UNPROCESSABLE_ENTITY, exception.getStatusCode()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceServiceIT.java index de38eed3a5..c4dce48e98 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentPersistenceServiceIT.java @@ -1,6 +1,9 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -10,18 +13,14 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; - @SpringIntegrationTest class AlignmentPersistenceServiceIT { @Autowired @@ -29,9 +28,11 @@ class AlignmentPersistenceServiceIT { private Alignment createdAlignment; private static ObjectiveAlignment createObjectiveAlignment(Long id) { - return ObjectiveAlignment.Builder.builder().withId(id) - .withAlignedObjective(Objective.Builder.builder().withId(5L).build()) - .withTargetObjective(Objective.Builder.builder().withId(4L).build()).build(); + return ObjectiveAlignment.Builder.builder() + .withId(id) + .withAlignedObjective(Objective.Builder.builder().withId(5L).build()) + .withTargetObjective(Objective.Builder.builder().withId(4L).build()) + .build(); } private static KeyResultAlignment createKeyResultAlignment(Long id) { @@ -39,9 +40,12 @@ private static KeyResultAlignment createKeyResultAlignment(Long id) { } private static KeyResultAlignment createKeyResultAlignment(Long id, int version) { - return KeyResultAlignment.Builder.builder().withId(id).withVersion(version) - .withAlignedObjective(Objective.Builder.builder().withId(5L).build()) - .withTargetKeyResult(KeyResultMetric.Builder.builder().withId(8L).build()).build(); + return KeyResultAlignment.Builder.builder() + .withId(id) + .withVersion(version) + .withAlignedObjective(Objective.Builder.builder().withId(5L).build()) + .withTargetKeyResult(KeyResultMetric.Builder.builder().withId(8L).build()) + .build(); } @BeforeEach @@ -105,7 +109,7 @@ void updateAlignmentShouldThrowExceptionWhenAlreadyUpdated() { updateAlignment.setAlignedObjective(Objective.Builder.builder().withId(8L).build()); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> alignmentPersistenceService.save(updateAlignment)); + () -> alignmentPersistenceService.save(updateAlignment)); List expectedErrors = List.of(new ErrorDto("DATA_HAS_BEEN_UPDATED", List.of("Alignment"))); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceServiceIT.java index 60ab85c7d9..5dab535f1f 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/AlignmentSelectionPersistenceServiceIT.java @@ -1,21 +1,20 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import ch.puzzle.okr.models.alignment.AlignmentSelection; import ch.puzzle.okr.models.alignment.AlignmentSelectionId; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; +import java.util.List; +import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - @SpringIntegrationTest class AlignmentSelectionPersistenceServiceIT { @Autowired @@ -33,12 +32,11 @@ void tearDown() { @Test void getAlignmentSelectionByQuarterIdAndTeamIdNotShouldReturnAlignmentSelections() { - List alignmentSelections = alignmentSelectionPersistenceService - .getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, 4L); + List alignmentSelections = alignmentSelectionPersistenceService.getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, + 4L); assertEquals(12, alignmentSelections.size()); - alignmentSelections.forEach(alignmentSelection -> assertTrue( - matchAlignmentSelectionId(alignmentSelection.getAlignmentSelectionId()))); + alignmentSelections.forEach(alignmentSelection -> assertTrue(matchAlignmentSelectionId(alignmentSelection.getAlignmentSelectionId()))); } private boolean matchAlignmentSelectionId(AlignmentSelectionId alignmentSelectionId) { @@ -47,16 +45,16 @@ private boolean matchAlignmentSelectionId(AlignmentSelectionId alignmentSelectio private static Stream getExpectedAlignmentSelectionIds() { return Stream.of(AlignmentSelectionId.of(9L, 15L), // - AlignmentSelectionId.of(9L, 16L), // - AlignmentSelectionId.of(9L, 17L), // - AlignmentSelectionId.of(4L, 6L), // - AlignmentSelectionId.of(4L, 7L), // - AlignmentSelectionId.of(4L, 8L), // - AlignmentSelectionId.of(3L, 3L), // - AlignmentSelectionId.of(3L, 4L), // - AlignmentSelectionId.of(3L, 5L), // - AlignmentSelectionId.of(8L, 18L), // - AlignmentSelectionId.of(8L, 19L), // - AlignmentSelectionId.of(10L, -1L)); + AlignmentSelectionId.of(9L, 16L), // + AlignmentSelectionId.of(9L, 17L), // + AlignmentSelectionId.of(4L, 6L), // + AlignmentSelectionId.of(4L, 7L), // + AlignmentSelectionId.of(4L, 8L), // + AlignmentSelectionId.of(3L, 3L), // + AlignmentSelectionId.of(3L, 4L), // + AlignmentSelectionId.of(3L, 5L), // + AlignmentSelectionId.of(8L, 18L), // + AlignmentSelectionId.of(8L, 19L), // + AlignmentSelectionId.of(10L, -1L)); } } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaIT.java index 7d1e4450ce..60e673d4ff 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaIT.java @@ -1,21 +1,20 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import static ch.puzzle.okr.test.TestHelper.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.*; -import static org.junit.jupiter.api.Assertions.assertEquals; - @SpringIntegrationTest class AuthorizationCriteriaIT { @@ -65,8 +64,10 @@ void appendObjectiveShouldReturnObjectiveWhenMemberRole() { void appendOverviewShouldReturnObjectiveWhenFirstLevelRoleAndTeamIdsEmpty() { Long quarterId = 2L; AuthorizationUser authorizationUser = defaultAuthorizationUser(); - List overviews = overviewPersistenceService.getFilteredOverview(quarterId, List.of(), "", - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(quarterId, + List.of(), + "", + authorizationUser); assertEquals(18L, overviews.size()); } @@ -75,8 +76,10 @@ void appendOverviewShouldReturnObjectiveWhenFirstLevelRoleAndTeamIdsEmpty() { void appendOverviewShouldReturnObjectiveWhenSecondLevelRole() { Long quarterId = 2L; AuthorizationUser authorizationUser = mockAuthorizationUser(defaultUser(null)); - List overviews = overviewPersistenceService.getFilteredOverview(quarterId, List.of(5L), "", - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(quarterId, + List.of(5L), + "", + authorizationUser); assertEquals(6L, overviews.size()); } @@ -85,8 +88,10 @@ void appendOverviewShouldReturnObjectiveWhenSecondLevelRole() { void appendOverviewShouldReturnObjectiveWhenMemberRole() { Long quarterId = 2L; AuthorizationUser authorizationUser = mockAuthorizationUser(defaultUser(null)); - List overviews = overviewPersistenceService.getFilteredOverview(quarterId, List.of(5L), "", - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(quarterId, + List.of(5L), + "", + authorizationUser); assertEquals(6L, overviews.size()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaParametersTest.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaParametersTest.java index 7cff83afd8..201b3f2b0c 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaParametersTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaParametersTest.java @@ -1,8 +1,14 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static ch.puzzle.okr.test.TestHelper.mockAuthorizationUser; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.User; import jakarta.persistence.*; +import java.util.*; +import java.util.stream.Stream; import org.apache.commons.lang3.NotImplementedException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -10,13 +16,6 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.*; -import java.util.stream.Stream; - -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static ch.puzzle.okr.test.TestHelper.mockAuthorizationUser; -import static org.junit.jupiter.api.Assertions.assertEquals; - public class AuthorizationCriteriaParametersTest { @DisplayName("setParameters() should be successful with default authorization user") @@ -44,12 +43,12 @@ void setParametersShouldBeSuccessfulWithDefaultAuthorizationUser() { void setParametersShouldBeSuccessfulWhenUserIsOkrChampion() { // arrange var user = User.Builder.builder() // - .withId(23L) // - .withFirstname("Hanna") // - .withLastname("muster") // - .withEmail("hanna.muster@example.com") // - .withOkrChampion(true) // - .build(); + .withId(23L) // + .withFirstname("Hanna") // + .withLastname("muster") // + .withEmail("hanna.muster@example.com") // + .withOkrChampion(true) // + .build(); var criteria = new AuthorizationCriteria(); TypedQueryMock typedQueryMock = new TypedQueryMock<>(); @@ -88,10 +87,10 @@ void setParametersShouldBeSuccessfulWhenTeamIdsOrObjectiveQueryAreEmpty(List provideListAndString() { return Stream.of( // - Arguments.of(List.of(), null), // - Arguments.of(List.of(), ""), // - Arguments.of(null, null), // - Arguments.of(null, "")); + Arguments.of(List.of(), null), // + Arguments.of(List.of(), ""), // + Arguments.of(null, null), // + Arguments.of(null, "")); } @DisplayName("setParameters() should be successful when team ids and objective query are not empty") @@ -118,8 +117,10 @@ void setParametersShouldBeSuccessfulWhenTeamIdsAndObjectiveQueryAreNotEmpty() { assertEquals(expected, typedQueryMock.getLog()); } - // TypedQuery implementation for testing. The setParameterX() methods calls are logged in an internal StringBuilder - // which is return by getLog(). This log can be used for checking the internal state of the TypedQuery. All other + // TypedQuery implementation for testing. The setParameterX() methods calls are + // logged in an internal StringBuilder + // which is return by getLog(). This log can be used for checking the internal + // state of the TypedQuery. All other // methods are not implemented. private static class TypedQueryMock implements TypedQuery { @@ -131,80 +132,101 @@ public String getLog() { @Override public TypedQuery setParameter(Parameter parameter, T t) { - log.append(parameter.getName()).append(", ") // - .append(t.getClass().getSimpleName()).append("=").append(t) // - .append("\n"); + log.append(parameter.getName()) + .append(", ") // + .append(t.getClass().getSimpleName()) + .append("=") + .append(t) // + .append("\n"); return null; } @Override public TypedQuery setParameter(Parameter parameter, Calendar calendar, - TemporalType temporalType) { - log.append(parameter.getName()).append(", ") // - .append(calendar.getTime()).append(", ") // - .append(temporalType.name()) // - .append("\n"); + TemporalType temporalType) { + log.append(parameter.getName()) + .append(", ") // + .append(calendar.getTime()) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } @Override public TypedQuery setParameter(Parameter parameter, Date date, TemporalType temporalType) { - log.append(parameter.getName()).append(", ") // - .append(date).append(", ") // - .append(temporalType.name()) // - .append("\n"); + log.append(parameter.getName()) + .append(", ") // + .append(date) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } @Override public TypedQuery setParameter(String s, Object o) { - log.append(s).append(", ") // - .append(o.getClass().getSimpleName()).append("=").append(o) // - .append("\n"); + log.append(s) + .append(", ") // + .append(o.getClass().getSimpleName()) + .append("=") + .append(o) // + .append("\n"); return null; } @Override public TypedQuery setParameter(String s, Calendar calendar, TemporalType temporalType) { - log.append(s).append(", ") // - .append(calendar.getTime()).append(", ") // - .append(temporalType.name()) // - .append("\n"); + log.append(s) + .append(", ") // + .append(calendar.getTime()) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } @Override public TypedQuery setParameter(String s, Date date, TemporalType temporalType) { - log.append(s).append(", ") // - .append(date).append(", ") // - .append(temporalType.name()) // - .append("\n"); + log.append(s) + .append(", ") // + .append(date) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } @Override public TypedQuery setParameter(int i, Object o) { - log.append(i).append(", ") // - .append(o.getClass().getSimpleName()).append("=").append(o) // - .append("\n"); + log.append(i) + .append(", ") // + .append(o.getClass().getSimpleName()) + .append("=") + .append(o) // + .append("\n"); return null; } @Override public TypedQuery setParameter(int i, Calendar calendar, TemporalType temporalType) { - log.append(i).append(", ") // - .append(calendar.getTime()).append(", ") // - .append(temporalType.name()) // - .append("\n"); + log.append(i) + .append(", ") // + .append(calendar.getTime()) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } @Override public TypedQuery setParameter(int i, Date date, TemporalType temporalType) { - log.append(i).append(", ") // - .append(date).append(", ") // - .append(temporalType.name()) // - .append("\n"); + log.append(i) + .append(", ") // + .append(date) + .append(", ") // + .append(temporalType.name()) // + .append("\n"); return null; } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaTest.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaTest.java index bdb382edaf..76b232ce30 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/AuthorizationCriteriaTest.java @@ -1,21 +1,20 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static ch.puzzle.okr.test.TestHelper.mockAuthorizationUser; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.models.User; +import java.util.List; +import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.List; -import java.util.stream.Stream; - -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static ch.puzzle.okr.test.TestHelper.mockAuthorizationUser; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - public class AuthorizationCriteriaTest { @DisplayName("appendObjective() should be successful with default authorization user") @@ -37,12 +36,12 @@ void appendObjectiveShouldBeSuccessfulWithDefaultAuthorizationUser() { void appendObjectiveShouldBeSuccessfulWhenUserIsOkrChampion() { // arrange var user = User.Builder.builder() // - .withId(23L) // - .withFirstname("Hanna") // - .withLastname("muster") // - .withEmail("hanna.muster@example.com") // - .withOkrChampion(true) // - .build(); + .withId(23L) // + .withFirstname("Hanna") // + .withLastname("muster") // + .withEmail("hanna.muster@example.com") // + .withOkrChampion(true) // + .build(); var criteria = new AuthorizationCriteria(); // act @@ -57,7 +56,7 @@ void appendObjectiveShouldBeSuccessfulWhenUserIsOkrChampion() { @ParameterizedTest @MethodSource("provideListAndString") void appendOverviewShouldBeSuccessfulWhenTeamIdsOrObjectiveQueryAreEmpty(List teamIds, - String objectiveQuery) { + String objectiveQuery) { // arrange var criteria = new AuthorizationCriteria(); @@ -71,10 +70,10 @@ void appendOverviewShouldBeSuccessfulWhenTeamIdsOrObjectiveQueryAreEmpty(List provideListAndString() { return Stream.of( // - Arguments.of(List.of(), null), // - Arguments.of(List.of(), ""), // - Arguments.of(null, null), // - Arguments.of(null, "")); + Arguments.of(List.of(), null), // + Arguments.of(List.of(), ""), // + Arguments.of(null, null), // + Arguments.of(null, "")); } @DisplayName("appendOverview() should be successful when team ids and objective query are not empty") @@ -92,10 +91,10 @@ void appendOverviewShouldBeSuccessfulWhenTeamIdsAndObjectiveQueryAreNotEmpty() { // assert var expected = startingNewLine + singleSpace - + """ - and o.overviewId.teamId in (:teamIds) - and lower(coalesce(o.objectiveTitle, '')) like lower(concat('%',:objectiveQuery,'%')) - and ((o.objectiveState=:teamDraftState and o.overviewId.teamId IN (:userTeamIds)) or o.objectiveState IN (:publishedStates) or o.overviewId.objectiveId = -1)"""; + + """ + and o.overviewId.teamId in (:teamIds) + and lower(coalesce(o.objectiveTitle, '')) like lower(concat('%',:objectiveQuery,'%')) + and ((o.objectiveState=:teamDraftState and o.overviewId.teamId IN (:userTeamIds)) or o.objectiveState IN (:publishedStates) or o.overviewId.objectiveId = -1)"""; assertEquals(expected, current); assertFalse(current.contains(anyNonEmptyString)); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/CheckInPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/CheckInPersistenceServiceIT.java index 0837b5f996..7eaae1c7ba 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/CheckInPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/CheckInPersistenceServiceIT.java @@ -1,24 +1,23 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.CHECK_IN; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; +import java.util.List; +import java.util.Objects; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; -import java.util.Objects; - -import static ch.puzzle.okr.Constants.CHECK_IN; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - @SpringIntegrationTest class CheckInPersistenceServiceIT { @@ -42,8 +41,7 @@ void tearDown() { @Test void getCheckInsByKeyResultIdOrderByCheckInDateShouldGetCheckInsByKeyResultIdAndOrderThemByDateDesc() { // act - List checkIns = checkInPersistenceService - .getCheckInsByKeyResultIdOrderByCheckInDateDesc(KEY_RESULT_ID); + List checkIns = checkInPersistenceService.getCheckInsByKeyResultIdOrderByCheckInDateDesc(KEY_RESULT_ID); // assert assertThat(2, greaterThanOrEqualTo(checkIns.size())); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/CompletedPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/CompletedPersistenceServiceIT.java index 651cfa0b88..4beae7a108 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/CompletedPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/CompletedPersistenceServiceIT.java @@ -1,25 +1,24 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.http.HttpStatus.NOT_FOUND; +import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Completed; import ch.puzzle.okr.models.Objective; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.springframework.http.HttpStatus.NOT_FOUND; -import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; - @SpringIntegrationTest class CompletedPersistenceServiceIT { @Autowired @@ -34,9 +33,15 @@ private static Completed createCompleted(Long id) { } private static Completed createCompleted(Long id, int version) { - return Completed.Builder.builder().withId(id).withVersion(version) - .withObjective(Objective.Builder.builder().withId(OBJECTIVE_ID).withTitle(GUTE_LERNENDE).build()) - .withComment(WIR_HABEN_ES_GUT_GESCHAFFT).build(); + return Completed.Builder.builder() + .withId(id) + .withVersion(version) + .withObjective(Objective.Builder.builder() + .withId(OBJECTIVE_ID) + .withTitle(GUTE_LERNENDE) + .build()) + .withComment(WIR_HABEN_ES_GUT_GESCHAFFT) + .build(); } private static final String COMPLETED = "Completed"; @@ -91,7 +96,7 @@ void updateCompletedShouldThrowExceptionWhenAlreadyUpdated() { updateCompleted.setComment("Updated completed"); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> completedPersistenceService.save(updateCompleted)); + () -> completedPersistenceService.save(updateCompleted)); List expectedErrors = List.of(new ErrorDto("DATA_HAS_BEEN_UPDATED", List.of(COMPLETED))); @@ -107,7 +112,7 @@ void getCompletedShouldGetCompletedByObjectiveId() { assertNotNull(savedCompleted.getId()); assertEquals("War leider nicht moeglich", savedCompleted.getComment()); assertEquals("Als BBT wollen wir den Arbeitsalltag der Members von Puzzle ITC erleichtern.", - savedCompleted.getObjective().getTitle()); + savedCompleted.getObjective().getTitle()); } @Test @@ -116,7 +121,7 @@ void deleteCompletedIdShouldDeleteExistingCompletedByObjectiveId() { completedPersistenceService.deleteById(3L); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> completedPersistenceService.findById(3L)); + () -> completedPersistenceService.findById(3L)); List expectedErrors = List.of(new ErrorDto("MODEL_WITH_ID_NOT_FOUND", List.of(COMPLETED, "3"))); @@ -132,7 +137,7 @@ void deleteCompletedShouldThrowExceptionWhenCompletedNotFound() { Long completedId = createdCompleted.getId(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> completedPersistenceService.findById(completedId)); + () -> completedPersistenceService.findById(completedId)); List expectedErrors = List.of(new ErrorDto("MODEL_WITH_ID_NOT_FOUND", List.of(COMPLETED, "200"))); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceServiceIT.java index 75e33aea68..6506397645 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/KeyResultPersistenceServiceIT.java @@ -1,6 +1,9 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.http.HttpStatus.*; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -11,18 +14,14 @@ import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; +import java.time.LocalDateTime; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.time.LocalDateTime; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.springframework.http.HttpStatus.*; - @SpringIntegrationTest class KeyResultPersistenceServiceIT { KeyResult createdKeyResult; @@ -30,11 +29,17 @@ class KeyResultPersistenceServiceIT { private KeyResultPersistenceService keyResultPersistenceService; private static KeyResult createKeyResultMetric(Long id) { - return KeyResultMetric.Builder.builder().withBaseline(3.0).withStretchGoal(5.0).withUnit(Unit.FTE).withId(id) - .withTitle("Title").withCreatedBy(User.Builder.builder().withId(1L).build()) - .withOwner(User.Builder.builder().withId(1L).build()) - .withObjective(Objective.Builder.builder().withId(4L).build()).withCreatedOn(LocalDateTime.now()) - .build(); + return KeyResultMetric.Builder.builder() + .withBaseline(3.0) + .withStretchGoal(5.0) + .withUnit(Unit.FTE) + .withId(id) + .withTitle("Title") + .withCreatedBy(User.Builder.builder().withId(1L).build()) + .withOwner(User.Builder.builder().withId(1L).build()) + .withObjective(Objective.Builder.builder().withId(4L).build()) + .withCreatedOn(LocalDateTime.now()) + .build(); } private static KeyResult createKeyResultOrdinal(Long id) { @@ -42,12 +47,18 @@ private static KeyResult createKeyResultOrdinal(Long id) { } private static KeyResult createKeyResultOrdinal(Long id, int version) { - return KeyResultOrdinal.Builder.builder().withCommitZone("Hamster").withTargetZone("Katze") - .withStretchZone("ZOO").withId(id).withVersion(version).withTitle("Ordinal KeyResult") - .withCreatedBy(User.Builder.builder().withId(1L).build()) - .withOwner(User.Builder.builder().withId(1L).build()) - .withObjective(Objective.Builder.builder().withId(4L).build()).withCreatedOn(LocalDateTime.now()) - .build(); + return KeyResultOrdinal.Builder.builder() + .withCommitZone("Hamster") + .withTargetZone("Katze") + .withStretchZone("ZOO") + .withId(id) + .withVersion(version) + .withTitle("Ordinal KeyResult") + .withCreatedBy(User.Builder.builder().withId(1L).build()) + .withOwner(User.Builder.builder().withId(1L).build()) + .withObjective(Objective.Builder.builder().withId(4L).build()) + .withCreatedOn(LocalDateTime.now()) + .build(); } private static final String KEY_RESULT_UPDATED = "Updated Key Result"; @@ -100,7 +111,7 @@ void getKeyResultByIdShouldReturnKeyResultProperly() { @Test void getKeyResultByIdShouldThrowExceptionWhenKeyResultNotFound() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(321L)); + () -> keyResultPersistenceService.findById(321L)); List expectedErrors = List.of(new ErrorDto(MODEL_NOT_FOUND, List.of(KEYRESULT, "321"))); @@ -112,7 +123,7 @@ void getKeyResultByIdShouldThrowExceptionWhenKeyResultNotFound() { @Test void getKeyResultByIdShouldThrowExceptionWhenKeyResultIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(null)); + () -> keyResultPersistenceService.findById(null)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", KEYRESULT))); @@ -129,7 +140,7 @@ void recreateEntityShouldUpdateKeyResultNoTypeChange() { Long keyResultId = createdKeyResult.getId(); KeyResult recreatedKeyResult = keyResultPersistenceService.recreateEntity(createdKeyResult.getId(), - createdKeyResult); + createdKeyResult); assertNotNull(createdKeyResult.getId()); assertEquals(KEY_RESULT_UPDATED, recreatedKeyResult.getTitle()); @@ -138,7 +149,7 @@ void recreateEntityShouldUpdateKeyResultNoTypeChange() { // Should delete the old KeyResult OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(keyResultId)); + () -> keyResultPersistenceService.findById(keyResultId)); List expectedErrors = List.of(ErrorDto.of(MODEL_NOT_FOUND, List.of(KEYRESULT, keyResultId))); @@ -155,14 +166,20 @@ void recreateEntityShouldUpdateKeyResultWithTypeChange() { KeyResult keyResult = createKeyResultMetric(null); createdKeyResult = keyResultPersistenceService.save(keyResult); - KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder().withCommitZone("Hund") - .withTargetZone("Hund + Katze").withStretchZone("Zoo").withId(createdKeyResult.getId()) - .withTitle(KEY_RESULT_UPDATED).withObjective(createdKeyResult.getObjective()) - .withOwner(createdKeyResult.getOwner()).withCreatedBy(createdKeyResult.getCreatedBy()) - .withCreatedOn(createdKeyResult.getCreatedOn()).build(); + KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() + .withCommitZone("Hund") + .withTargetZone("Hund + Katze") + .withStretchZone("Zoo") + .withId(createdKeyResult.getId()) + .withTitle(KEY_RESULT_UPDATED) + .withObjective(createdKeyResult.getObjective()) + .withOwner(createdKeyResult.getOwner()) + .withCreatedBy(createdKeyResult.getCreatedBy()) + .withCreatedOn(createdKeyResult.getCreatedOn()) + .build(); KeyResult recreatedKeyResult = keyResultPersistenceService.recreateEntity(keyResultOrdinal.getId(), - keyResultOrdinal); + keyResultOrdinal); assertNotNull(createdKeyResult.getId()); assertEquals(createdKeyResult.getObjective().getId(), recreatedKeyResult.getObjective().getId()); @@ -172,7 +189,7 @@ void recreateEntityShouldUpdateKeyResultWithTypeChange() { Long keyResultId = createdKeyResult.getId(); // Should delete the old KeyResult OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(keyResultId)); + () -> keyResultPersistenceService.findById(keyResultId)); List expectedErrors = List.of(ErrorDto.of(MODEL_NOT_FOUND, List.of(KEYRESULT, keyResultId))); @@ -212,7 +229,7 @@ void updateEntityShouldThrowExceptionWhenAlreadyUpdated() { updateKeyResult.setDescription(THIS_IS_DESCRIPTION); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.updateEntity(updateKeyResult)); + () -> keyResultPersistenceService.updateEntity(updateKeyResult)); List expectedErrors = List.of(new ErrorDto("DATA_HAS_BEEN_UPDATED", List.of(KEYRESULT))); assertEquals(UNPROCESSABLE_ENTITY, exception.getStatusCode()); @@ -235,7 +252,7 @@ void deleteKeyResultByIdShouldDeleteExistingKeyResult() { Long keyResultId = createdKeyResult.getId(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(keyResultId)); + () -> keyResultPersistenceService.findById(keyResultId)); List expectedErrors = List.of(ErrorDto.of(MODEL_NOT_FOUND, List.of(KEYRESULT, keyResultId))); @@ -252,7 +269,7 @@ void deleteKeyResultShouldThrowExceptionWhenKeyResultNotFound() { Long keyResultId = newKeyResult.getId(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(keyResultId)); + () -> keyResultPersistenceService.findById(keyResultId)); List expectedErrors = List.of(ErrorDto.of(MODEL_NOT_FOUND, List.of(KEYRESULT, keyResultId))); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceServiceIT.java index 9708e9d779..0ffe2459e1 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/ObjectivePersistenceServiceIT.java @@ -1,5 +1,13 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.exception.OkrResponseStatusException.of; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.springframework.http.HttpStatus.BAD_REQUEST; +import static org.springframework.http.HttpStatus.UNAUTHORIZED; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -9,6 +17,8 @@ import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; +import java.util.List; +import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -19,17 +29,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; -import java.util.List; -import java.util.stream.Stream; - -import static ch.puzzle.okr.exception.OkrResponseStatusException.of; -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.junit.jupiter.params.provider.Arguments.arguments; -import static org.springframework.http.HttpStatus.BAD_REQUEST; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; - // tests are using data from V100_0_0__TestData.sql @SpringIntegrationTest class ObjectivePersistenceServiceIT { @@ -79,8 +78,9 @@ void tearDown() { @Test void findObjectiveByIdShouldReturnObjectiveProperly() { // act - var objective = objectivePersistenceService.findObjectiveById(ID_OF_OBJECTIVE_3, authorizationUser, - NO_RESULT_EXCEPTION); + var objective = objectivePersistenceService.findObjectiveById(ID_OF_OBJECTIVE_3, + authorizationUser, + NO_RESULT_EXCEPTION); // assert assertObjective(ID_OF_OBJECTIVE_3, TITLE_OF_OBJECTIVE_3, objective); @@ -90,8 +90,10 @@ void findObjectiveByIdShouldReturnObjectiveProperly() { @Test void findObjectiveByIdShouldThrowExceptionWhenObjectiveNotFound() { // act - var exception = assertThrows(OkrResponseStatusException.class, () -> objectivePersistenceService - .findObjectiveById(INVALID_OBJECTIVE_ID, authorizationUser, NO_RESULT_EXCEPTION)); + var exception = assertThrows(OkrResponseStatusException.class, + () -> objectivePersistenceService.findObjectiveById(INVALID_OBJECTIVE_ID, + authorizationUser, + NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(REASON_UNAUTHORIZED, List.of())); @@ -103,7 +105,9 @@ void findObjectiveByIdShouldThrowExceptionWhenObjectiveNotFound() { void findObjectiveByIdShouldThrowExceptionWhenObjectiveIdIsNull() { // act var exception = assertThrows(OkrResponseStatusException.class, - () -> objectivePersistenceService.findObjectiveById(null, authorizationUser, NO_RESULT_EXCEPTION)); + () -> objectivePersistenceService.findObjectiveById(null, + authorizationUser, + NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(ATTRIBUTE_NULL, List.of("ID", OBJECTIVE))); @@ -114,8 +118,9 @@ void findObjectiveByIdShouldThrowExceptionWhenObjectiveIdIsNull() { @Test void findObjectiveByKeyResultIdShouldReturnObjectiveProperly() { // act - var objective = objectivePersistenceService.findObjectiveByKeyResultId(ID_OF_KEY_RESULT_5, authorizationUser, - NO_RESULT_EXCEPTION); + var objective = objectivePersistenceService.findObjectiveByKeyResultId(ID_OF_KEY_RESULT_5, + authorizationUser, + NO_RESULT_EXCEPTION); // assert assertObjective(ID_OF_OBJECTIVE_3, TITLE_OF_OBJECTIVE_3, objective); @@ -125,8 +130,10 @@ void findObjectiveByKeyResultIdShouldReturnObjectiveProperly() { @Test void findObjectiveByKeyResultIdShouldThrowExceptionWhenObjectiveNotFound() { // act - var exception = assertThrows(OkrResponseStatusException.class, () -> objectivePersistenceService - .findObjectiveByKeyResultId(INVALID_KEY_RESULT_ID, authorizationUser, NO_RESULT_EXCEPTION)); + var exception = assertThrows(OkrResponseStatusException.class, + () -> objectivePersistenceService.findObjectiveByKeyResultId(INVALID_KEY_RESULT_ID, + authorizationUser, + NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(REASON_UNAUTHORIZED, List.of())); @@ -137,8 +144,10 @@ void findObjectiveByKeyResultIdShouldThrowExceptionWhenObjectiveNotFound() { @Test void findObjectiveByKeyResultIdShouldThrowExceptionWhenObjectiveIdIsNull() { // act - var exception = assertThrows(OkrResponseStatusException.class, () -> objectivePersistenceService - .findObjectiveByKeyResultId(null, authorizationUser, NO_RESULT_EXCEPTION)); + var exception = assertThrows(OkrResponseStatusException.class, + () -> objectivePersistenceService.findObjectiveByKeyResultId(null, + authorizationUser, + NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(ATTRIBUTE_NULL, List.of("ID", OBJECTIVE))); @@ -149,8 +158,9 @@ void findObjectiveByKeyResultIdShouldThrowExceptionWhenObjectiveIdIsNull() { @Test void findObjectiveByCheckInIdShouldReturnObjectiveProperly() { // act - var objective = objectivePersistenceService.findObjectiveByCheckInId(ID_OF_CHECK_IN_7, authorizationUser, - NO_RESULT_EXCEPTION); + var objective = objectivePersistenceService.findObjectiveByCheckInId(ID_OF_CHECK_IN_7, + authorizationUser, + NO_RESULT_EXCEPTION); // assert assertObjective(ID_OF_OBJECTIVE_3, TITLE_OF_OBJECTIVE_3, objective); @@ -160,8 +170,10 @@ void findObjectiveByCheckInIdShouldReturnObjectiveProperly() { @Test void findObjectiveByCheckInIdShouldThrowExceptionWhenObjectiveNotFound() { // act - var exception = assertThrows(OkrResponseStatusException.class, () -> objectivePersistenceService - .findObjectiveByCheckInId(INVALID_CHECK_IN_ID, authorizationUser, NO_RESULT_EXCEPTION)); + var exception = assertThrows(OkrResponseStatusException.class, + () -> objectivePersistenceService.findObjectiveByCheckInId(INVALID_CHECK_IN_ID, + authorizationUser, + NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(REASON_UNAUTHORIZED, List.of())); @@ -172,8 +184,10 @@ void findObjectiveByCheckInIdShouldThrowExceptionWhenObjectiveNotFound() { @Test void findObjectiveByCheckInIdShouldThrowExceptionWhenObjectiveIdIsNull() { // act - var exception = assertThrows(OkrResponseStatusException.class, () -> objectivePersistenceService - .findObjectiveByCheckInId(null, authorizationUser, ObjectivePersistenceServiceIT.NO_RESULT_EXCEPTION)); + var exception = assertThrows(OkrResponseStatusException.class, + () -> objectivePersistenceService.findObjectiveByCheckInId(null, + authorizationUser, + ObjectivePersistenceServiceIT.NO_RESULT_EXCEPTION)); // assert var expectedErrors = List.of(new ErrorDto(ATTRIBUTE_NULL, List.of("ID", OBJECTIVE))); @@ -216,7 +230,8 @@ void findObjectiveByTeamIdShouldReturnEmptyListWhenObjectiveIdIsNull() { @DisplayName("countByTeamAndQuarter() should return number of objectives for current quarter") @Test void countByTeamAndQuarterShouldReturnNumberOfObjectivesForCurrentQuarter() { - // arrange: there are 3 objectives for the current quarter (id 2) for team with id 6 + // arrange: there are 3 objectives for the current quarter (id 2) for team with + // id 6 var team = Team.Builder.builder().withId(ID_OF_TEAM_6).build(); var quarter = Quarter.Builder.builder().withId(CURRENT_QUARTER_ID).build(); @@ -245,18 +260,18 @@ private static Stream invalidTeamsAndQuarters() { var invalidQuarter = Quarter.Builder.builder().withId(INVALID_QUARTER_ID).build(); return Stream.of( - // valid team + invalid quarter - arguments(validTeam, invalidQuarter), - // valid team + null quarter - arguments(validTeam, null), - // invalid team + valid quarter - arguments(invalidTeam, validQuarter), - // invalid team + null quarter - arguments(null, validQuarter), - // invalid team + invalid quarter - arguments(invalidTeam, invalidQuarter), - // null team + null quarter - arguments(null, null)); + // valid team + invalid quarter + arguments(validTeam, invalidQuarter), + // valid team + null quarter + arguments(validTeam, null), + // invalid team + valid quarter + arguments(invalidTeam, validQuarter), + // invalid team + null quarter + arguments(null, validQuarter), + // invalid team + invalid quarter + arguments(invalidTeam, invalidQuarter), + // null team + null quarter + arguments(null, null)); } @DisplayName("getModelName() should return Objective") @@ -266,7 +281,7 @@ void getModelNameShouldReturnObjective() { } private void assertResponseStatusException(HttpStatus expectedStatus, List expectedErrors, - OkrResponseStatusException currentException) { + OkrResponseStatusException currentException) { assertEquals(expectedStatus, currentException.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(currentException.getErrors()); assertTrue(TestHelper.getAllErrorKeys(expectedErrors).contains(currentException.getReason())); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/OverviewPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/OverviewPersistenceServiceIT.java index fb74abd66e..e72b84f677 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/OverviewPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/OverviewPersistenceServiceIT.java @@ -1,46 +1,45 @@ package ch.puzzle.okr.service.persistence; -import ch.puzzle.okr.test.TestHelper; +import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; + import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.overview.Overview; import ch.puzzle.okr.models.overview.OverviewId; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import ch.puzzle.okr.test.TestHelper; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.defaultAuthorizationUser; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; - @SpringIntegrationTest class OverviewPersistenceServiceIT { private static final List expectedOverviewIds = List.of( // index: - OverviewId.of(4L, 5L, 9L, 15L), // 0 - OverviewId.of(4L, 5L, 10L, 14L), // 1 - OverviewId.of(4L, 6L, 12L, 12L), // 2 - OverviewId.of(4L, 6L, 13L, 11L), // 3 - OverviewId.of(4L, 6L, 14L, 10L), // 4 - OverviewId.of(5L, 3L, 3L, 9L), // 5 - OverviewId.of(5L, 3L, 4L, 8L), // 6 - OverviewId.of(5L, 3L, 5L, 7L), // 7 - OverviewId.of(5L, 4L, 6L, 5L), // 8 - OverviewId.of(5L, 4L, 7L, 4L), // 9 - OverviewId.of(5L, 4L, 8L, 2L), // 10 - OverviewId.of(6L, 8L, 18L, 20L), // 11 - OverviewId.of(6L, 8L, 19L, 19L), // 12 - OverviewId.of(6L, 9L, 15L, 18L), // 13 - OverviewId.of(6L, 9L, 16L, 17L), // 14 - OverviewId.of(6L, 9L, 17L, 16L), // 15 - OverviewId.of(6L, 10L, -1L, -1L), // 16 - OverviewId.of(8L, -1L, -1L, -1L), // 17 - OverviewId.of(5L, -1L, -1L, -1L), // 18 - OverviewId.of(6L, -1L, -1L, -1L), // 19 - OverviewId.of(4L, -1L, -1L, -1L)); // 20 + OverviewId.of(4L, 5L, 9L, 15L), // 0 + OverviewId.of(4L, 5L, 10L, 14L), // 1 + OverviewId.of(4L, 6L, 12L, 12L), // 2 + OverviewId.of(4L, 6L, 13L, 11L), // 3 + OverviewId.of(4L, 6L, 14L, 10L), // 4 + OverviewId.of(5L, 3L, 3L, 9L), // 5 + OverviewId.of(5L, 3L, 4L, 8L), // 6 + OverviewId.of(5L, 3L, 5L, 7L), // 7 + OverviewId.of(5L, 4L, 6L, 5L), // 8 + OverviewId.of(5L, 4L, 7L, 4L), // 9 + OverviewId.of(5L, 4L, 8L, 2L), // 10 + OverviewId.of(6L, 8L, 18L, 20L), // 11 + OverviewId.of(6L, 8L, 19L, 19L), // 12 + OverviewId.of(6L, 9L, 15L, 18L), // 13 + OverviewId.of(6L, 9L, 16L, 17L), // 14 + OverviewId.of(6L, 9L, 17L, 16L), // 15 + OverviewId.of(6L, 10L, -1L, -1L), // 16 + OverviewId.of(8L, -1L, -1L, -1L), // 17 + OverviewId.of(5L, -1L, -1L, -1L), // 18 + OverviewId.of(6L, -1L, -1L, -1L), // 19 + OverviewId.of(4L, -1L, -1L, -1L)); // 20 private final AuthorizationUser authorizationUser = defaultAuthorizationUser(); @Autowired @@ -58,8 +57,10 @@ void tearDown() { @Test void getFilteredOverviewShouldReturnOverviewsWhenTeamIdsSet() { - List overviews = overviewPersistenceService.getFilteredOverview(2L, List.of(5L, 6L, 8L), "", - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(2L, + List.of(5L, 6L, 8L), + "", + authorizationUser); assertThat(expectedOverviewIds.subList(5, 18)).hasSameElementsAs(getOverviewIds(overviews)); } @@ -73,24 +74,30 @@ void getFilteredOverviewShouldReturnOverviewsWhenTeamIdsEmpty() { @Test void getFilteredOverviewShouldReturnOverviewsWhenObjectiveQuery() { - List overviews = overviewPersistenceService.getFilteredOverview(2L, List.of(5L, 6L, 8L), - "kundenzufriedenheit", authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(2L, + List.of(5L, 6L, 8L), + "kundenzufriedenheit", + authorizationUser); assertThat(expectedOverviewIds.subList(5, 8)).hasSameElementsAs(getOverviewIds(overviews)); } @Test void getFilteredOverviewShouldReturnOverviewsWhenQuarterWithoutObjectives() { - List overviews = overviewPersistenceService.getFilteredOverview(3L, List.of(5L, 6L, 8L), null, - authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(3L, + List.of(5L, 6L, 8L), + null, + authorizationUser); assertThat(expectedOverviewIds.subList(17, 20)).hasSameElementsAs(getOverviewIds(overviews)); } @Test void getFilteredOverviewShouldReturnOverviewsWhenQuarterWithoutObjectivesAndObjectiveQuery() { - List overviews = overviewPersistenceService.getFilteredOverview(3L, List.of(5L, 6L, 8L), - "kundenzufriedenheit", authorizationUser); + List overviews = overviewPersistenceService.getFilteredOverview(3L, + List.of(5L, 6L, 8L), + "kundenzufriedenheit", + authorizationUser); assertTrue(overviews.isEmpty()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/PersistenceBaseTestIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/PersistenceBaseTestIT.java index 7f5a60a5e5..1d8647c40b 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/PersistenceBaseTestIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/PersistenceBaseTestIT.java @@ -1,10 +1,19 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.test.TestHelper.getAllErrorKeys; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.http.HttpStatus.*; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.repository.UserRepository; import ch.puzzle.okr.test.SpringIntegrationTest; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -13,19 +22,9 @@ import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static ch.puzzle.okr.test.TestHelper.getAllErrorKeys; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.springframework.http.HttpStatus.*; - /** - * Testing the functionality of the abstract PersistenceBase and use UserRepository as example of a CrudRepository - * implementation. + * Testing the functionality of the abstract PersistenceBase and use + * UserRepository as example of a CrudRepository implementation. *

* Tests depending on data from V100_0_0__TestData.sql */ @@ -37,10 +36,10 @@ public class PersistenceBaseTestIT { private static final long NON_EXISTING_USER_ID = 321L; private static final long USER_PACO_ID = 1L; private static final User USER_WITHOUT_CONSTRAINTS = User.Builder.builder() // - .withFirstname("Hans") // - .withLastname("Muster") // - .withEmail("hans.muster@puzzle.ch") // - .build(); + .withFirstname("Hans") // + .withLastname("Muster") // + .withEmail("hans.muster@puzzle.ch") // + .build(); @Autowired private PersistenceBase persistenceBase; @@ -72,7 +71,7 @@ void findByIdShouldReturnSingleEntityIfEntityWithIdExists() { @Test void findByIdShouldThrowExceptionIfEntityWithIdDoesNotExist() { var exception = assertThrows(ResponseStatusException.class, - () -> persistenceBase.findById(NON_EXISTING_USER_ID)); + () -> persistenceBase.findById(NON_EXISTING_USER_ID)); assertEquals(NOT_FOUND, exception.getStatusCode()); assertErrorKey("MODEL_WITH_ID_NOT_FOUND", exception); @@ -163,7 +162,7 @@ void deleteByIdShouldDeleteEntity() throws ResponseStatusException { } private static void assertUser(String expectedFirstName, String expectedLastName, String expectedEmail, - User currentUser) { + User currentUser) { assertEquals(expectedFirstName, currentUser.getFirstname()); assertEquals(expectedLastName, currentUser.getLastname()); assertEquals(expectedEmail, currentUser.getEmail()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/QuarterPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/QuarterPersistenceServiceIT.java index 1eee877cc1..9a7c1e7a00 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/QuarterPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/QuarterPersistenceServiceIT.java @@ -1,24 +1,23 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.QUARTER; +import static ch.puzzle.okr.test.TestConstants.GJ_FOR_TESTS_QUARTER_ID; +import static ch.puzzle.okr.test.TestConstants.GJ_FOR_TEST_QUARTER_LABEL; +import static org.junit.jupiter.api.Assertions.*; + import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; import ch.puzzle.okr.util.quarter.check.QuarterRangeChecker; +import java.time.LocalDate; +import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.time.LocalDate; -import java.util.List; - -import static ch.puzzle.okr.Constants.QUARTER; -import static ch.puzzle.okr.test.TestConstants.GJ_FOR_TESTS_QUARTER_ID; -import static ch.puzzle.okr.test.TestConstants.GJ_FOR_TEST_QUARTER_LABEL; -import static org.junit.jupiter.api.Assertions.*; - @SpringIntegrationTest class QuarterPersistenceServiceIT { @@ -47,13 +46,17 @@ void getMostCurrentQuartersShouldReturnCurrentQuarterAndFutureQuarterAndGJForTes private void assertGJForTestsQuarterIsFoundOnce(List quarters) { long foundGJForTestsQuartersCount = quarters.stream() - .filter(quarter -> quarter.getLabel().equals(GJ_FOR_TEST_QUARTER_LABEL)).count(); + .filter(quarter -> quarter.getLabel() + .equals(GJ_FOR_TEST_QUARTER_LABEL)) + .count(); assertEquals(1, foundGJForTestsQuartersCount); } private void assertCurrentQuarterIsFoundOnce(List quarters) { long foundCurrentQuartersCount = quarters.stream() - .filter(quarter -> QuarterRangeChecker.nowIsInQuarter(LocalDate.now(), quarter)).count(); + .filter(quarter -> QuarterRangeChecker.nowIsInQuarter(LocalDate.now(), + quarter)) + .count(); assertEquals(1, foundCurrentQuartersCount); } @@ -62,10 +65,10 @@ void shouldReturnCurrentQuarter() { Quarter quarter = quarterPersistenceService.getCurrentQuarter(); assertTrue(LocalDate.now().isEqual(quarter.getStartDate()) || // - LocalDate.now().isAfter(quarter.getStartDate())); + LocalDate.now().isAfter(quarter.getStartDate())); assertTrue(LocalDate.now().isEqual(quarter.getEndDate()) || // - LocalDate.now().isBefore(quarter.getEndDate())); + LocalDate.now().isBefore(quarter.getEndDate())); assertNotNull(quarter.getId()); assertNotNull(quarter.getLabel()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/TeamPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/TeamPersistenceServiceIT.java index f37812cb21..74f2e0f50f 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/TeamPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/TeamPersistenceServiceIT.java @@ -1,19 +1,18 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.TEAM; +import static org.junit.jupiter.api.Assertions.assertEquals; + import ch.puzzle.okr.models.Team; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import java.util.List; - -import static ch.puzzle.okr.Constants.TEAM; -import static org.junit.jupiter.api.Assertions.assertEquals; - @SpringIntegrationTest class TeamPersistenceServiceIT { diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/UserPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/UserPersistenceServiceIT.java index aab5435654..5ec083c632 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/UserPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/UserPersistenceServiceIT.java @@ -1,9 +1,15 @@ package ch.puzzle.okr.service.persistence; +import static ch.puzzle.okr.Constants.USER; +import static ch.puzzle.okr.util.CollectionUtils.iterableToList; +import static org.junit.jupiter.api.Assertions.*; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; +import java.util.List; +import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -12,13 +18,6 @@ import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.http.HttpStatus; -import java.util.List; -import java.util.Optional; - -import static ch.puzzle.okr.Constants.USER; -import static ch.puzzle.okr.util.CollectionUtils.iterableToList; -import static org.junit.jupiter.api.Assertions.*; - @SpringIntegrationTest class UserPersistenceServiceIT { @@ -46,10 +45,11 @@ void tearDown() { void saveShouldSaveUserWithEmptyUserTeamList() { // arrange var newUser = User.Builder.builder() // - .withFirstname("Hans") // - .withLastname("Muster") // - .withEmail("muster@puzzle.ch") // - .withUserTeamList(List.of()).build(); + .withFirstname("Hans") // + .withLastname("Muster") // + .withEmail("muster@puzzle.ch") // + .withUserTeamList(List.of()) + .build(); // act createdUser = userPersistenceService.save(newUser); @@ -64,10 +64,11 @@ void saveShouldSaveUserWithEmptyUserTeamList() { void saveShouldSaveUserWithNullUserTeamList() { // arrange var newUser = User.Builder.builder() // - .withFirstname("Hans") // - .withLastname("Muster") // - .withEmail("muster@puzzle.ch") // - .withUserTeamList(null).build(); + .withFirstname("Hans") // + .withLastname("Muster") // + .withEmail("muster@puzzle.ch") // + .withUserTeamList(null) + .build(); // act createdUser = userPersistenceService.save(newUser); @@ -82,10 +83,10 @@ void saveShouldSaveUserWithNullUserTeamList() { void saveAllShouldSaveAllUsersInTheInputList() { // arrange var newUser = User.Builder.builder() // - .withFirstname("Hans") // - .withLastname("Muster") // - .withEmail("muster@puzzle.ch") // - .build(); + .withFirstname("Hans") // + .withLastname("Muster") // + .withEmail("muster@puzzle.ch") // + .build(); // act var createdUsers = iterableToList(userPersistenceService.saveAll(List.of(newUser))); @@ -116,11 +117,11 @@ void getOrCreateUserShouldReturnSingleUserWhenUserFound() { void getOrCreateUserShouldReturnSavedUserWhenUserNotFound() { // arrange var newUser = User.Builder.builder() // - .withId(null) // - .withFirstname("firstname") // - .withLastname("lastname") // - .withEmail("lastname@puzzle.ch") // - .build(); + .withId(null) // + .withFirstname("firstname") // + .withLastname("lastname") // + .withEmail("lastname@puzzle.ch") // + .build(); // act createdUser = userPersistenceService.getOrCreateUser(newUser); @@ -193,18 +194,18 @@ void deleteByIdShouldDeleteUserWhenUserFound() { // assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, // - () -> userPersistenceService.findById(createdUser.getId())); + () -> userPersistenceService.findById(createdUser.getId())); assertEquals(HttpStatus.NOT_FOUND, exception.getStatusCode()); } private User createUser() { User newUser = User.Builder.builder() // - .withId(null) // - .withFirstname("firstname") // - .withLastname("lastname") // - .withEmail("lastname@puzzle.ch") // - .build(); + .withId(null) // + .withFirstname("firstname") // + .withLastname("lastname") // + .withEmail("lastname@puzzle.ch") // + .build(); createdUser = userPersistenceService.getOrCreateUser(newUser); assertNotNull(createdUser.getId()); return createdUser; @@ -214,7 +215,7 @@ private User createUser() { @Test void deleteByIdShouldThrowExceptionWhenIdIsNull() { InvalidDataAccessApiUsageException exception = assertThrows(InvalidDataAccessApiUsageException.class, // - () -> userPersistenceService.deleteById(null)); + () -> userPersistenceService.deleteById(null)); assertEquals("The given id must not be null", exception.getMessage()); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceServiceIT.java b/backend/src/test/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceServiceIT.java index cc2dfe71b8..7b11855395 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceServiceIT.java +++ b/backend/src/test/java/ch/puzzle/okr/service/persistence/UserTeamPersistenceServiceIT.java @@ -3,14 +3,13 @@ import ch.puzzle.okr.multitenancy.TenantContext; import ch.puzzle.okr.test.SpringIntegrationTest; import ch.puzzle.okr.test.TestHelper; +import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; -import java.util.List; - // uses test date from V100_0_0__TestData.sql @SpringIntegrationTest public class UserTeamPersistenceServiceIT { diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/ActionValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/ActionValidationServiceTest.java index 1521f05a33..f6122d5d2c 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/ActionValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/ActionValidationServiceTest.java @@ -1,11 +1,20 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.*; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Action; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.persistence.ActionPersistenceService; +import java.util.List; +import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -20,34 +29,28 @@ import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.List; -import java.util.stream.Stream; - -import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; -import static org.junit.jupiter.api.Assertions.*; -import static org.junit.jupiter.params.provider.Arguments.arguments; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.*; -import static org.springframework.http.HttpStatus.BAD_REQUEST; - @ExtendWith(MockitoExtension.class) class ActionValidationServiceTest { private final KeyResult keyResult = KeyResultMetric.Builder.builder() // - .withId(10L) // - .withTitle("KR Title").build(); // + .withId(10L) // + .withTitle("KR Title") + .build(); // private final Action action1 = Action.Builder.builder() // - .withId(null) // - .withAction("Neue Katze") // - .withIsChecked(false) // - .withPriority(0) // - .withKeyResult(keyResult).build(); + .withId(null) // + .withAction("Neue Katze") // + .withIsChecked(false) // + .withPriority(0) // + .withKeyResult(keyResult) + .build(); private final Action action2 = Action.Builder.builder() // - .withId(2L) // - .withAction("Neues Lama") // - .withIsChecked(true) // // - .withPriority(1).withKeyResult(keyResult).build(); + .withId(2L) // + .withAction("Neues Lama") // + .withIsChecked(true) // // + .withPriority(1) + .withKeyResult(keyResult) + .build(); @Mock ActionPersistenceService actionPersistenceService; @@ -60,10 +63,10 @@ class ActionValidationServiceTest { private ActionValidationService validator; private static Stream actionValidationArguments() { - return Stream.of( - arguments(StringUtils.repeat('1', 5000), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("action", "Action", "0", "4096")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action"))))); + return Stream.of(arguments(StringUtils.repeat('1', 5000), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("action", "Action", "0", "4096")))), + arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action"))))); } private record ActionPair(Action action, Action saveAction) { @@ -75,32 +78,56 @@ private static Stream actionPairArgument() { KeyResult keyResult = KeyResultMetric.Builder.builder().withId(10L).withTitle("KR Title").build(); // return Stream.of( // - Arguments.of(new ActionPair( // - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) // - .withKeyResult(null).build(), - - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) // - .withKeyResult(null).build())), - - Arguments.of(new ActionPair( // - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) // - .withKeyResult(keyResult).build(), - - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) // - .withKeyResult(null).build())), - - Arguments.of(new ActionPair( // - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) // - .withKeyResult(null).build(), - - Action.Builder.builder() // - .withId(id).withAction("Action").withIsChecked(false).withPriority(1) - .withKeyResult(keyResult).build()))); + Arguments.of(new ActionPair( // + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) // + .withKeyResult(null) + .build(), + + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) // + .withKeyResult(null) + .build())), + + Arguments.of(new ActionPair( // + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) // + .withKeyResult(keyResult) + .build(), + + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) // + .withKeyResult(null) + .build())), + + Arguments.of(new ActionPair( // + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) // + .withKeyResult(null) + .build(), + + Action.Builder.builder() // + .withId(id) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) + .withKeyResult(keyResult) + .build()))); } @BeforeEach @@ -120,11 +147,11 @@ void validateOnCreateShouldBeSuccessfulWhenActionIsValid() { void validateOnCreateShouldThrowExceptionWhenModelIsNull() { // arrange OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); // act + assert List expectedErrors = List.of( // - new ErrorDto("MODEL_NULL", List.of("Action"))); + new ErrorDto("MODEL_NULL", List.of("Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -132,11 +159,11 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { // arrange OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(action2)); + () -> validator.validateOnCreate(action2)); // act + assert List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Action"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -144,12 +171,17 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { @MethodSource("actionValidationArguments") void validateOnCreateShouldThrowExceptionWhenActionIsInvalid(String actionText, List errors) { // arrange - Action action = Action.Builder.builder().withId(null).withAction(actionText).withIsChecked(false) - .withPriority(1).withKeyResult(keyResult).build(); + Action action = Action.Builder.builder() + .withId(null) + .withAction(actionText) + .withIsChecked(false) + .withPriority(1) + .withKeyResult(keyResult) + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(action)); + () -> validator.validateOnCreate(action)); assertOkrResponseStatusException(exception, errors); } @@ -161,11 +193,11 @@ void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(actionInvalid)); + () -> validator.validateOnCreate(actionInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("keyResult", "Action"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("keyResult", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -190,11 +222,11 @@ void validateOnUpdateShouldBeSuccessfulWhenActionIsValid() { void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { // arrange OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, null)); + () -> validator.validateOnUpdate(1L, null)); // act + assert List expectedErrors = List.of( // - new ErrorDto("MODEL_NULL", List.of("Action"))); + new ErrorDto("MODEL_NULL", List.of("Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -202,13 +234,13 @@ void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, action1)); + () -> validator.validateOnUpdate(null, action1)); verify(validator, times(1)).throwExceptionWhenModelIsNull(action1); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Action"))); + new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -216,14 +248,14 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, action2)); + () -> validator.validateOnUpdate(1L, action2)); verify(validator, times(1)).throwExceptionWhenModelIsNull(action2); verify(validator, times(1)).throwExceptionWhenIdIsNull(action2.getId()); verify(validator, times(1)).throwExceptionWhenIdHasChanged(1L, action2.getId()); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_CHANGED", List.of("ID", "1", "2"))); + new ErrorDto("ATTRIBUTE_CHANGED", List.of("ID", "1", "2"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -231,12 +263,12 @@ void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { void validateOnUpdateShouldThrowExceptionWhenEntityDoesNotExist() { // arrange String reason = "MODEL_WITH_ID_NOT_FOUND"; - when(actionPersistenceService.findById(anyLong())) - .thenThrow(new OkrResponseStatusException(BAD_REQUEST, reason)); + when(actionPersistenceService.findById(anyLong())).thenThrow(new OkrResponseStatusException(BAD_REQUEST, + reason)); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(action2.getId(), action2)); + () -> validator.validateOnUpdate(action2.getId(), action2)); verify(validator, times(1)).throwExceptionWhenModelIsNull(action2); verify(validator, times(1)).throwExceptionWhenIdIsNull(action2.getId()); @@ -259,35 +291,43 @@ void validateOnUpdateShouldThrowExceptionWhenKeyResultNotSet(ActionPair actionPa // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(id, action)); + () -> validator.validateOnUpdate(id, action)); verify(validator, times(1)).throwExceptionWhenModelIsNull(action); verify(validator, times(1)).throwExceptionWhenIdIsNull(action.getId()); verify(validator, times(1)).throwExceptionWhenIdHasChanged(id, action.getId()); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("KeyResult", "Action"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("KeyResult", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @Test void validateOnUpdateShouldThrowExceptionWhenKeyResultIdHasChanged() { // arrange - Action action = Action.Builder.builder().withId(action2.getId()).withAction("Action").withIsChecked(false) - .withPriority(1) - .withKeyResult(KeyResultMetric.Builder.builder().withId(11L).withTitle("KR Title").build()).build(); + Action action = Action.Builder.builder() + .withId(action2.getId()) + .withAction("Action") + .withIsChecked(false) + .withPriority(1) + .withKeyResult(KeyResultMetric.Builder.builder() + .withId(11L) + .withTitle("KR Title") + .build()) + .build(); when(actionPersistenceService.findById(anyLong())).thenReturn(action2); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(action.getId(), action)); + () -> validator.validateOnUpdate(action.getId(), action)); verify(validator, times(1)).throwExceptionWhenModelIsNull(action); verify(validator, times(1)).throwExceptionWhenIdIsNull(action.getId()); verify(validator, times(1)).throwExceptionWhenIdHasChanged(action.getId(), action2.getId()); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", List.of("KeyResult", "Action"))); + new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", + List.of("KeyResult", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -295,13 +335,18 @@ void validateOnUpdateShouldThrowExceptionWhenKeyResultIdHasChanged() { @MethodSource("actionValidationArguments") void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String actionText, List errors) { // arrange - Action action = Action.Builder.builder().withId(3L).withAction(actionText).withIsChecked(false).withPriority(1) - .withKeyResult(keyResult).build(); + Action action = Action.Builder.builder() + .withId(3L) + .withAction(actionText) + .withIsChecked(false) + .withPriority(1) + .withKeyResult(keyResult) + .build(); when(actionPersistenceService.findById(anyLong())).thenReturn(action); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, action)); + () -> validator.validateOnUpdate(3L, action)); assertOkrResponseStatusException(exception, errors); } @@ -313,26 +358,29 @@ void validateOnUpdateShouldThrowExceptionWhenKeyResultIsMissing() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(11L, actionInvalid)); + () -> validator.validateOnUpdate(11L, actionInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("KeyResult", "Action"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("KeyResult", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @Test void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { // arrange - Action actionInvalid = Action.Builder.builder().withId(11L).withIsChecked(true).withKeyResult(keyResult) - .build(); + Action actionInvalid = Action.Builder.builder() + .withId(11L) + .withIsChecked(true) + .withKeyResult(keyResult) + .build(); when(actionPersistenceService.findById(anyLong())).thenReturn(actionInvalid); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(11L, actionInvalid)); + () -> validator.validateOnUpdate(11L, actionInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/CheckInValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/CheckInValidationServiceTest.java index b4a1801da5..d5c2d5780c 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/CheckInValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/CheckInValidationServiceTest.java @@ -1,5 +1,10 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.*; @@ -11,6 +16,9 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.persistence.CheckInPersistenceService; +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -23,54 +31,91 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.mock.mockito.MockBean; -import java.time.LocalDateTime; -import java.util.List; -import java.util.stream.Stream; - -import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.params.provider.Arguments.arguments; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class CheckInValidationServiceTest { @MockBean CheckInPersistenceService checkInPersistenceService = Mockito.mock(CheckInPersistenceService.class); - private final User user = User.Builder.builder().withId(1L).withFirstname("Ruedi").withLastname("Grochde") - .withEmail("grochde@puzzle.ch").build(); + private final User user = User.Builder.builder() + .withId(1L) + .withFirstname("Ruedi") + .withLastname("Grochde") + .withEmail("grochde@puzzle.ch") + .build(); private final Team team = Team.Builder.builder().withId(1L).withName("Team4").build(); private final Quarter quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build(); - private final Objective objective = Objective.Builder.builder().withId(1L).withTitle("Objective 1") - .withCreatedBy(user).withTeam(team).withQuarter(quarter).withDescription("This is our description") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withModifiedBy(user) - .withCreatedOn(LocalDateTime.MAX).build(); - private final KeyResult keyResultMetric = KeyResultMetric.Builder.builder().withBaseline(13D).withStretchGoal(25D) - .withUnit(Unit.NUMBER).withId(8L).withTitle("Keyresult Metric").withObjective(objective).withOwner(user) - .build(); - private final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder().withCommitZone("Commit Zone") - .withTargetZone("Target Zone").withTitle("Keyresult Ordinal").withObjective(objective).withOwner(user) - .build(); - private final CheckIn checkInMetric = CheckInMetric.Builder.builder().withValue(45D).withChangeInfo("ChangeInfo") - .withInitiatives("Initiatives").withConfidence(10).withKeyResult(keyResultMetric) - .withCreatedOn(LocalDateTime.MAX).withModifiedOn(LocalDateTime.MAX).withCreatedBy(user).build(); - private final CheckIn checkInOrdinal = CheckInMetric.Builder.builder().withValue(27D).withId(1L) - .withChangeInfo("ChangeInfoMetric").withInitiatives("InitiativesMetric").withConfidence(8) - .withKeyResult(keyResultOrdinal).withCreatedOn(LocalDateTime.MAX).withModifiedOn(LocalDateTime.MAX) - .withCreatedBy(user).build(); - private final CheckIn fullCheckIn = CheckInOrdinal.Builder.builder().withZone(Zone.STRETCH).withId(1L) - .withChangeInfo("ChangeInfoMetric").withInitiatives("InitiativesMetric").withConfidence(8) - .withKeyResult(keyResultMetric).withCreatedOn(LocalDateTime.MAX).withModifiedOn(LocalDateTime.MAX) - .withCreatedBy(user).build(); + private final Objective objective = Objective.Builder.builder() + .withId(1L) + .withTitle("Objective 1") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withDescription("This is our description") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withModifiedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .build(); + private final KeyResult keyResultMetric = KeyResultMetric.Builder.builder() + .withBaseline(13D) + .withStretchGoal(25D) + .withUnit(Unit.NUMBER) + .withId(8L) + .withTitle("Keyresult Metric") + .withObjective(objective) + .withOwner(user) + .build(); + private final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() + .withCommitZone("Commit Zone") + .withTargetZone("Target Zone") + .withTitle("Keyresult Ordinal") + .withObjective(objective) + .withOwner(user) + .build(); + private final CheckIn checkInMetric = CheckInMetric.Builder.builder() + .withValue(45D) + .withChangeInfo("ChangeInfo") + .withInitiatives("Initiatives") + .withConfidence(10) + .withKeyResult(keyResultMetric) + .withCreatedOn(LocalDateTime.MAX) + .withModifiedOn(LocalDateTime.MAX) + .withCreatedBy(user) + .build(); + private final CheckIn checkInOrdinal = CheckInMetric.Builder.builder() + .withValue(27D) + .withId(1L) + .withChangeInfo("ChangeInfoMetric") + .withInitiatives("InitiativesMetric") + .withConfidence(8) + .withKeyResult(keyResultOrdinal) + .withCreatedOn(LocalDateTime.MAX) + .withModifiedOn(LocalDateTime.MAX) + .withCreatedBy(user) + .build(); + private final CheckIn fullCheckIn = CheckInOrdinal.Builder.builder() + .withZone(Zone.STRETCH) + .withId(1L) + .withChangeInfo("ChangeInfoMetric") + .withInitiatives("InitiativesMetric") + .withConfidence(8) + .withKeyResult(keyResultMetric) + .withCreatedOn(LocalDateTime.MAX) + .withModifiedOn(LocalDateTime.MAX) + .withCreatedBy(user) + .build(); @Spy @InjectMocks private CheckInValidationService validator; private static Stream confidenceValidationArguments() { - return Stream.of( - arguments(-1, List.of(new ErrorDto("ATTRIBUTE_MIN_VALUE", List.of("confidence", "CheckIn", "0")))), - arguments(11, List.of(new ErrorDto("ATTRIBUTE_MAX_VALUE", List.of("confidence", "CheckIn", "10")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn"))))); + return Stream.of(arguments(-1, + List.of(new ErrorDto("ATTRIBUTE_MIN_VALUE", List.of("confidence", "CheckIn", "0")))), + arguments(11, + List.of(new ErrorDto("ATTRIBUTE_MAX_VALUE", + List.of("confidence", "CheckIn", "10")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn"))))); } @BeforeEach @@ -88,7 +133,7 @@ void validateOnGetShouldBeSuccessfulWhenValidCheckInId() { void validateOnGetShouldThrowExceptionIfCheckInIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -111,7 +156,7 @@ void validateOnCreateShouldBeSuccessfulWhenCheckInIsValid() { void validateOnCreateShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("CheckIn"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -121,7 +166,7 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(fullCheckIn)); + () -> validator.validateOnCreate(fullCheckIn)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "CheckIn"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -130,23 +175,23 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { @ParameterizedTest @MethodSource("confidenceValidationArguments") void validateOnCreateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confidence, - List expectedErrors) { + List expectedErrors) { // arrange CheckIn checkIn = CheckInMetric.Builder.builder() // - .withValue(40.9) // - .withChangeInfo("ChangeInfo") // - .withInitiatives("Initiatives") // - .withConfidence(confidence) // - .withCreatedBy(user) // - .withKeyResult(keyResultMetric) // - .withCreatedOn(LocalDateTime.MAX) // - .withModifiedOn(LocalDateTime.MAX) // - .build(); + .withValue(40.9) // + .withChangeInfo("ChangeInfo") // + .withInitiatives("Initiatives") // + .withConfidence(confidence) // + .withCreatedBy(user) // + .withKeyResult(keyResultMetric) // + .withCreatedOn(LocalDateTime.MAX) // + .withModifiedOn(LocalDateTime.MAX) // + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(checkIn)); + () -> validator.validateOnCreate(checkIn)); assertOkrResponseStatusException(exception, expectedErrors); } @@ -154,19 +199,20 @@ void validateOnCreateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confide void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { // arrange CheckIn checkInInvalid = CheckInMetric.Builder.builder() // - .withId(null) // - .withChangeInfo("ChangeInfo").build(); + .withId(null) // + .withChangeInfo("ChangeInfo") + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(checkInInvalid)); + () -> validator.validateOnCreate(checkInInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("keyResult", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("valueMetric", "CheckIn"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("keyResult", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("valueMetric", "CheckIn"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -186,7 +232,7 @@ void validateOnUpdateShouldBeSuccessfulWhenCheckInIsValid() { void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, null)); + () -> validator.validateOnUpdate(1L, null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("CheckIn"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -196,7 +242,7 @@ void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, checkInOrdinal)); + () -> validator.validateOnUpdate(null, checkInOrdinal)); verify(validator, times(1)).throwExceptionWhenModelIsNull(checkInOrdinal); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -209,7 +255,7 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdIsHasChanged() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(2L, checkInOrdinal)); + () -> validator.validateOnUpdate(2L, checkInOrdinal)); verify(validator, times(1)).throwExceptionWhenModelIsNull(checkInOrdinal); verify(validator, times(1)).throwExceptionWhenIdIsNull(2L); @@ -222,19 +268,26 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsHasChanged() { @ParameterizedTest @MethodSource("confidenceValidationArguments") void validateOnUpdateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confidence, - List expectedErrors) { + List expectedErrors) { // arrange Long id = 2L; - CheckIn checkIn = CheckInMetric.Builder.builder().withValue(40.9).withId(id).withChangeInfo("ChangeInfo") - .withInitiatives("Initiatives").withConfidence(confidence).withCreatedBy(user) - .withKeyResult(keyResultMetric).withCreatedOn(LocalDateTime.MAX).withModifiedOn(LocalDateTime.MAX) - .build(); + CheckIn checkIn = CheckInMetric.Builder.builder() + .withValue(40.9) + .withId(id) + .withChangeInfo("ChangeInfo") + .withInitiatives("Initiatives") + .withConfidence(confidence) + .withCreatedBy(user) + .withKeyResult(keyResultMetric) + .withCreatedOn(LocalDateTime.MAX) + .withModifiedOn(LocalDateTime.MAX) + .build(); when(checkInPersistenceService.findById(id)).thenReturn(checkIn); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(id, checkIn)); + () -> validator.validateOnUpdate(id, checkIn)); assertOkrResponseStatusException(exception, expectedErrors); } @@ -242,24 +295,38 @@ void validateOnUpdateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confide void validateOnUpdateShouldThrowExceptionWhenCheckInsOfKeyResultIsEmpty() { // arrange Long id = 2L; - CheckIn checkIn = CheckInMetric.Builder.builder().withValue(40.9).withId(id).withChangeInfo("ChangeInfo") - .withInitiatives("Initiatives").withConfidence(2).withCreatedBy(user).withKeyResult(keyResultMetric) - .withCreatedOn(LocalDateTime.MAX).withModifiedOn(LocalDateTime.MAX).build(); - CheckIn savedCheckIn = CheckInMetric.Builder.builder().withId(id).withChangeInfo("") - .withInitiatives("Initiatives").withCreatedBy(user) - .withKeyResult(KeyResultMetric.Builder.builder().withId(13L).build()).build(); + CheckIn checkIn = CheckInMetric.Builder.builder() + .withValue(40.9) + .withId(id) + .withChangeInfo("ChangeInfo") + .withInitiatives("Initiatives") + .withConfidence(2) + .withCreatedBy(user) + .withKeyResult(keyResultMetric) + .withCreatedOn(LocalDateTime.MAX) + .withModifiedOn(LocalDateTime.MAX) + .build(); + CheckIn savedCheckIn = CheckInMetric.Builder.builder() + .withId(id) + .withChangeInfo("") + .withInitiatives("Initiatives") + .withCreatedBy(user) + .withKeyResult(KeyResultMetric.Builder.builder() + .withId(13L) + .build()) + .build(); when(checkInPersistenceService.findById(id)).thenReturn(savedCheckIn); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(id, checkIn)); + () -> validator.validateOnUpdate(id, checkIn)); verify(validator, times(1)).throwExceptionWhenModelIsNull(checkIn); verify(validator, times(1)).throwExceptionWhenIdIsNull(checkIn.getId()); verify(validator, times(1)).throwExceptionWhenIdHasChanged(checkIn.getId(), checkIn.getId()); - List expectedErrors = List - .of(new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", List.of("KeyResult", "Check-in"))); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", + List.of("KeyResult", "Check-in"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -268,21 +335,23 @@ void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { // arrange Long id = 11L; CheckIn checkInInvalid = CheckInMetric.Builder.builder() // - .withId(id) // - .withChangeInfo("ChangeInfo") // - .withKeyResult(KeyResultMetric.Builder.builder().withId(13L).build()) // - .build(); + .withId(id) // + .withChangeInfo("ChangeInfo") // + .withKeyResult(KeyResultMetric.Builder.builder() + .withId(13L) + .build()) // + .build(); when(checkInPersistenceService.findById(id)).thenReturn(checkInInvalid); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(id, checkInInvalid)); + () -> validator.validateOnUpdate(id, checkInInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "CheckIn")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("valueMetric", "CheckIn"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("confidence", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "CheckIn")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("valueMetric", "CheckIn"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -297,7 +366,7 @@ void validateOnDeleteShouldBeSuccessfulWhenValidKeyResultId() { void validateOnDeleteShouldThrowExceptionIfKeyResultIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnDelete(null)); + () -> validator.validateOnDelete(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/CompletedValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/CompletedValidationServiceTest.java index 3fbe650e14..da47f8714e 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/CompletedValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/CompletedValidationServiceTest.java @@ -1,9 +1,17 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.*; import ch.puzzle.okr.service.persistence.CompletedPersistenceService; +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -20,15 +28,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.List; -import java.util.stream.Stream; - -import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.params.provider.Arguments.arguments; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class CompletedValidationServiceTest { @MockBean @@ -43,24 +42,40 @@ class CompletedValidationServiceTest { @BeforeEach void setUp() { - this.user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); + this.user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); this.team = Team.Builder.builder().withId(1L).withName("Team1").build(); this.quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build(); - this.objective = Objective.Builder.builder().withId(1L).withTitle("Objective 1").withCreatedBy(user) - .withTeam(team).withQuarter(quarter).withDescription("This is our description") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withModifiedBy(user) - .withCreatedOn(LocalDateTime.MAX).build(); - - this.validCompleted = Completed.Builder.builder().withObjective(this.objective).withComment("Valid Comment") - .build(); + this.objective = Objective.Builder.builder() + .withId(1L) + .withTitle("Objective 1") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withDescription("This is our description") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withModifiedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .build(); + + this.validCompleted = Completed.Builder.builder() + .withObjective(this.objective) + .withComment("Valid Comment") + .build(); when(completedPersistenceService.getCompletedByObjectiveId(1L)).thenReturn(this.validCompleted); when(completedPersistenceService.getModelName()).thenReturn("Completed"); doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, - String.format("%s with id %s not found", completedPersistenceService.getModelName(), 2L))) - .when(completedPersistenceService).getCompletedByObjectiveId(2L); + String.format("%s with id %s not found", + completedPersistenceService.getModelName(), + 2L))).when(completedPersistenceService) + .getCompletedByObjectiveId(2L); } @Spy @@ -69,7 +84,8 @@ void setUp() { private static Stream nameValidationArguments() { return Stream.of(arguments(StringUtils.repeat('1', 5000), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("comment", "Completed", "0", "4096"))))); + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("comment", "Completed", "0", "4096"))))); } @Test @@ -84,7 +100,7 @@ void validateOnCreateShouldBeSuccessfulWhenCompletedIsValid() { void validateOnCreateShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Completed"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -94,14 +110,14 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { // arrange Completed completed = Completed.Builder.builder() // - .withId(300L) // - .withObjective(this.objective) // - .withComment("Not valid") // - .build(); + .withId(300L) // + .withObjective(this.objective) // + .withComment("Not valid") // + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(completed)); + () -> validator.validateOnCreate(completed)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Completed"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -112,13 +128,13 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { void validateOnCreateShouldThrowExceptionWhenCommentIsInvalid(String comment, List expectedErrors) { // arrange Completed completed = Completed.Builder.builder() // - .withObjective(this.objective) // - .withComment(comment) // - .build(); + .withObjective(this.objective) // + .withComment(comment) // + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(completed)); + () -> validator.validateOnCreate(completed)); assertOkrResponseStatusException(exception, expectedErrors); } @@ -127,14 +143,14 @@ void validateOnCreateShouldThrowExceptionWhenCommentIsInvalid(String comment, Li void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { // arrange Completed completedInvalid = Completed.Builder.builder() // - .withId(null) // - .withComment("Valid comment") // - .withObjective(null) // - .build(); + .withId(null) // + .withComment("Valid comment") // + .withObjective(null) // + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(completedInvalid)); + () -> validator.validateOnCreate(completedInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("objective", "Completed"))); assertOkrResponseStatusException(exception, expectedErrors); diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/KeyResultValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/KeyResultValidationServiceTest.java index 5eaa2aa827..a917f00b76 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/KeyResultValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/KeyResultValidationServiceTest.java @@ -1,5 +1,12 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.Constants.KEY_RESULT; +import static ch.puzzle.okr.Constants.OBJECTIVE; +import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.*; @@ -7,6 +14,9 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; import ch.puzzle.okr.service.persistence.KeyResultPersistenceService; +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -23,40 +33,60 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.List; -import java.util.stream.Stream; - -import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; -import static ch.puzzle.okr.Constants.KEY_RESULT; -import static ch.puzzle.okr.Constants.OBJECTIVE; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.params.provider.Arguments.arguments; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class KeyResultValidationServiceTest { @MockBean KeyResultPersistenceService keyResultPersistenceService = Mockito.mock(KeyResultPersistenceService.class); - private final User user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); + private final User user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); private final Quarter quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2").build(); private final Team team = Team.Builder.builder().withId(1L).withName("Team1").build(); - private final Objective objective = Objective.Builder.builder().withId(1L).withTitle("Objective 1") - .withCreatedBy(user).withTeam(team).withQuarter(quarter).withDescription("This is our description") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withModifiedBy(user) - .withCreatedOn(LocalDateTime.MAX).build(); - private final KeyResult keyResultMetric = KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(7.0) - .withUnit(Unit.NUMBER).withId(5L).withTitle("Keyresult Metric").withObjective(objective).withOwner(user) - .build(); - private final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder().withCommitZone("Ein Baum") - .withTargetZone("Zwei Bäume").withTitle("Keyresult Ordinal").withObjective(objective).withOwner(user) - .build(); - private final KeyResult fullKeyResult = KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(7.0) - .withUnit(Unit.FTE).withId(null).withTitle("Keyresult Metric").withObjective(objective).withOwner(user) - .withCreatedOn(LocalDateTime.MIN).withModifiedOn(LocalDateTime.MAX).withDescription("Description") - .withCreatedBy(user).build(); + private final Objective objective = Objective.Builder.builder() + .withId(1L) + .withTitle("Objective 1") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withDescription("This is our description") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withModifiedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .build(); + private final KeyResult keyResultMetric = KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(7.0) + .withUnit(Unit.NUMBER) + .withId(5L) + .withTitle("Keyresult Metric") + .withObjective(objective) + .withOwner(user) + .build(); + private final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() + .withCommitZone("Ein Baum") + .withTargetZone("Zwei Bäume") + .withTitle("Keyresult Ordinal") + .withObjective(objective) + .withOwner(user) + .build(); + private final KeyResult fullKeyResult = KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(7.0) + .withUnit(Unit.FTE) + .withId(null) + .withTitle("Keyresult Metric") + .withObjective(objective) + .withOwner(user) + .withCreatedOn(LocalDateTime.MIN) + .withModifiedOn(LocalDateTime.MAX) + .withDescription("Description") + .withCreatedBy(user) + .build(); @BeforeEach void setUp() { @@ -72,20 +102,25 @@ void setUp() { private KeyResultValidationService validator; private static Stream nameValidationArguments() { - return Stream.of( - arguments(StringUtils.repeat('1', 251), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "KeyResult", "2", "250")))), - arguments(StringUtils.repeat('1', 1), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "KeyResult", "2", "250")))), - arguments("", - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "KeyResult", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), - arguments(" ", - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "KeyResult", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), - arguments(" ", List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("title", "KeyResult")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult"))))); + return Stream.of(arguments(StringUtils.repeat('1', 251), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "KeyResult", "2", "250")))), + arguments(StringUtils.repeat('1', 1), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "KeyResult", "2", "250")))), + arguments("", + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "KeyResult", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "KeyResult", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("title", "KeyResult")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "KeyResult"))))); } @Test @@ -100,7 +135,7 @@ void validateOnGetShouldBeSuccessfulWhenValidKeyResultId() { void validateOnGetShouldThrowExceptionIfKeyResultIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -120,7 +155,7 @@ void validateOnCreateShouldBeSuccessfulWhenKeyResultIsValid() { void validateOnCreateShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("KeyResult"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -130,7 +165,7 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(keyResultMetric)); + () -> validator.validateOnCreate(keyResultMetric)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "KeyResult"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -141,20 +176,20 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { void validateOnCreateShouldThrowExceptionWhenTitleIsInvalid(String title, List errors) { // arrange KeyResult keyResult = KeyResultMetric.Builder.builder() // - .withBaseline(3.0) // - .withStretchGoal(5.0) // - .withUnit(Unit.EUR) // - .withId(null) // - .withTitle(title) // - .withOwner(user) // - .withObjective(objective) // - .withCreatedBy(user) // - .withCreatedOn(LocalDateTime.MIN) // - .build(); + .withBaseline(3.0) // + .withStretchGoal(5.0) // + .withUnit(Unit.EUR) // + .withId(null) // + .withTitle(title) // + .withOwner(user) // + .withObjective(objective) // + .withCreatedBy(user) // + .withCreatedOn(LocalDateTime.MIN) // + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(keyResult)); + () -> validator.validateOnCreate(keyResult)); assertOkrResponseStatusException(exception, errors); } @@ -162,22 +197,22 @@ void validateOnCreateShouldThrowExceptionWhenTitleIsInvalid(String title, List validator.validateOnCreate(keyResultInvalid)); + () -> validator.validateOnCreate(keyResultInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("owner", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("stretchGoal", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("objective", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("baseline", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("unit", "KeyResult"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("owner", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("stretchGoal", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("objective", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("baseline", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("unit", "KeyResult"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -185,10 +220,19 @@ void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { void validateOnUpdateShouldBeSuccessfulWhenKeyResultIsValid() { // arrange Long id = 5L; - KeyResult keyResult = KeyResultMetric.Builder.builder().withBaseline(4.0).withStretchGoal(7.0) - .withUnit(Unit.EUR).withId(id).withTitle("Keyresult Metric").withObjective(objective).withOwner(user) - .withCreatedOn(LocalDateTime.MIN).withModifiedOn(LocalDateTime.MAX).withDescription("Description") - .withCreatedBy(user).build(); + KeyResult keyResult = KeyResultMetric.Builder.builder() + .withBaseline(4.0) + .withStretchGoal(7.0) + .withUnit(Unit.EUR) + .withId(id) + .withTitle("Keyresult Metric") + .withObjective(objective) + .withOwner(user) + .withCreatedOn(LocalDateTime.MIN) + .withModifiedOn(LocalDateTime.MAX) + .withDescription("Description") + .withCreatedBy(user) + .build(); when(keyResultPersistenceService.findById(id)).thenReturn(keyResult); // act @@ -205,7 +249,7 @@ void validateOnUpdateShouldBeSuccessfulWhenKeyResultIsValid() { void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, null)); + () -> validator.validateOnUpdate(1L, null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("KeyResult"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -215,7 +259,7 @@ void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, keyResultOrdinal)); + () -> validator.validateOnUpdate(null, keyResultOrdinal)); verify(validator, times(1)).throwExceptionWhenModelIsNull(keyResultOrdinal); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -228,7 +272,7 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, keyResultMetric)); + () -> validator.validateOnUpdate(1L, keyResultMetric)); verify(validator, times(1)).throwExceptionWhenModelIsNull(keyResultMetric); verify(validator, times(1)).throwExceptionWhenIdIsNull(keyResultMetric.getId()); @@ -244,21 +288,21 @@ void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String title, List validator.validateOnUpdate(id, keyResult)); + () -> validator.validateOnUpdate(id, keyResult)); assertOkrResponseStatusException(exception, errors); } @@ -268,23 +312,23 @@ void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { // arrange Long id = 11L; KeyResult keyResultInvalid = KeyResultMetric.Builder.builder() // - .withId(id) // - .withTitle("Title") // - .withObjective(objective) // - .build(); + .withId(id) // + .withTitle("Title") // + .withObjective(objective) // + .build(); when(keyResultPersistenceService.findById(id)).thenReturn(keyResultInvalid); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(id, keyResultInvalid)); + () -> validator.validateOnUpdate(id, keyResultInvalid)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("baseline", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("stretchGoal", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("unit", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "KeyResult")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("owner", "KeyResult"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("baseline", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("stretchGoal", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("unit", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "KeyResult")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("owner", "KeyResult"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -300,7 +344,7 @@ void validateOnDeleteShouldBeSuccessfulWhenValidKeyResultId() { void validateOnDeleteShouldThrowExceptionIfKeyResultIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -316,23 +360,25 @@ void validateOnUpdateShouldThrowExceptionWhenObjectiveIdOfKeyResultHasChanged() Long objectiveId = 2L; Objective objective = Objective.Builder.builder().withId(objectiveId).build(); KeyResult keyResult = KeyResultMetric.Builder.builder() // - .withId(keyResultId) // - .withObjective(objective).build(); + .withId(keyResultId) // + .withObjective(objective) + .build(); Long savedObjectiveId = 3L; Objective savedObjective = Objective.Builder.builder().withId(savedObjectiveId).build(); KeyResult savedKeyResultWithDifferentObjectiveId = KeyResultMetric.Builder.builder() // - .withId(keyResultId) // - .withObjective(savedObjective).build(); + .withId(keyResultId) // + .withObjective(savedObjective) + .build(); when(keyResultPersistenceService.findById(keyResultId)).thenReturn(savedKeyResultWithDifferentObjectiveId); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(keyResultId, keyResult)); + () -> validator.validateOnUpdate(keyResultId, keyResult)); - List expectedErrors = List - .of(new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", List.of(OBJECTIVE, KEY_RESULT))); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", + List.of(OBJECTIVE, KEY_RESULT))); assertOkrResponseStatusException(exception, expectedErrors); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/ObjectiveValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/ObjectiveValidationServiceTest.java index cc52bad997..1c17cbfd10 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/ObjectiveValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/ObjectiveValidationServiceTest.java @@ -1,10 +1,23 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; +import static ch.puzzle.okr.test.TestConstants.BACK_LOG_QUARTER_ID; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.mockito.Mockito.*; +import static org.springframework.http.HttpStatus.BAD_REQUEST; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.*; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.test.TestHelper; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -20,20 +33,6 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.List; -import java.util.stream.Stream; - -import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; -import static ch.puzzle.okr.test.TestConstants.BACK_LOG_QUARTER_ID; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.junit.jupiter.params.provider.Arguments.arguments; -import static org.mockito.Mockito.*; -import static org.springframework.http.HttpStatus.BAD_REQUEST; -import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; - @ExtendWith(MockitoExtension.class) class ObjectiveValidationServiceTest { @MockBean @@ -49,46 +48,75 @@ class ObjectiveValidationServiceTest { private ObjectiveValidationService validator; private static Stream nameValidationArguments() { - return Stream.of( - arguments(StringUtils.repeat('1', 251), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "Objective", "2", "250")))), - arguments(StringUtils.repeat('1', 1), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "Objective", "2", "250")))), - - arguments("", - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "Objective", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), - - arguments(" ", - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "Objective", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), - - arguments(" ", List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("title", "Objective"))))); + return Stream.of(arguments(StringUtils.repeat('1', 251), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "Objective", "2", "250")))), + arguments(StringUtils.repeat('1', 1), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "Objective", "2", "250")))), + + arguments("", + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "Objective", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), + + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "Objective", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), + + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("title", "Objective")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("title", "Objective"))))); } @BeforeEach void setUp() { - this.user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); + this.user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); this.team = Team.Builder.builder().withId(1L).withName("Team1").build(); - this.quarter = Quarter.Builder.builder().withId(1L).withLabel("GJ 22/23-Q2") - .withStartDate(LocalDate.of(2022, 1, 1)).withEndDate(LocalDate.of(2022, 3, 31)).build(); - - this.objective1 = Objective.Builder.builder().withId(1L).withTitle("Objective 1").withCreatedBy(user) - .withTeam(team).withQuarter(quarter).withDescription("This is our description") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withModifiedBy(user) - .withCreatedOn(LocalDateTime.MAX).build(); - - this.objectiveMinimal = Objective.Builder.builder().withId(null).withTitle("Objective 2").withCreatedBy(user) - .withTeam(team).withQuarter(quarter).withState(State.DRAFT).withCreatedOn(LocalDateTime.MAX).build(); + this.quarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ 22/23-Q2") + .withStartDate(LocalDate.of(2022, 1, 1)) + .withEndDate(LocalDate.of(2022, 3, 31)) + .build(); + + this.objective1 = Objective.Builder.builder() + .withId(1L) + .withTitle("Objective 1") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withDescription("This is our description") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withModifiedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .build(); + + this.objectiveMinimal = Objective.Builder.builder() + .withId(null) + .withTitle("Objective 2") + .withCreatedBy(user) + .withTeam(team) + .withQuarter(quarter) + .withState(State.DRAFT) + .withCreatedOn(LocalDateTime.MAX) + .build(); when(objectivePersistenceService.findById(1L)).thenReturn(objective1); when(objectivePersistenceService.getModelName()).thenReturn("Objective"); doThrow(new OkrResponseStatusException(HttpStatus.NOT_FOUND, - String.format("%s with id %s not found", objectivePersistenceService.getModelName(), 2L))) - .when(objectivePersistenceService).findById(2L); + String.format("%s with id %s not found", + objectivePersistenceService.getModelName(), + 2L))).when(objectivePersistenceService).findById(2L); } @Test @@ -102,7 +130,7 @@ void validateOnGetShouldBeSuccessfulWhenValidObjectiveId() { @Test void validateOnGetShouldThrowExceptionIfObjectiveIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Objective"))); @@ -123,7 +151,7 @@ void validateOnCreateShouldBeSuccessfulWhenTeamIsValid() { @Test void validateOnCreateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Objective"))); @@ -135,7 +163,7 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { @Test void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objective1)); + () -> validator.validateOnCreate(objective1)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Objective"))); @@ -147,12 +175,20 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { @ParameterizedTest @MethodSource("nameValidationArguments") void validateOnCreateShouldThrowExceptionWhenTitleIsInvalid(String title, List expectedErrors) { - Objective objective = Objective.Builder.builder().withId(null).withTitle(title).withCreatedBy(this.user) - .withTeam(this.team).withQuarter(this.quarter).withDescription("This is our description 2") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withCreatedOn(LocalDateTime.MAX).build(); + Objective objective = Objective.Builder.builder() + .withId(null) + .withTitle(title) + .withCreatedBy(this.user) + .withTeam(this.team) + .withQuarter(this.quarter) + .withDescription("This is our description 2") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withCreatedOn(LocalDateTime.MAX) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objective)); + () -> validator.validateOnCreate(objective)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); @@ -161,15 +197,18 @@ void validateOnCreateShouldThrowExceptionWhenTitleIsInvalid(String title, List validator.validateOnCreate(objectiveInvalid)); + () -> validator.validateOnCreate(objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("team", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); @@ -178,14 +217,22 @@ void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { @Test void validateOnCreateShouldThrowExceptionWhenAttrModifiedByIsSet() { - Objective objectiveInvalid = Objective.Builder.builder().withId(null) - .withTitle("ModifiedBy is not null on create").withCreatedBy(user).withCreatedOn(LocalDateTime.MAX) - .withState(State.DRAFT).withTeam(team).withQuarter(quarter).withModifiedBy(user).build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(null) + .withTitle("ModifiedBy is not null on create") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(quarter) + .withModifiedBy(user) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objectiveInvalid)); - List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_SET_FORBIDDEN", List.of("ModifiedBy", - "User{id=1, version=0, firstname='Bob', lastname='Kaufmann', email='kaufmann@puzzle.ch', isOkrChampion='false'}"))); + () -> validator.validateOnCreate(objectiveInvalid)); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_SET_FORBIDDEN", + List.of("ModifiedBy", + "User{id=1, version=0, firstname='Bob', lastname='Kaufmann', email='kaufmann@puzzle.ch', isOkrChampion='false'}"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); @@ -194,14 +241,23 @@ void validateOnCreateShouldThrowExceptionWhenAttrModifiedByIsSet() { @Test void validateOnCreateShouldThrowExceptionWhenStartDateIsNull() { - Quarter invalidQuarter = Quarter.Builder.builder().withId(1L).withLabel("GJ-22/23-Q3") - .withEndDate(LocalDate.of(2022, 7, 31)).build(); - Objective objectiveInvalid = Objective.Builder.builder().withId(null).withTitle("Start date is missing") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(invalidQuarter).build(); + Quarter invalidQuarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ-22/23-Q3") + .withEndDate(LocalDate.of(2022, 7, 31)) + .build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(null) + .withTitle("Start date is missing") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(invalidQuarter) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objectiveInvalid)); + () -> validator.validateOnCreate(objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("StartDate", "GJ-22/23-Q3"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); @@ -211,14 +267,23 @@ void validateOnCreateShouldThrowExceptionWhenStartDateIsNull() { @Test void validateOnCreateShouldThrowExceptionWhenEndDateIsNull() { - Quarter invalidQuarter = Quarter.Builder.builder().withId(1L).withLabel("GJ-22/23-Q3") - .withStartDate(LocalDate.of(2022, 4, 1)).build(); - Objective objectiveInvalid = Objective.Builder.builder().withId(null).withTitle("End date is missing") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(invalidQuarter).build(); + Quarter invalidQuarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ-22/23-Q3") + .withStartDate(LocalDate.of(2022, 4, 1)) + .build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(null) + .withTitle("End date is missing") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(invalidQuarter) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(objectiveInvalid)); + () -> validator.validateOnCreate(objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("EndDate", "GJ-22/23-Q3"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); @@ -239,7 +304,7 @@ void validateOnUpdateShouldBeSuccessfulWhenObjectiveIsValid() { @Test void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, null)); + () -> validator.validateOnUpdate(1L, null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Objective"))); @@ -251,7 +316,7 @@ void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { @Test void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, objectiveMinimal)); + () -> validator.validateOnUpdate(null, objectiveMinimal)); verify(validator, times(1)).throwExceptionWhenModelIsNull(objectiveMinimal); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -265,7 +330,7 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { @Test void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(7L, objective1)); + () -> validator.validateOnUpdate(7L, objective1)); verify(validator, times(1)).throwExceptionWhenModelIsNull(objective1); verify(validator, times(1)).throwExceptionWhenIdIsNull(objective1.getId()); @@ -280,14 +345,22 @@ void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { @ParameterizedTest @MethodSource("nameValidationArguments") void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String title, List expectedErrors) { - Objective objective = Objective.Builder.builder().withId(3L).withTitle(title).withCreatedBy(this.user) - .withTeam(this.team).withQuarter(this.quarter).withDescription("This is our description 2") - .withModifiedOn(LocalDateTime.MAX).withState(State.DRAFT).withModifiedBy(this.user) - .withCreatedOn(LocalDateTime.MAX).build(); + Objective objective = Objective.Builder.builder() + .withId(3L) + .withTitle(title) + .withCreatedBy(this.user) + .withTeam(this.team) + .withQuarter(this.quarter) + .withDescription("This is our description 2") + .withModifiedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withModifiedBy(this.user) + .withCreatedOn(LocalDateTime.MAX) + .build(); when(objectivePersistenceService.findById(objective.getId())).thenReturn(objective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, objective)); + () -> validator.validateOnUpdate(3L, objective)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); @@ -296,16 +369,20 @@ void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String title, List validator.validateOnUpdate(5L, objective)); + () -> validator.validateOnUpdate(5L, objective)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("team", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective"))); + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); @@ -314,12 +391,19 @@ void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { @Test void validateOnUpdateShouldThrowExceptionWhenAttrModifiedByIsNotSet() { - Objective objectiveInvalid = Objective.Builder.builder().withId(1L) - .withTitle("ModifiedBy is not null on create").withCreatedBy(user).withCreatedOn(LocalDateTime.MAX) - .withState(State.DRAFT).withTeam(team).withQuarter(quarter).withModifiedBy(null).build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(1L) + .withTitle("ModifiedBy is not null on create") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(quarter) + .withModifiedBy(null) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, objectiveInvalid)); + () -> validator.validateOnUpdate(1L, objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_SET", List.of("modifiedBy"))); @@ -330,14 +414,24 @@ void validateOnUpdateShouldThrowExceptionWhenAttrModifiedByIsNotSet() { @Test void validateOnUpdateShouldThrowExceptionWhenStartDateIsNull() { - Quarter invalidQuarter = Quarter.Builder.builder().withId(1L).withLabel("GJ-22/23-Q3") - .withEndDate(LocalDate.of(2022, 7, 31)).build(); - Objective objectiveInvalid = Objective.Builder.builder().withId(1L).withTitle("Start date is missing") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(invalidQuarter).withModifiedBy(user).build(); + Quarter invalidQuarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ-22/23-Q3") + .withEndDate(LocalDate.of(2022, 7, 31)) + .build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(1L) + .withTitle("Start date is missing") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(invalidQuarter) + .withModifiedBy(user) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, objectiveInvalid)); + () -> validator.validateOnUpdate(1L, objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("StartDate", "GJ-22/23-Q3"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); @@ -347,14 +441,24 @@ void validateOnUpdateShouldThrowExceptionWhenStartDateIsNull() { @Test void validateOnUpdateShouldThrowExceptionWhenEndDateIsNull() { - Quarter invalidQuarter = Quarter.Builder.builder().withId(1L).withLabel("GJ-22/23-Q3") - .withStartDate(LocalDate.of(2022, 4, 1)).build(); - Objective objectiveInvalid = Objective.Builder.builder().withId(1L).withTitle("End date is missing") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(invalidQuarter).withModifiedBy(user).build(); + Quarter invalidQuarter = Quarter.Builder.builder() + .withId(1L) + .withLabel("GJ-22/23-Q3") + .withStartDate(LocalDate.of(2022, 4, 1)) + .build(); + Objective objectiveInvalid = Objective.Builder.builder() + .withId(1L) + .withTitle("End date is missing") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(invalidQuarter) + .withModifiedBy(user) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, objectiveInvalid)); + () -> validator.validateOnUpdate(1L, objectiveInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("EndDate", "GJ-22/23-Q3"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); @@ -364,17 +468,33 @@ void validateOnUpdateShouldThrowExceptionWhenEndDateIsNull() { @Test void validateOnUpdateShouldThrowExceptionWheTeamHasChanged() { - Objective savedObjective = Objective.Builder.builder().withId(1L).withTitle("Team has changed") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(quarter).withModifiedBy(null).build(); - Objective updatedObjective = Objective.Builder.builder().withId(1L).withTitle("Team has changed") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT) - .withTeam(Team.Builder.builder().withId(2L).withName("other team").build()).withQuarter(quarter) - .withModifiedBy(user).build(); + Objective savedObjective = Objective.Builder.builder() + .withId(1L) + .withTitle("Team has changed") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(quarter) + .withModifiedBy(null) + .build(); + Objective updatedObjective = Objective.Builder.builder() + .withId(1L) + .withTitle("Team has changed") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(Team.Builder.builder() + .withId(2L) + .withName("other team") + .build()) + .withQuarter(quarter) + .withModifiedBy(user) + .build(); when(objectivePersistenceService.findById(savedObjective.getId())).thenReturn(savedObjective); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, updatedObjective)); + () -> validator.validateOnUpdate(1L, updatedObjective)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", List.of("Team", "Objective"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); @@ -383,18 +503,28 @@ void validateOnUpdateShouldThrowExceptionWheTeamHasChanged() { } @ParameterizedTest - @EnumSource(value = State.class, names = { "DRAFT" }, mode = EnumSource.Mode.EXCLUDE) + @EnumSource(value = State.class, names = {"DRAFT"}, mode = EnumSource.Mode.EXCLUDE) void validateOnCreateShouldThrowExceptionWhenQuarterIsBacklogAndStateIsNotDraft(State state) { - Quarter backlogQuarter = Quarter.Builder.builder().withId(BACK_LOG_QUARTER_ID).withLabel(BACK_LOG_QUARTER_LABEL) - .withStartDate(null).withEndDate(null).build(); - - Objective invalidObjective = Objective.Builder.builder().withTitle("Invalid Objective").withCreatedBy(user) - .withCreatedOn(LocalDateTime.MAX).withState(state).withTeam(team).withQuarter(backlogQuarter).build(); + Quarter backlogQuarter = Quarter.Builder.builder() + .withId(BACK_LOG_QUARTER_ID) + .withLabel(BACK_LOG_QUARTER_LABEL) + .withStartDate(null) + .withEndDate(null) + .build(); + + Objective invalidObjective = Objective.Builder.builder() + .withTitle("Invalid Objective") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(state) + .withTeam(team) + .withQuarter(backlogQuarter) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(invalidObjective)); - List expectedErrors = List - .of(new ErrorDto("ATTRIBUTE_MUST_BE_DRAFT", List.of("Objective", "Draft", state.toString()))); + () -> validator.validateOnCreate(invalidObjective)); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_MUST_BE_DRAFT", + List.of("Objective", "Draft", state.toString()))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); @@ -402,19 +532,30 @@ void validateOnCreateShouldThrowExceptionWhenQuarterIsBacklogAndStateIsNotDraft( } @ParameterizedTest - @EnumSource(value = State.class, names = { "DRAFT" }, mode = EnumSource.Mode.EXCLUDE) + @EnumSource(value = State.class, names = {"DRAFT"}, mode = EnumSource.Mode.EXCLUDE) void validateOnUpdateShouldThrowExceptionWhenQuarterIsBacklogAndStateIsNotDraft(State state) { - Quarter backlogQuarter = Quarter.Builder.builder().withId(BACK_LOG_QUARTER_ID).withLabel(BACK_LOG_QUARTER_LABEL) - .withStartDate(null).withEndDate(null).build(); - - Objective invalidObjective = Objective.Builder.builder().withId(1L).withTitle("Invalid Objective") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(state).withTeam(team) - .withQuarter(backlogQuarter).withModifiedBy(user).build(); + Quarter backlogQuarter = Quarter.Builder.builder() + .withId(BACK_LOG_QUARTER_ID) + .withLabel(BACK_LOG_QUARTER_LABEL) + .withStartDate(null) + .withEndDate(null) + .build(); + + Objective invalidObjective = Objective.Builder.builder() + .withId(1L) + .withTitle("Invalid Objective") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(state) + .withTeam(team) + .withQuarter(backlogQuarter) + .withModifiedBy(user) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, invalidObjective)); - List expectedErrors = List - .of(new ErrorDto("ATTRIBUTE_MUST_BE_DRAFT", List.of("Objective", "Draft", state.toString()))); + () -> validator.validateOnUpdate(1L, invalidObjective)); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_MUST_BE_DRAFT", + List.of("Objective", "Draft", state.toString()))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); @@ -423,12 +564,23 @@ void validateOnUpdateShouldThrowExceptionWhenQuarterIsBacklogAndStateIsNotDraft( @Test void validateOnUpdateShouldPassWhenQuarterIsBacklogAndStateIsDraft() { - Quarter backlogQuarter = Quarter.Builder.builder().withId(BACK_LOG_QUARTER_ID).withLabel(BACK_LOG_QUARTER_LABEL) - .withStartDate(null).withEndDate(null).build(); - - Objective validObjective = Objective.Builder.builder().withId(1L).withTitle("Invalid Objective") - .withCreatedBy(user).withCreatedOn(LocalDateTime.MAX).withState(State.DRAFT).withTeam(team) - .withQuarter(backlogQuarter).withModifiedBy(user).build(); + Quarter backlogQuarter = Quarter.Builder.builder() + .withId(BACK_LOG_QUARTER_ID) + .withLabel(BACK_LOG_QUARTER_LABEL) + .withStartDate(null) + .withEndDate(null) + .build(); + + Objective validObjective = Objective.Builder.builder() + .withId(1L) + .withTitle("Invalid Objective") + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withState(State.DRAFT) + .withTeam(team) + .withQuarter(backlogQuarter) + .withModifiedBy(user) + .build(); assertDoesNotThrow(() -> validator.validateOnUpdate(1L, validObjective)); } @@ -444,7 +596,7 @@ void validateOnDeleteShouldBeSuccessfulWhenValidObjectiveId() { @Test void validateOnDeleteShouldThrowExceptionIfObjectiveIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Objective"))); diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/OverviewValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/OverviewValidationServiceTest.java index f61bbc48cd..742017d560 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/OverviewValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/OverviewValidationServiceTest.java @@ -1,16 +1,16 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.test.OverviewTestHelper.*; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import static ch.puzzle.okr.test.OverviewTestHelper.*; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - @ExtendWith(MockitoExtension.class) class OverviewValidationServiceTest { @Mock diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/QuarterValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/QuarterValidationServiceTest.java index d47a98e53c..2dae5107ac 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/QuarterValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/QuarterValidationServiceTest.java @@ -1,10 +1,18 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Quarter; import ch.puzzle.okr.service.persistence.QuarterPersistenceService; import ch.puzzle.okr.test.TestHelper; +import java.time.LocalDate; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -14,15 +22,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.mock.mockito.MockBean; -import java.time.LocalDate; -import java.util.List; - -import static ch.puzzle.okr.Constants.BACK_LOG_QUARTER_LABEL; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -import static org.springframework.http.HttpStatus.BAD_REQUEST; - @ExtendWith(MockitoExtension.class) class QuarterValidationServiceTest { @MockBean @@ -57,7 +56,7 @@ void throwExceptionWhenStartEndDateQuarterIsNullShouldThrowExceptionWhenStartDat // act + assert OkrResponseStatusException okrResponseStatusException = assertThrows(OkrResponseStatusException.class, - () -> QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull(quarter)); + () -> QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull(quarter)); assertEquals(BAD_REQUEST, okrResponseStatusException.getStatusCode()); } @@ -72,7 +71,7 @@ void throwExceptionWhenStartEndDateQuarterIsNullShouldThrowExceptionWhenEndDateI // act + assert OkrResponseStatusException okrResponseStatusException = assertThrows(OkrResponseStatusException.class, - () -> QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull(quarter)); + () -> QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull(quarter)); assertEquals(BAD_REQUEST, okrResponseStatusException.getStatusCode()); } @@ -100,7 +99,7 @@ void validateOnCreateShouldThrowException() { @Test void validateOnUpdateShouldThrowException() { Exception exception = assertThrows(IllegalCallerException.class, - () -> validator.validateOnUpdate(anyLong(), any())); + () -> validator.validateOnUpdate(anyLong(), any())); assertEquals("This method must not be called because there is no update of quarters", exception.getMessage()); } @@ -114,11 +113,11 @@ void validateOnGenerationShouldThrowExceptionWhenStartDateIsNull() { // act + assert OkrResponseStatusException okrResponseStatusException = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGeneration(quarter)); + () -> validator.validateOnGeneration(quarter)); assertOkrResponseStatusException( // - okrResponseStatusException, // - List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("StartDate", "Any Label")))); + okrResponseStatusException, // + List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("StartDate", "Any Label")))); } @DisplayName("validateOnGeneration() should throw exception when EndDate is null") @@ -132,11 +131,11 @@ void validateOnGenerationShouldThrowExceptionWhenEndDateIsNull() { // act + assert OkrResponseStatusException okrResponseStatusException = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGeneration(quarter)); + () -> validator.validateOnGeneration(quarter)); assertOkrResponseStatusException( // - okrResponseStatusException, // - List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("EndDate", "Any Label")))); + okrResponseStatusException, // + List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("EndDate", "Any Label")))); } @DisplayName("validateOnGeneration() should do nothing when both dates are not null") diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/TeamValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/TeamValidationServiceTest.java index 044a7b9a5c..eec4f50788 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/TeamValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/TeamValidationServiceTest.java @@ -1,10 +1,16 @@ package ch.puzzle.okr.service.validation; -import ch.puzzle.okr.test.TestHelper; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Team; import ch.puzzle.okr.service.persistence.TeamPersistenceService; +import ch.puzzle.okr.test.TestHelper; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -17,13 +23,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; -import static org.springframework.http.HttpStatus.BAD_REQUEST; - @ExtendWith(MockitoExtension.class) class TeamValidationServiceTest { @MockBean @@ -46,8 +45,9 @@ void setUp() { when(teamPersistenceService.findById(1L)).thenReturn(team1); when(teamPersistenceService.getModelName()).thenReturn("Team"); doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, - String.format("%s with id %s not found", teamPersistenceService.getModelName(), 2L))) - .when(teamPersistenceService).findById(2L); + String.format("%s with id %s not found", + teamPersistenceService.getModelName(), + 2L))).when(teamPersistenceService).findById(2L); } @Spy @@ -65,7 +65,7 @@ void validateOnGetShouldBeSuccessfulWhenValidTeamId() { @Test void validateOnGetShouldThrowExceptionIfTeamIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Team"))); @@ -86,7 +86,7 @@ void validateOnDeleteShouldBeSuccessfulWhenValidTeamId() { @Test void validateOnDeleteShouldThrowExceptionIfTeamIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Team"))); @@ -99,7 +99,7 @@ void validateOnDeleteShouldThrowExceptionIfTeamIdIsNull() { @Test void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(team1)); + () -> validator.validateOnCreate(team1)); verify(validator, times(1)).throwExceptionWhenIdIsNotNull(team1.getId()); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Team"))); @@ -112,7 +112,7 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { void validateOnCreateShouldThrowExceptionWhenTeamAlreadyExists() { BDDMockito.given(teamPersistenceService.findTeamsByName(anyString())).willReturn(List.of(team1)); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(teamWithIdNull)); + () -> validator.validateOnCreate(teamWithIdNull)); List expectedErrors = List.of(new ErrorDto("ALREADY_EXISTS_SAME_NAME", List.of("Team", "Team null"))); @@ -124,7 +124,7 @@ void validateOnCreateShouldThrowExceptionWhenTeamAlreadyExists() { @Test void validateOnCreateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); verify(validator, times(1)).throwExceptionWhenModelIsNull(null); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Team"))); @@ -136,12 +136,12 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { @Test void validateOnCreateShouldThrowExceptionWhenModelIsNameIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(teamWithoutName)); + () -> validator.validateOnCreate(teamWithoutName)); verify(validator, times(1)).throwExceptionWhenModelIsNull(teamWithoutName); verify(validator, times(1)).throwExceptionWhenIdIsNotNull(teamWithoutName.getId()); verify(validator, times(1)).validate(teamWithoutName); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("name", "Team")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("name", "Team"))); + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("name", "Team"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); @@ -151,7 +151,8 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNameIsNull() { @Test void validateOnUpdateShouldThrowExceptionWhenModelIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(teamWithIdNull.getId(), teamWithIdNull)); + () -> validator.validateOnUpdate(teamWithIdNull.getId(), + teamWithIdNull)); verify(validator, times(1)).throwExceptionWhenModelIsNull(teamWithIdNull); verify(validator, times(1)).throwExceptionWhenIdIsNull(teamWithIdNull.getId()); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Team"))); @@ -164,7 +165,7 @@ void validateOnUpdateShouldThrowExceptionWhenModelIdIsNull() { @Test void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, null)); + () -> validator.validateOnUpdate(null, null)); verify(validator, times(1)).throwExceptionWhenModelIsNull(null); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Team"))); @@ -176,12 +177,13 @@ void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { @Test void validateOnUpdateShouldThrowExceptionWhenModelIsNameIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(teamWithoutNameWithId.getId(), teamWithoutNameWithId)); + () -> validator.validateOnUpdate(teamWithoutNameWithId.getId(), + teamWithoutNameWithId)); verify(validator, times(1)).throwExceptionWhenModelIsNull(teamWithoutNameWithId); verify(validator, times(1)).throwExceptionWhenIdIsNull(teamWithoutNameWithId.getId()); verify(validator, times(1)).validate(teamWithoutNameWithId); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("name", "Team")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("name", "Team"))); + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("name", "Team"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/UserValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/UserValidationServiceTest.java index fbf55cb798..4baa8f8ff1 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/UserValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/UserValidationServiceTest.java @@ -1,10 +1,18 @@ package ch.puzzle.okr.service.validation; -import ch.puzzle.okr.test.TestHelper; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.mockito.Mockito.*; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.User; import ch.puzzle.okr.service.persistence.UserPersistenceService; +import ch.puzzle.okr.test.TestHelper; +import java.util.List; +import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,15 +29,6 @@ import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.web.server.ResponseStatusException; -import java.util.List; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.junit.jupiter.params.provider.Arguments.arguments; -import static org.mockito.Mockito.*; -import static org.springframework.http.HttpStatus.BAD_REQUEST; - @ExtendWith(MockitoExtension.class) class UserValidationServiceTest { @MockBean @@ -43,17 +42,25 @@ class UserValidationServiceTest { @BeforeEach void setUp() { - user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - - userMinimal = User.Builder.builder().withFirstname("Max").withLastname("Mustermann") - .withEmail("max@mustermann.com").build(); + user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + + userMinimal = User.Builder.builder() + .withFirstname("Max") + .withLastname("Mustermann") + .withEmail("max@mustermann.com") + .build(); when(userPersistenceService.findById(1L)).thenReturn(user); when(userPersistenceService.getModelName()).thenReturn("User"); doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, - String.format("%s with id %s not found", userPersistenceService.getModelName(), 2L))) - .when(userPersistenceService).findById(2L); + String.format("%s with id %s not found", + userPersistenceService.getModelName(), + 2L))).when(userPersistenceService).findById(2L); } @Spy @@ -61,59 +68,71 @@ void setUp() { private UserValidationService validator; private static Stream firstNameValidationArguments() { - return Stream.of( - arguments(StringUtils.repeat('1', 51), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("firstname", "User", "2", "50")))), - arguments(StringUtils.repeat('1', 1), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("firstname", "User", "2", "50")))), - arguments("", - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("firstname", "User", "2", "50")))), - arguments(" ", - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("firstname", "User", "2", "50")))), - arguments(" ", List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("firstname", "User"))))); + return Stream.of(arguments(StringUtils.repeat('1', 51), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("firstname", "User", "2", "50")))), + arguments(StringUtils.repeat('1', 1), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("firstname", "User", "2", "50")))), + arguments("", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("firstname", "User", "2", "50")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("firstname", "User", "2", "50")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("firstname", "User")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("firstname", "User"))))); } private static Stream lastNameValidationArguments() { - return Stream.of( - arguments(StringUtils.repeat('1', 51), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("lastname", "User", "2", "50")))), - arguments(StringUtils.repeat('1', 1), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("lastname", "User", "2", "50")))), - arguments("", - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("lastname", "User", "2", "50")))), - arguments(" ", - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("lastname", "User", "2", "50")))), - arguments(" ", List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("lastname", "User"))))); + return Stream.of(arguments(StringUtils.repeat('1', 51), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("lastname", "User", "2", "50")))), + arguments(StringUtils.repeat('1', 1), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("lastname", "User", "2", "50")))), + arguments("", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("lastname", "User", "2", "50")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("lastname", "User", "2", "50")))), + arguments(" ", + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("lastname", "User")), + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("lastname", "User"))))); } private static Stream emailValidationArguments() { - return Stream.of( - arguments(("1".repeat(251)), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), - arguments(("1"), - List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")), - new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), - arguments((""), - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")))), - arguments((" "), - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), - new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")), - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")))), - arguments((" "), - List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), - new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), - arguments(null, List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("email", "User")), - new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User"))))); + return Stream.of(arguments(("1".repeat(251)), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), + arguments(("1"), + List.of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("email", "User", "2", "250")), + new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), + arguments((""), + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("email", "User", "2", "250")))), + arguments((" "), + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), + new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")), + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("email", "User", "2", "250")))), + arguments((" "), + List.of(new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User")), + new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User")))), + arguments(null, + List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("email", "User")), + new ErrorDto("ATTRIBUTE_NOT_BLANK", List.of("email", "User"))))); } @Test @@ -127,7 +146,7 @@ void validateOnGetShouldBeSuccessfulWhenValidUserId() { @Test void validateOnGetShouldThrowExceptionIfUserIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "User"))); @@ -147,7 +166,7 @@ void validateOnGetOrCreateShouldBeSuccessful() { @Test void validateOnGetOrCreateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGetOrCreate(null)); + () -> validator.validateOnGetOrCreate(null)); verify(validator, times(1)).throwExceptionWhenModelIsNull(null); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("User"))); @@ -168,7 +187,7 @@ void validateOnCreateShouldBeSuccessfulWhenUserIsValid() { @Test void validateOnCreateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(null)); + () -> validator.validateOnCreate(null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("User"))); @@ -180,7 +199,7 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { @Test void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(user)); + () -> validator.validateOnCreate(user)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "User"))); @@ -192,11 +211,14 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { @ParameterizedTest @MethodSource("firstNameValidationArguments") void validateOnCreateShouldThrowExceptionWhenFirstnameIsInvalid(String name, List errors) { - User user2 = User.Builder.builder().withEmail("max@mail.com").withFirstname(name).withLastname("lastname") - .build(); + User user2 = User.Builder.builder() + .withEmail("max@mail.com") + .withFirstname(name) + .withLastname("lastname") + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(user2)); + () -> validator.validateOnCreate(user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); @@ -206,11 +228,14 @@ void validateOnCreateShouldThrowExceptionWhenFirstnameIsInvalid(String name, Lis @ParameterizedTest @MethodSource("lastNameValidationArguments") void validateOnCreateShouldThrowExceptionWhenLastnameIsInvalid(String name, List errors) { - User user2 = User.Builder.builder().withEmail("max@mail.com").withFirstname("firstname").withLastname(name) - .build(); + User user2 = User.Builder.builder() + .withEmail("max@mail.com") + .withFirstname("firstname") + .withLastname(name) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(user2)); + () -> validator.validateOnCreate(user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); @@ -220,11 +245,14 @@ void validateOnCreateShouldThrowExceptionWhenLastnameIsInvalid(String name, List @ParameterizedTest @MethodSource("emailValidationArguments") void validateOnCreateShouldThrowExceptionWhenEmailIsInvalid(String email, List errors) { - User user2 = User.Builder.builder().withEmail(email).withFirstname("firstname").withLastname("lastname") - .build(); + User user2 = User.Builder.builder() + .withEmail(email) + .withFirstname("firstname") + .withLastname("lastname") + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(user2)); + () -> validator.validateOnCreate(user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); @@ -233,10 +261,14 @@ void validateOnCreateShouldThrowExceptionWhenEmailIsInvalid(String email, List validator.validateOnCreate(userInvalid)); + () -> validator.validateOnCreate(userInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User"))); @@ -258,7 +290,7 @@ void validateOnUpdateShouldBeSuccessfulWhenUserIsValid() { @Test void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, null)); + () -> validator.validateOnUpdate(1L, null)); List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("User"))); @@ -270,7 +302,7 @@ void validateOnUpdateShouldThrowExceptionWhenModelIsNull() { @Test void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(null, userMinimal)); + () -> validator.validateOnUpdate(null, userMinimal)); verify(validator, times(1)).throwExceptionWhenModelIsNull(userMinimal); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -285,7 +317,7 @@ void validateOnUpdateShouldThrowExceptionWhenIdIsNull() { @Test void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(7L, user)); + () -> validator.validateOnUpdate(7L, user)); verify(validator, times(1)).throwExceptionWhenModelIsNull(user); verify(validator, times(1)).throwExceptionWhenIdIsNull(user.getId()); @@ -301,11 +333,15 @@ void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { @ParameterizedTest @MethodSource("firstNameValidationArguments") void validateOnUpdateShouldThrowExceptionWhenFirstnameIsInvalid(String name, List errors) { - User user2 = User.Builder.builder().withId(3L).withEmail("max@mail.com").withFirstname(name) - .withLastname("lastname").build(); + User user2 = User.Builder.builder() + .withId(3L) + .withEmail("max@mail.com") + .withFirstname(name) + .withLastname("lastname") + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, user2)); + () -> validator.validateOnUpdate(3L, user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); @@ -315,11 +351,15 @@ void validateOnUpdateShouldThrowExceptionWhenFirstnameIsInvalid(String name, Lis @ParameterizedTest @MethodSource("lastNameValidationArguments") void validateOnUpdateShouldThrowExceptionWhenLastnameIsInvalid(String name, List errors) { - User user2 = User.Builder.builder().withId(3L).withEmail("max@mail.com").withFirstname("firstname") - .withLastname(name).build(); + User user2 = User.Builder.builder() + .withId(3L) + .withEmail("max@mail.com") + .withFirstname("firstname") + .withLastname(name) + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, user2)); + () -> validator.validateOnUpdate(3L, user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); @@ -329,11 +369,15 @@ void validateOnUpdateShouldThrowExceptionWhenLastnameIsInvalid(String name, List @ParameterizedTest @MethodSource("emailValidationArguments") void validateOnUpdateShouldThrowExceptionWhenEmailIsInvalid(String email, List errors) { - User user2 = User.Builder.builder().withId(3L).withEmail(email).withFirstname("firstname") - .withLastname("lastname").build(); + User user2 = User.Builder.builder() + .withId(3L) + .withEmail(email) + .withFirstname("firstname") + .withLastname("lastname") + .build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(3L, user2)); + () -> validator.validateOnUpdate(3L, user2)); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(errors).hasSameElementsAs(exception.getErrors()); @@ -342,10 +386,14 @@ void validateOnUpdateShouldThrowExceptionWhenEmailIsInvalid(String email, List validator.validateOnUpdate(3L, userInvalid)); + () -> validator.validateOnUpdate(3L, userInvalid)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_VALID", List.of("email", "User"))); @@ -364,7 +412,7 @@ void validateAuthorisationTokenShouldNotThrowError() { @Test void validateAuthorisationTokenShouldThrowErrorWhenNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateAuthorisationToken(null)); + () -> validator.validateAuthorisationToken(null)); List expectedErrors = List.of(new ErrorDto("TOKEN_NULL", List.of())); @@ -384,7 +432,7 @@ void validateOnDeleteShouldBeSuccessfulWhenValidObjectiveId() { @Test void validateOnDeleteShouldThrowExceptionIfObjectiveIdIsNull() { OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "User"))); diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/ValidationBaseTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/ValidationBaseTest.java index c91cfddc1b..076522f078 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/ValidationBaseTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/ValidationBaseTest.java @@ -1,5 +1,9 @@ package ch.puzzle.okr.service.validation; +import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.Objective; @@ -8,6 +12,7 @@ import ch.puzzle.okr.repository.QuarterRepository; import ch.puzzle.okr.service.persistence.ObjectivePersistenceService; import ch.puzzle.okr.service.persistence.QuarterPersistenceService; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -17,12 +22,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.mock.mockito.MockBean; -import java.util.List; - -import static ch.puzzle.okr.test.AssertionHelper.assertOkrResponseStatusException; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - @ExtendWith(MockitoExtension.class) class ValidationBaseTest { @MockBean @@ -62,7 +61,7 @@ void validateOnGetShouldThrowExceptionWhenIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(id)); + () -> validator.validateOnGet(id)); // assert List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Quarter"))); @@ -93,7 +92,7 @@ void validateOnDeleteShouldThrowExceptionWhenIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnDelete(id)); + () -> validator.validateOnDelete(id)); // assert List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Quarter"))); @@ -121,7 +120,7 @@ void throwExceptionWhenModelIsNullShouldThrowExceptionWhenModelIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.throwExceptionWhenModelIsNull(model)); + () -> validator.throwExceptionWhenModelIsNull(model)); // assert List expectedErrors = List.of(new ErrorDto("MODEL_NULL", List.of("Quarter"))); @@ -145,7 +144,7 @@ void throwExceptionWhenIdIsNotNullShouldThrowExceptionWhenIdIsNotNull() { // act OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.throwExceptionWhenIdIsNotNull(id)); + () -> validator.throwExceptionWhenIdIsNotNull(id)); // assert List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Quarter"))); @@ -171,11 +170,12 @@ void throwExceptionWhenIdHasChangedShouldThrowExceptionWhenIdsAreNotEqual() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.throwExceptionWhenIdHasChanged(id, modelId)); + () -> validator.throwExceptionWhenIdHasChanged(id, + modelId)); // assert - List expectedErrors = List - .of(new ErrorDto("ATTRIBUTE_CHANGED", List.of("ID", id.toString(), modelId.toString()))); + List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_CHANGED", + List.of("ID", id.toString(), modelId.toString()))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -201,7 +201,7 @@ void validateShouldThrowExceptionWhenWhenConstraintInModelClassIsViolated() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validate(quarterWithNullLabel)); + () -> validator.validate(quarterWithNullLabel)); List expectedErrors = List.of(new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("label", "Quarter"))); assertOkrResponseStatusException(exception, expectedErrors); @@ -217,21 +217,23 @@ void validateShouldThrowExceptionWhenOneOfSeveralConstraintsInModelClassIsViolat // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validatorWithSeveralConstraints.validate(objective)); + () -> validatorWithSeveralConstraints.validate(objective)); List expectedErrors = List.of( // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("team", "Objective")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective")), // - new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("quarter", "Objective")), // - new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", List.of("title", "Objective", "2", "250")) // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("team", "Objective")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdBy", "Objective")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("createdOn", "Objective")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("state", "Objective")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("quarter", "Objective")), // + new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("title", "Objective", "2", "250")) // ); assertOkrResponseStatusException(exception, expectedErrors); } static class DummyValidationService - extends ValidationBase { + extends + ValidationBase { public DummyValidationService(QuarterPersistenceService quarterPersistenceService) { super(quarterPersistenceService); @@ -247,7 +249,8 @@ public void validateOnUpdate(Long aLong, Quarter model) { } static class DummyValidationServiceWithSeveralConstraints - extends ValidationBase { + extends + ValidationBase { public DummyValidationServiceWithSeveralConstraints(ObjectivePersistenceService objectivePersistenceService) { super(objectivePersistenceService); diff --git a/backend/src/test/java/ch/puzzle/okr/test/AssertionHelper.java b/backend/src/test/java/ch/puzzle/okr/test/AssertionHelper.java index cb5e4e2322..401f52075f 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/AssertionHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/test/AssertionHelper.java @@ -1,27 +1,25 @@ package ch.puzzle.okr.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.http.HttpStatus.BAD_REQUEST; + import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; +import java.util.List; import org.junit.jupiter.api.Assertions; import org.springframework.http.HttpStatus; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.springframework.http.HttpStatus.BAD_REQUEST; - public class AssertionHelper { public static void assertOkrResponseStatusException(OkrResponseStatusException exception, - List expectedErrors) { + List expectedErrors) { assertOkrResponseStatusException(BAD_REQUEST, exception, expectedErrors); } public static void assertOkrResponseStatusException(HttpStatus statusCode, OkrResponseStatusException exception, - List expectedErrors) { + List expectedErrors) { assertEquals(statusCode, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); diff --git a/backend/src/test/java/ch/puzzle/okr/test/CheckInTestHelpers.java b/backend/src/test/java/ch/puzzle/okr/test/CheckInTestHelpers.java index 78c98b659e..f2cd871027 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/CheckInTestHelpers.java +++ b/backend/src/test/java/ch/puzzle/okr/test/CheckInTestHelpers.java @@ -11,7 +11,6 @@ import ch.puzzle.okr.models.checkin.Zone; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; - import java.time.LocalDateTime; public class CheckInTestHelpers { @@ -29,9 +28,9 @@ public class CheckInTestHelpers { public static final String JSON_CHANGE_INFO = "changeinfo"; public static final String JSON_INITIATIVES = "initiatives"; public static final String JSON = "{\"" + JSON_CHANGE_INFO + "\":" + "\"" + CHANGE_INFO_1 + "\"" - + ", \"keyResultId\": 1}"; + + ", \"keyResultId\": 1}"; public static final String JSON_WITHOUT_KEY_RESULT_ID = "{\"" + JSON_CHANGE_INFO + "\":" + "\"" + CHANGE_INFO_1 - + "\"}"; + + "\"}"; public static final String JSON_PATH_ID = "$.id"; public static final String JSON_PATH_CHANGE_INFO = "$.changeInfo"; @@ -46,24 +45,60 @@ public class CheckInTestHelpers { /* Test entities */ static final Objective objective = Objective.Builder.builder().withId(1L).build(); - public static final CheckIn checkInMetric = CheckInMetric.Builder.builder().withValue(30D).withConfidence(5) - .withChangeInfo(CHANGE_INFO).withInitiatives(INITIATIVES) - .withCreatedBy(User.Builder.builder().withId(1L).withFirstname("Frank").build()) - .withKeyResult(KeyResultMetric.Builder.builder().withBaseline(3.0).withStretchGoal(6.0).withId(8L) - .withObjective(objective).build()) - .build(); - public static final CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder().withZone(Zone.COMMIT).withId(4L) - .withCreatedBy(User.Builder.builder().withId(2L).withFirstname("Robert").build()) - .withCreatedOn(LocalDateTime.MAX).withChangeInfo(CHANGE_INFO).withInitiatives(INITIATIVES) - .withKeyResult( - KeyResultOrdinal.Builder.builder().withCommitZone("Baum").withTargetZone("Wald").withId(9L).build()) - .build(); + public static final CheckIn checkInMetric = CheckInMetric.Builder.builder() + .withValue(30D) + .withConfidence(5) + .withChangeInfo(CHANGE_INFO) + .withInitiatives(INITIATIVES) + .withCreatedBy(User.Builder.builder() + .withId(1L) + .withFirstname("Frank") + .build()) + .withKeyResult(KeyResultMetric.Builder.builder() + .withBaseline(3.0) + .withStretchGoal(6.0) + .withId(8L) + .withObjective(objective) + .build()) + .build(); + public static final CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder() + .withZone(Zone.COMMIT) + .withId(4L) + .withCreatedBy(User.Builder.builder() + .withId(2L) + .withFirstname("Robert") + .build()) + .withCreatedOn(LocalDateTime.MAX) + .withChangeInfo(CHANGE_INFO) + .withInitiatives(INITIATIVES) + .withKeyResult(KeyResultOrdinal.Builder.builder() + .withCommitZone("Baum") + .withTargetZone("Wald") + .withId(9L) + .build()) + .build(); /* Test DTOs */ - public static final CheckInDto checkInMetricDto = new CheckInMetricDto(5L, 1, CHANGE_INFO_1, INITIATIVES_1, 6, 1L, - LocalDateTime.MAX, LocalDateTime.MAX, 46D, true); - public static final CheckInDto checkInOrdinalDto = new CheckInOrdinalDto(4L, 1, CHANGE_INFO_2, INITIATIVES_2, 5, 2L, - LocalDateTime.MAX, LocalDateTime.MAX, Zone.COMMIT, true); + public static final CheckInDto checkInMetricDto = new CheckInMetricDto(5L, + 1, + CHANGE_INFO_1, + INITIATIVES_1, + 6, + 1L, + LocalDateTime.MAX, + LocalDateTime.MAX, + 46D, + true); + public static final CheckInDto checkInOrdinalDto = new CheckInOrdinalDto(4L, + 1, + CHANGE_INFO_2, + INITIATIVES_2, + 5, + 2L, + LocalDateTime.MAX, + LocalDateTime.MAX, + Zone.COMMIT, + true); private CheckInTestHelpers() { } diff --git a/backend/src/test/java/ch/puzzle/okr/test/KeyResultTestHelpers.java b/backend/src/test/java/ch/puzzle/okr/test/KeyResultTestHelpers.java index 27f175ccb1..63d1fb03d9 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/KeyResultTestHelpers.java +++ b/backend/src/test/java/ch/puzzle/okr/test/KeyResultTestHelpers.java @@ -1,5 +1,8 @@ package ch.puzzle.okr.test; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; +import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; + import ch.puzzle.okr.dto.checkin.CheckInDto; import ch.puzzle.okr.dto.checkin.CheckInMetricDto; import ch.puzzle.okr.dto.keyresult.*; @@ -12,14 +15,10 @@ import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.models.keyresult.KeyResultOrdinal; - import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_METRIC; -import static ch.puzzle.okr.Constants.KEY_RESULT_TYPE_ORDINAL; - public class KeyResultTestHelpers { public static final String DESCRIPTION = "Description"; @@ -78,41 +77,115 @@ public class KeyResultTestHelpers { static final String INITIATIVES_2 = "Initiatives2"; static final String CHANGE_INFO_1 = "Changeinfo1"; static final String CHANGE_INFO_2 = "Changeinfo2"; - public static final User user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").build(); - public static final KeyResult metricKeyResult = KeyResultMetric.Builder.builder().withId(5L).withTitle(TITLE) - .build(); - public static final CheckIn checkIn1 = CheckInMetric.Builder.builder().withValue(23D).withId(1L) - .withKeyResult(metricKeyResult).withCreatedBy(user).withCreatedOn(LocalDateTime.MAX) - .withChangeInfo(CHANGE_INFO_1).withInitiatives(INITIATIVES_1).build(); - public static final CheckIn checkIn2 = CheckInMetric.Builder.builder().withValue(12D).withId(4L) - .withKeyResult(metricKeyResult).withCreatedBy(user).withCreatedOn(LocalDateTime.MAX) - .withChangeInfo(CHANGE_INFO_2).withInitiatives(INITIATIVES_2).build(); - public static final CheckInDto checkInDto1 = new CheckInMetricDto(1L, 1, CHANGE_INFO_1, INITIATIVES_1, 6, - metricKeyResult.getId(), LocalDateTime.MAX, LocalDateTime.MAX, 23D, true); - public static final CheckInDto checkInDto2 = new CheckInMetricDto(4L, 1, CHANGE_INFO_2, INITIATIVES_2, 5, - metricKeyResult.getId(), LocalDateTime.MAX, LocalDateTime.MAX, 12D, true); + public static final User user = User.Builder.builder() + .withId(1L) + .withFirstname("Bob") + .withLastname("Kaufmann") + .withEmail("kaufmann@puzzle.ch") + .build(); + public static final KeyResult metricKeyResult = KeyResultMetric.Builder.builder() + .withId(5L) + .withTitle(TITLE) + .build(); + public static final CheckIn checkIn1 = CheckInMetric.Builder.builder() + .withValue(23D) + .withId(1L) + .withKeyResult(metricKeyResult) + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withChangeInfo(CHANGE_INFO_1) + .withInitiatives(INITIATIVES_1) + .build(); + public static final CheckIn checkIn2 = CheckInMetric.Builder.builder() + .withValue(12D) + .withId(4L) + .withKeyResult(metricKeyResult) + .withCreatedBy(user) + .withCreatedOn(LocalDateTime.MAX) + .withChangeInfo(CHANGE_INFO_2) + .withInitiatives(INITIATIVES_2) + .build(); + public static final CheckInDto checkInDto1 = new CheckInMetricDto(1L, + 1, + CHANGE_INFO_1, + INITIATIVES_1, + 6, + metricKeyResult.getId(), + LocalDateTime.MAX, + LocalDateTime.MAX, + 23D, + true); + public static final CheckInDto checkInDto2 = new CheckInMetricDto(4L, + 1, + CHANGE_INFO_2, + INITIATIVES_2, + 5, + metricKeyResult.getId(), + LocalDateTime.MAX, + LocalDateTime.MAX, + 12D, + true); public static final KeyResultUserDto keyResultUserDto = new KeyResultUserDto(1L, FIRSTNAME, LASTNAME); - public static final KeyResultQuarterDto keyResultQuarterDto = new KeyResultQuarterDto(1L, QUARTER_LABEL, - LocalDate.MIN, LocalDate.MAX); - public static final KeyResultLastCheckInMetricDto keyResultLastCheckInDto = new KeyResultLastCheckInMetricDto(1L, 1, - 4.0, 6, LocalDateTime.MIN, CHANGE_INFO_1, INITIATIVES_1); - public static final KeyResultLastCheckInOrdinalDto keyResultLastCheckInOrdinalDto = new KeyResultLastCheckInOrdinalDto( - 1L, 1, LAST_CHECK_IN_ZONE, 6, LocalDateTime.MIN, CHANGE_INFO_2, INITIATIVES_2); + public static final KeyResultQuarterDto keyResultQuarterDto = new KeyResultQuarterDto(1L, + QUARTER_LABEL, + LocalDate.MIN, + LocalDate.MAX); + public static final KeyResultLastCheckInMetricDto keyResultLastCheckInDto = new KeyResultLastCheckInMetricDto(1L, + 1, + 4.0, + 6, + LocalDateTime.MIN, + CHANGE_INFO_1, + INITIATIVES_1); + public static final KeyResultLastCheckInOrdinalDto keyResultLastCheckInOrdinalDto = new KeyResultLastCheckInOrdinalDto(1L, + 1, + LAST_CHECK_IN_ZONE, + 6, + LocalDateTime.MIN, + CHANGE_INFO_2, + INITIATIVES_2); public static final KeyResultObjectiveDto keyResultObjectiveDto = new KeyResultObjectiveDto(1L, - OBJECTIVE_STATE_ONGOING, keyResultQuarterDto); + OBJECTIVE_STATE_ONGOING, + keyResultQuarterDto); - public static final KeyResultMetricDto keyResultMetricDto = new KeyResultMetricDto(5L, 1, KEY_RESULT_TYPE_METRIC, - TITLE, DESCRIPTION, 1.0, 5.0, KEY_RESULT_UNIT, keyResultUserDto, keyResultObjectiveDto, - keyResultLastCheckInDto, LocalDateTime.MIN, LocalDateTime.MAX, true, List.of()); - public static final KeyResultOrdinalDto keyResultOrdinalDto = new KeyResultOrdinalDto(5L, 1, - KEY_RESULT_TYPE_ORDINAL, TITLE, DESCRIPTION, COMMIT_ZONE, TARGET_ZONE, STRETCH_ZONE, keyResultUserDto, - keyResultObjectiveDto, keyResultLastCheckInOrdinalDto, LocalDateTime.MIN, LocalDateTime.MAX, true, - List.of()); + public static final KeyResultMetricDto keyResultMetricDto = new KeyResultMetricDto(5L, + 1, + KEY_RESULT_TYPE_METRIC, + TITLE, + DESCRIPTION, + 1.0, + 5.0, + KEY_RESULT_UNIT, + keyResultUserDto, + keyResultObjectiveDto, + keyResultLastCheckInDto, + LocalDateTime.MIN, + LocalDateTime.MAX, + true, + List.of()); + public static final KeyResultOrdinalDto keyResultOrdinalDto = new KeyResultOrdinalDto(5L, + 1, + KEY_RESULT_TYPE_ORDINAL, + TITLE, + DESCRIPTION, + COMMIT_ZONE, + TARGET_ZONE, + STRETCH_ZONE, + keyResultUserDto, + keyResultObjectiveDto, + keyResultLastCheckInOrdinalDto, + LocalDateTime.MIN, + LocalDateTime.MAX, + true, + List.of()); public static final Objective objective = Objective.Builder.builder().withId(5L).withTitle("Objective 1").build(); - public static final KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder().withId(3L) - .withTitle("Keyresult 2").withOwner(user).withObjective(objective).build(); + public static final KeyResult ordinalKeyResult = KeyResultOrdinal.Builder.builder() + .withId(3L) + .withTitle("Keyresult 2") + .withOwner(user) + .withObjective(objective) + .build(); public static final String CREATE_BODY_METRIC = """ { diff --git a/backend/src/test/java/ch/puzzle/okr/test/SpringIntegrationTest.java b/backend/src/test/java/ch/puzzle/okr/test/SpringIntegrationTest.java index 2fe500d842..7c1834fd9d 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/SpringIntegrationTest.java +++ b/backend/src/test/java/ch/puzzle/okr/test/SpringIntegrationTest.java @@ -1,12 +1,11 @@ package ch.puzzle.okr.test; +import java.lang.annotation.*; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; -import java.lang.annotation.*; - -@Target({ ElementType.TYPE }) +@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited diff --git a/backend/src/test/java/ch/puzzle/okr/test/TestHelper.java b/backend/src/test/java/ch/puzzle/okr/test/TestHelper.java index 86bb30b3f7..a87f940c09 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/TestHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/test/TestHelper.java @@ -5,8 +5,6 @@ import ch.puzzle.okr.models.User; import ch.puzzle.okr.models.UserTeam; import ch.puzzle.okr.models.authorization.AuthorizationUser; -import org.springframework.security.oauth2.jwt.Jwt; - import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; @@ -14,6 +12,7 @@ import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.springframework.security.oauth2.jwt.Jwt; public class TestHelper { private TestHelper() { @@ -26,8 +25,12 @@ private TestHelper() { private static final String EMAIL = "kaufmann@puzzle.ch"; public static User defaultUser(Long id) { - return User.Builder.builder().withId(id).withFirstname(FIRSTNAME).withLastname(LASTNAME).withEmail(EMAIL) - .build(); + return User.Builder.builder() + .withId(id) + .withFirstname(FIRSTNAME) + .withLastname(LASTNAME) + .withEmail(EMAIL) + .build(); } public static User defaultOkrChampion(Long id) { @@ -39,11 +42,15 @@ public static User defaultOkrChampion(Long id) { public static User defaultUserWithTeams(Long userId, List adminTeams, List memberTeams) { var user = defaultUser(userId); var adminUserTeams = adminTeams.stream() - .map(t -> UserTeam.Builder.builder().withTeamAdmin(true).withTeam(t).withUser(user).build()); + .map(t -> UserTeam.Builder.builder() + .withTeamAdmin(true) + .withTeam(t) + .withUser(user) + .build()); var memberUserTeams = memberTeams.stream() - .map(t -> UserTeam.Builder.builder().withTeam(t).withUser(user).build()); - user.setUserTeamList( - Stream.concat(adminUserTeams, memberUserTeams).collect(Collectors.toCollection(ArrayList::new))); + .map(t -> UserTeam.Builder.builder().withTeam(t).withUser(user).build()); + user.setUserTeamList(Stream.concat(adminUserTeams, memberUserTeams) + .collect(Collectors.toCollection(ArrayList::new))); return user; } @@ -60,19 +67,22 @@ public static AuthorizationUser defaultAuthorizationUser() { } public static AuthorizationUser mockAuthorizationUser(User user) { - return mockAuthorizationUser(user.getId(), user.getFirstname(), user.getLastname(), user.getEmail(), - user.isOkrChampion()); + return mockAuthorizationUser(user.getId(), + user.getFirstname(), + user.getLastname(), + user.getEmail(), + user.isOkrChampion()); } public static AuthorizationUser mockAuthorizationUser(Long id, String firstname, String lastname, String email, - boolean isOkrChampion) { + boolean isOkrChampion) { User user = User.Builder.builder() // - .withId(id) // - .withFirstname(firstname) // - .withLastname(lastname) // - .withEmail(email) // - .withOkrChampion(isOkrChampion) // - .build(); + .withId(id) // + .withFirstname(firstname) // + .withLastname(lastname) // + .withEmail(email) // + .withOkrChampion(isOkrChampion) // + .build(); user.setUserTeamList(List.of(defaultUserTeam(1L, user))); return new AuthorizationUser(user); } diff --git a/backend/src/test/java/ch/puzzle/okr/test/dto/builder/ObjectiveDtoBuilder.java b/backend/src/test/java/ch/puzzle/okr/test/dto/builder/ObjectiveDtoBuilder.java index b3f7e90638..c8a2b55344 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/dto/builder/ObjectiveDtoBuilder.java +++ b/backend/src/test/java/ch/puzzle/okr/test/dto/builder/ObjectiveDtoBuilder.java @@ -2,7 +2,6 @@ import ch.puzzle.okr.dto.ObjectiveDto; import ch.puzzle.okr.models.State; - import java.time.LocalDateTime; public class ObjectiveDtoBuilder { @@ -81,8 +80,17 @@ public ObjectiveDtoBuilder withWriteable(boolean writeable) { } public ObjectiveDto build() { - return new ObjectiveDto(id, version, title, teamId, quarterId, quarterLabel, description, state, createdOn, - modifiedOn, writeable); + return new ObjectiveDto(id, + version, + title, + teamId, + quarterId, + quarterLabel, + description, + state, + createdOn, + modifiedOn, + writeable); } } diff --git a/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeChecker.java b/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeChecker.java index d7ec5e387a..7b997bd5d4 100644 --- a/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeChecker.java +++ b/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeChecker.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.util.quarter.check; import ch.puzzle.okr.models.Quarter; - import java.time.LocalDate; public class QuarterRangeChecker { diff --git a/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeCheckerTest.java b/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeCheckerTest.java index 8dbf76d0a1..6e373a043e 100644 --- a/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeCheckerTest.java +++ b/backend/src/test/java/ch/puzzle/okr/util/quarter/check/QuarterRangeCheckerTest.java @@ -1,14 +1,13 @@ package ch.puzzle.okr.util.quarter.check; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import ch.puzzle.okr.models.Quarter; +import java.time.LocalDate; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.time.LocalDate; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - public class QuarterRangeCheckerTest { @DisplayName("nowIsInQuarter() should return false if Quarter is null") @@ -104,8 +103,8 @@ void nowIsInQuarterShouldReturnFalseIfNowIsAfterQuarterEndDate() { private Quarter quarter(LocalDate startDate, LocalDate endDate) { return Quarter.Builder.builder() // - .withStartDate(startDate) // - .withEndDate(endDate) // - .build(); + .withStartDate(startDate) // + .withEndDate(endDate) // + .build(); } } diff --git a/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuarterLabelTest.java b/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuarterLabelTest.java index 8d3d466546..209113e547 100644 --- a/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuarterLabelTest.java +++ b/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuarterLabelTest.java @@ -1,15 +1,14 @@ package ch.puzzle.okr.util.quarter.generate; +import static org.junit.jupiter.api.Assertions.*; + +import java.time.LocalDate; +import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.time.LocalDate; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.*; - public class QuarterLabelTest { @DisplayName("label() should return label with year and quarter info") @@ -22,33 +21,33 @@ void labelShouldReturnLabelWithYearAndQuarterInfo(LocalDate date, String expecte private static Stream datesAndLabels() { return Stream.of( // - Arguments.of(LocalDate.of(2024, 7, 1), "GJ 24/25-Q1"), - Arguments.of(LocalDate.of(2024, 7, 2), "GJ 24/25-Q1"), - Arguments.of(LocalDate.of(2024, 7, 15), "GJ 24/25-Q1"), - Arguments.of(LocalDate.of(2024, 9, 15), "GJ 24/25-Q1"), - Arguments.of(LocalDate.of(2024, 9, 29), "GJ 24/25-Q1"), - Arguments.of(LocalDate.of(2024, 9, 30), "GJ 24/25-Q1"), - - Arguments.of(LocalDate.of(2024, 10, 1), "GJ 24/25-Q2"), - Arguments.of(LocalDate.of(2024, 10, 2), "GJ 24/25-Q2"), - Arguments.of(LocalDate.of(2024, 10, 15), "GJ 24/25-Q2"), - Arguments.of(LocalDate.of(2024, 12, 15), "GJ 24/25-Q2"), - Arguments.of(LocalDate.of(2024, 12, 30), "GJ 24/25-Q2"), - Arguments.of(LocalDate.of(2024, 12, 31), "GJ 24/25-Q2"), - - Arguments.of(LocalDate.of(2024, 1, 1), "GJ 23/24-Q3"), - Arguments.of(LocalDate.of(2024, 1, 2), "GJ 23/24-Q3"), - Arguments.of(LocalDate.of(2024, 1, 15), "GJ 23/24-Q3"), - Arguments.of(LocalDate.of(2024, 3, 15), "GJ 23/24-Q3"), - Arguments.of(LocalDate.of(2024, 3, 30), "GJ 23/24-Q3"), - Arguments.of(LocalDate.of(2024, 3, 31), "GJ 23/24-Q3"), - - Arguments.of(LocalDate.of(2024, 4, 1), "GJ 23/24-Q4"), - Arguments.of(LocalDate.of(2024, 4, 2), "GJ 23/24-Q4"), - Arguments.of(LocalDate.of(2024, 4, 15), "GJ 23/24-Q4"), - Arguments.of(LocalDate.of(2024, 6, 15), "GJ 23/24-Q4"), - Arguments.of(LocalDate.of(2024, 6, 29), "GJ 23/24-Q4"), - Arguments.of(LocalDate.of(2024, 6, 30), "GJ 23/24-Q4")); + Arguments.of(LocalDate.of(2024, 7, 1), "GJ 24/25-Q1"), + Arguments.of(LocalDate.of(2024, 7, 2), "GJ 24/25-Q1"), + Arguments.of(LocalDate.of(2024, 7, 15), "GJ 24/25-Q1"), + Arguments.of(LocalDate.of(2024, 9, 15), "GJ 24/25-Q1"), + Arguments.of(LocalDate.of(2024, 9, 29), "GJ 24/25-Q1"), + Arguments.of(LocalDate.of(2024, 9, 30), "GJ 24/25-Q1"), + + Arguments.of(LocalDate.of(2024, 10, 1), "GJ 24/25-Q2"), + Arguments.of(LocalDate.of(2024, 10, 2), "GJ 24/25-Q2"), + Arguments.of(LocalDate.of(2024, 10, 15), "GJ 24/25-Q2"), + Arguments.of(LocalDate.of(2024, 12, 15), "GJ 24/25-Q2"), + Arguments.of(LocalDate.of(2024, 12, 30), "GJ 24/25-Q2"), + Arguments.of(LocalDate.of(2024, 12, 31), "GJ 24/25-Q2"), + + Arguments.of(LocalDate.of(2024, 1, 1), "GJ 23/24-Q3"), + Arguments.of(LocalDate.of(2024, 1, 2), "GJ 23/24-Q3"), + Arguments.of(LocalDate.of(2024, 1, 15), "GJ 23/24-Q3"), + Arguments.of(LocalDate.of(2024, 3, 15), "GJ 23/24-Q3"), + Arguments.of(LocalDate.of(2024, 3, 30), "GJ 23/24-Q3"), + Arguments.of(LocalDate.of(2024, 3, 31), "GJ 23/24-Q3"), + + Arguments.of(LocalDate.of(2024, 4, 1), "GJ 23/24-Q4"), + Arguments.of(LocalDate.of(2024, 4, 2), "GJ 23/24-Q4"), + Arguments.of(LocalDate.of(2024, 4, 15), "GJ 23/24-Q4"), + Arguments.of(LocalDate.of(2024, 6, 15), "GJ 23/24-Q4"), + Arguments.of(LocalDate.of(2024, 6, 29), "GJ 23/24-Q4"), + Arguments.of(LocalDate.of(2024, 6, 30), "GJ 23/24-Q4")); } } diff --git a/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuartersTest.java b/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuartersTest.java index 43d7aca711..9d849a0340 100644 --- a/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuartersTest.java +++ b/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/QuartersTest.java @@ -1,24 +1,23 @@ package ch.puzzle.okr.util.quarter.generate; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.time.LocalDate; +import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.time.LocalDate; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - public class QuartersTest { @DisplayName("currentQuarter() should find current quarter for now and 12 months in future") @ParameterizedTest @MethodSource("futureDatesAndLabels") void currentQuarterShouldFindCurrentQuarterForNowAnd12MonthsInFuture(LocalDate date, String expectedLabelFirstYear, - String expectedLabelSecondYear) { + String expectedLabelSecondYear) { // arrange Quarters nowQuarters = new Quarters(date.getYear()); @@ -37,65 +36,65 @@ void currentQuarterShouldFindCurrentQuarterForNowAnd12MonthsInFuture(LocalDate d private static Stream futureDatesAndLabels() { return Stream.of( // - Arguments.of( // - LocalDate.of(2024, 7, 15), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), - Arguments.of( // - LocalDate.of(2024, 8, 15), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), - Arguments.of( // - LocalDate.of(2024, 9, 15), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), - Arguments.of( // - LocalDate.of(2024, 10, 15), // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), - Arguments.of( // - LocalDate.of(2024, 11, 15), // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), - Arguments.of( // - LocalDate.of(2024, 12, 15), // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), - Arguments.of( // - LocalDate.of(2025, 1, 15), // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), - Arguments.of( // - LocalDate.of(2025, 2, 15), // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), - Arguments.of( // - LocalDate.of(2025, 3, 15), // - "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), - Arguments.of( // - LocalDate.of(2025, 4, 15), // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // - "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), - Arguments.of( // - LocalDate.of(2025, 5, 15), // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // - "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), - Arguments.of( // - LocalDate.of(2025, 6, 15), // - "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // - "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), - Arguments.of( // - LocalDate.of(2025, 7, 15), // - "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')", // - "('GJ 25/26-Q2', '2025-10-01', '2025-12-31')")); + Arguments.of( // + LocalDate.of(2024, 7, 15), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), + Arguments.of( // + LocalDate.of(2024, 8, 15), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), + Arguments.of( // + LocalDate.of(2024, 9, 15), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')"), + Arguments.of( // + LocalDate.of(2024, 10, 15), // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), + Arguments.of( // + LocalDate.of(2024, 11, 15), // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), + Arguments.of( // + LocalDate.of(2024, 12, 15), // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')", // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')"), + Arguments.of( // + LocalDate.of(2025, 1, 15), // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), + Arguments.of( // + LocalDate.of(2025, 2, 15), // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), + Arguments.of( // + LocalDate.of(2025, 3, 15), // + "('GJ 24/25-Q3', '2025-01-01', '2025-03-31')", // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')"), + Arguments.of( // + LocalDate.of(2025, 4, 15), // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // + "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), + Arguments.of( // + LocalDate.of(2025, 5, 15), // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // + "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), + Arguments.of( // + LocalDate.of(2025, 6, 15), // + "('GJ 24/25-Q4', '2025-04-01', '2025-06-30')", // + "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')"), + Arguments.of( // + LocalDate.of(2025, 7, 15), // + "('GJ 25/26-Q1', '2025-07-01', '2025-09-30')", // + "('GJ 25/26-Q2', '2025-10-01', '2025-12-31')")); } @DisplayName("currentQuarter() should find current quarter for now and 7 months in past") @ParameterizedTest @MethodSource("pastDatesAndLabels") void currentQuarterShouldFindCurrentQuarterForNowAnd7MonthsInPast(LocalDate date, String expectedLabelFirstYear, - String expectedLabelSecondYear) { + String expectedLabelSecondYear) { // arrange Quarters nowQuarters = new Quarters(date.getYear()); @@ -114,38 +113,38 @@ void currentQuarterShouldFindCurrentQuarterForNowAnd7MonthsInPast(LocalDate date private static Stream pastDatesAndLabels() { return Stream.of( // - Arguments.of( // - LocalDate.of(2023, 12, 15), // - "('GJ 23/24-Q2', '2023-10-01', '2023-12-31')", // - "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')"), - Arguments.of( // - LocalDate.of(2024, 1, 15), // - "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), - Arguments.of( // - LocalDate.of(2024, 2, 15), // - "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), - Arguments.of( // - LocalDate.of(2024, 3, 15), // - "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), - Arguments.of( // - LocalDate.of(2024, 4, 15), // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), - Arguments.of( // - LocalDate.of(2024, 5, 15), // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), - Arguments.of( // - LocalDate.of(2024, 6, 15), // - "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), - Arguments.of( // - LocalDate.of(2024, 7, 15), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // - "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')")); + Arguments.of( // + LocalDate.of(2023, 12, 15), // + "('GJ 23/24-Q2', '2023-10-01', '2023-12-31')", // + "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')"), + Arguments.of( // + LocalDate.of(2024, 1, 15), // + "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), + Arguments.of( // + LocalDate.of(2024, 2, 15), // + "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), + Arguments.of( // + LocalDate.of(2024, 3, 15), // + "('GJ 23/24-Q3', '2024-01-01', '2024-03-31')", // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')"), + Arguments.of( // + LocalDate.of(2024, 4, 15), // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), + Arguments.of( // + LocalDate.of(2024, 5, 15), // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), + Arguments.of( // + LocalDate.of(2024, 6, 15), // + "('GJ 23/24-Q4', '2024-04-01', '2024-06-30')", // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), + Arguments.of( // + LocalDate.of(2024, 7, 15), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')", // + "('GJ 24/25-Q2', '2024-10-01', '2024-12-31')")); } @DisplayName("currentQuarter() should throw exception if no matching quarter is found for now") @@ -159,7 +158,7 @@ void currentQuarterShouldThrowExceptionIfNoMatchingQuarterIsFoundForNow() { // act RuntimeException exception = assertThrows(RuntimeException.class, - () -> allQuartersOfCurrentYear.currentQuarter(in2Years)); + () -> allQuartersOfCurrentYear.currentQuarter(in2Years)); // assert assertEquals(RuntimeException.class, exception.getClass()); @@ -182,12 +181,12 @@ void currentQuarterShouldFindCurrentQuarterForBoundaryDates(LocalDate date, Stri private static Stream boundaryDatesAndLabels() { return Stream.of( // - Arguments.of( // - LocalDate.of(2024, 7, 1), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), // - Arguments.of( // - LocalDate.of(2024, 9, 30), // - "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')") // + Arguments.of( // + LocalDate.of(2024, 7, 1), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')"), // + Arguments.of( // + LocalDate.of(2024, 9, 30), // + "('GJ 24/25-Q1', '2024-07-01', '2024-09-30')") // ); } } diff --git a/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunctionTest.java b/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunctionTest.java index 232c7c1337..41fa7e0cfa 100644 --- a/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunctionTest.java +++ b/backend/src/test/java/ch/puzzle/okr/util/quarter/generate/h2/QuarterFunctionTest.java @@ -1,11 +1,11 @@ package ch.puzzle.okr.util.quarter.generate.h2; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - import static ch.puzzle.okr.util.quarter.generate.h2.QuarterFunction.*; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + public class QuarterFunctionTest { @DisplayName("QuarterFunction should return correct current quarter data") @@ -16,9 +16,9 @@ void quarterFunctionShouldReturnCorrectCurrentQuarterData() { // act String currentQuarter = "(2, " // - + currentQuarterLabel() + ", " // - + currentQuarterStartDate() + ", " // - + currentQuarterEndDate() + ")"; + + currentQuarterLabel() + ", " // + + currentQuarterStartDate() + ", " // + + currentQuarterEndDate() + ")"; // assert String expectedCurrent = "(2, GJ 24/25-Q2, 2024-10-01, 2024-12-31)"; @@ -33,9 +33,9 @@ void quarterFunctionShouldReturnCorrectNextQuarterData() { // act String nextQuarter = "(3, " // - + nextQuarterLabel() + ", " // - + nextQuarterStartDate() + ", " // - + nextQuarterEndDate() + ")"; + + nextQuarterLabel() + ", " // + + nextQuarterStartDate() + ", " // + + nextQuarterEndDate() + ")"; // assert String expectedNext = "(3, GJ 24/25-Q3, 2025-01-01, 2025-03-31)";