From 0d052c6b47357efb7f6d6bffad388d60c9b0e016 Mon Sep 17 00:00:00 2001 From: Yanick Minder Date: Thu, 19 Dec 2024 10:34:43 +0100 Subject: [PATCH] run backend formatter --- .../main/java/ch/puzzle/okr/Constants.java | 17 +- .../src/main/java/ch/puzzle/okr/ErrorKey.java | 22 +- .../java/ch/puzzle/okr/ForwardFilter.java | 5 +- .../ch/puzzle/okr/OkrErrorAttributes.java | 3 +- .../ch/puzzle/okr/OpenAPI30Configuration.java | 12 +- .../java/ch/puzzle/okr/SecurityConfig.java | 56 +-- .../java/ch/puzzle/okr/UserKeyGenerator.java | 3 +- .../okr/controller/ActionController.java | 7 +- .../okr/controller/AlignmentController.java | 18 +- .../okr/controller/CheckInController.java | 16 +- .../controller/ClientConfigController.java | 3 +- .../okr/controller/CompletedController.java | 2 +- .../okr/controller/KeyResultController.java | 27 +- .../okr/controller/ObjectiveController.java | 54 ++- .../okr/controller/OverviewController.java | 19 +- .../okr/controller/QuarterController.java | 4 +- .../puzzle/okr/controller/TeamController.java | 38 +- .../puzzle/okr/controller/UserController.java | 22 +- .../okr/deserializer/CheckInDeserializer.java | 9 +- .../okr/deserializer/DeserializerHelper.java | 8 +- .../deserializer/KeyResultDeserializer.java | 5 +- .../puzzle/okr/dto/DuplicateObjectiveDto.java | 1 - .../main/java/ch/puzzle/okr/dto/ErrorDto.java | 1 - .../java/ch/puzzle/okr/dto/ObjectiveDto.java | 1 - .../okr/dto/checkin/CheckInMetricDto.java | 5 +- .../okr/dto/checkin/CheckInOrdinalDto.java | 5 +- .../okr/dto/keyresult/KeyResultDto.java | 1 - .../KeyResultLastCheckInOrdinalDto.java | 1 - .../okr/dto/keyresult/KeyResultMetricDto.java | 5 +- .../dto/keyresult/KeyResultOrdinalDto.java | 5 +- .../overview/OverviewKeyResultOrdinalDto.java | 4 +- .../OverviewLastCheckInMetricDto.java | 4 +- .../OverviewLastCheckInOrdinalDto.java | 4 +- .../dto/overview/OverviewObjectiveDto.java | 1 - .../exception/OkrResponseStatusException.java | 11 +- .../ch/puzzle/okr/mapper/ActionMapper.java | 27 +- .../okr/mapper/AlignmentSelectionMapper.java | 15 +- .../ch/puzzle/okr/mapper/CompletedMapper.java | 9 +- .../ch/puzzle/okr/mapper/ObjectiveMapper.java | 35 +- .../ch/puzzle/okr/mapper/OverviewMapper.java | 62 ++- .../java/ch/puzzle/okr/mapper/TeamMapper.java | 6 +- .../java/ch/puzzle/okr/mapper/UserMapper.java | 21 +- .../puzzle/okr/mapper/UserOkrDataMapper.java | 12 +- .../okr/mapper/checkin/CheckInMapper.java | 8 +- .../mapper/checkin/CheckInMetricMapper.java | 21 +- .../mapper/checkin/CheckInOrdinalMapper.java | 22 +- .../okr/mapper/keyresult/KeyResultMapper.java | 15 +- .../keyresult/KeyResultMetricMapper.java | 69 +-- .../keyresult/KeyResultOrdinalMapper.java | 70 +-- .../java/ch/puzzle/okr/models/Action.java | 59 +-- .../java/ch/puzzle/okr/models/Completed.java | 28 +- .../java/ch/puzzle/okr/models/Objective.java | 119 ++--- .../java/ch/puzzle/okr/models/Quarter.java | 33 +- .../main/java/ch/puzzle/okr/models/State.java | 5 +- .../main/java/ch/puzzle/okr/models/Team.java | 35 +- .../main/java/ch/puzzle/okr/models/Unit.java | 6 +- .../main/java/ch/puzzle/okr/models/User.java | 55 +-- .../java/ch/puzzle/okr/models/UserTeam.java | 45 +- .../okr/models/alignment/Alignment.java | 19 +- .../models/alignment/AlignmentSelection.java | 37 +- .../alignment/AlignmentSelectionId.java | 9 +- .../models/alignment/KeyResultAlignment.java | 9 +- .../models/alignment/ObjectiveAlignment.java | 9 +- .../authorization/AuthorizationUser.java | 5 +- .../ch/puzzle/okr/models/checkin/CheckIn.java | 105 ++-- .../okr/models/checkin/CheckInMetric.java | 13 +- .../okr/models/checkin/CheckInOrdinal.java | 13 +- .../ch/puzzle/okr/models/checkin/Zone.java | 5 +- .../okr/models/keyresult/KeyResult.java | 110 ++--- .../okr/models/keyresult/KeyResultMetric.java | 35 +- .../models/keyresult/KeyResultOrdinal.java | 35 +- .../keyresult/KeyResultWithActionList.java | 1 - .../puzzle/okr/models/overview/Overview.java | 107 ++--- .../okr/models/overview/OverviewId.java | 21 +- ...FlywayMultitenantMigrationInitializer.java | 10 +- .../okr/multitenancy/HibernateContext.java | 7 +- .../SchemaMultiTenantConnectionProvider.java | 34 +- .../multitenancy/TenantConfigProvider.java | 68 ++- .../okr/multitenancy/TenantContext.java | 3 +- .../TenantClientCustomizationProvider.java | 52 +- .../okr/repository/ActionRepository.java | 3 +- .../okr/repository/AlignmentRepository.java | 3 +- .../AlignmentSelectionRepository.java | 5 +- .../okr/repository/CheckInRepository.java | 3 +- .../okr/repository/KeyResultRepository.java | 3 +- .../okr/repository/ObjectiveRepository.java | 3 +- .../okr/repository/QuarterRepository.java | 5 +- .../puzzle/okr/repository/TeamRepository.java | 3 +- .../puzzle/okr/repository/UserRepository.java | 3 +- .../ch/puzzle/okr/security/JwtHelper.java | 62 +-- .../okr/security/TenantJWSKeySelector.java | 12 +- .../security/TenantJwtIssuerValidator.java | 8 +- .../okr/security/helper/ClaimHelper.java | 9 +- .../okr/security/helper/JwtStatusLogger.java | 25 +- .../okr/security/helper/TokenHelper.java | 7 +- .../ch/puzzle/okr/service/CacheService.java | 4 +- .../ActionAuthorizationService.java | 5 +- .../AuthorizationRegistrationService.java | 6 +- .../authorization/AuthorizationService.java | 120 +++-- .../AuthorizationServiceBase.java | 10 +- .../CheckInAuthorizationService.java | 2 +- .../CompletedAuthorizationService.java | 2 +- .../KeyResultAuthorizationService.java | 12 +- .../ObjectiveAuthorizationService.java | 6 +- .../OverviewAuthorizationService.java | 19 +- .../TeamAuthorizationService.java | 11 +- .../UserAuthorizationService.java | 25 +- .../business/ActionBusinessService.java | 3 +- .../business/AlignmentBusinessService.java | 5 +- .../AlignmentSelectionBusinessService.java | 10 +- .../business/CheckInBusinessService.java | 5 +- .../business/CompletedBusinessService.java | 2 +- .../business/KeyResultBusinessService.java | 27 +- .../business/ObjectiveBusinessService.java | 36 +- .../business/OverviewBusinessService.java | 11 +- .../business/QuarterBusinessService.java | 41 +- .../service/business/TeamBusinessService.java | 36 +- .../service/business/UserBusinessService.java | 18 +- .../clientconfig/ClientConfigService.java | 43 +- .../persistence/ActionPersistenceService.java | 11 +- .../AlignmentPersistenceService.java | 11 +- .../AlignmentSelectionPersistenceService.java | 3 +- .../persistence/AuthorizationCriteria.java | 28 +- .../CheckInPersistenceService.java | 11 +- .../CompletedPersistenceService.java | 8 +- .../KeyResultPersistenceService.java | 14 +- .../ObjectivePersistenceService.java | 26 +- .../OverviewPersistenceService.java | 9 +- .../service/persistence/PersistenceBase.java | 27 +- .../QuarterPersistenceService.java | 15 +- .../persistence/TeamPersistenceService.java | 11 +- .../persistence/UserPersistenceService.java | 11 +- .../UserTeamPersistenceService.java | 11 +- .../validation/ActionValidationService.java | 17 +- .../AlignmentValidationService.java | 3 +- .../validation/CheckInValidationService.java | 13 +- .../CompletedValidationService.java | 3 +- .../KeyResultValidationService.java | 13 +- .../ObjectiveValidationService.java | 40 +- .../validation/OverviewValidationService.java | 2 +- .../validation/QuarterValidationService.java | 30 +- .../validation/TeamValidationService.java | 22 +- .../validation/UserValidationService.java | 4 +- .../service/validation/ValidationBase.java | 33 +- .../util/quarter/generate/QuarterData.java | 12 +- .../util/quarter/generate/QuarterLabel.java | 12 +- .../okr/util/quarter/generate/Quarters.java | 6 +- .../quarter/generate/h2/QuarterFunction.java | 10 +- .../java/ch/puzzle/okr/ForwardFilterTest.java | 8 +- .../puzzle/okr/SpringCachingConfigTest.java | 14 +- .../ch/puzzle/okr/UserKeyGeneratorTest.java | 7 +- .../okr/architecture/OkrArchitectureTest.java | 164 +++++-- .../okr/controller/ActionControllerIT.java | 48 +- .../okr/controller/AlignmentControllerIT.java | 113 +++-- .../okr/controller/CacheControllerIT.java | 16 +- .../okr/controller/CheckInControllerIT.java | 110 +++-- .../controller/ClientConfigControllerIT.java | 28 +- .../okr/controller/CompletedControllerIT.java | 46 +- .../okr/controller/KeyResultControllerIT.java | 233 ++++++--- .../okr/controller/ObjectiveControllerIT.java | 222 ++++++--- .../okr/controller/OverviewControllerIT.java | 181 ++++--- .../okr/controller/QuarterControllerIT.java | 64 ++- .../okr/controller/TeamControllerIT.java | 120 +++-- .../okr/controller/UserControllerIT.java | 97 ++-- .../deserializer/CheckInDeserializerTest.java | 27 +- .../deserializer/DeserializerHelperTest.java | 13 +- .../KeyResultDeserializerTest.java | 21 +- .../puzzle/okr/mapper/ActionMapperTest.java | 29 +- .../mapper/AlignmentSelectionMapperTest.java | 129 +++-- .../okr/mapper/CompletedMapperTest.java | 20 +- .../okr/mapper/ObjectiveMapperTest.java | 17 +- .../puzzle/okr/mapper/OverviewMapperTest.java | 247 +++++++--- .../ch/puzzle/okr/mapper/TeamMapperTest.java | 7 +- .../ch/puzzle/okr/mapper/UserMapperTest.java | 23 +- .../okr/mapper/checkin/CheckInMapperTest.java | 16 +- .../checkin/CheckInMetricMapperTest.java | 14 +- .../checkin/CheckInOrdinalMapperTest.java | 14 +- .../mapper/checkin/helper/AssertHelper.java | 6 +- .../checkin/helper/TestDataConstants.java | 1 - .../checkin/helper/TestDataDtoHelper.java | 40 +- .../mapper/checkin/helper/TestDataHelper.java | 16 +- .../mapper/keyresult/KeyResultMapperTest.java | 41 +- .../keyresult/KeyResultMetricMapperTest.java | 23 +- .../keyresult/KeyResultOrdinalMapperTest.java | 23 +- .../mapper/keyresult/helper/AssertHelper.java | 30 +- .../keyresult/helper/TestDataConstants.java | 1 - .../keyresult/helper/TestDataDtoHelper.java | 119 ++--- .../keyresult/helper/TestDataHelper.java | 37 +- .../authorization/AuthorizationUserTest.java | 21 +- .../okr/models/keyresult/KeyResultTest.java | 12 +- ...rrentTenantIdentifierResolverImplTest.java | 6 +- ...ayMultitenantMigrationInitializerTest.java | 59 ++- .../multitenancy/HibernateContextTest.java | 38 +- ...TenantConnectionProviderInternalsTest.java | 11 +- ...hemaMultiTenantConnectionProviderTest.java | 13 +- .../TenantConfigProviderTestIT.java | 15 +- ...TenantClientCustomizationProviderTest.java | 14 +- ...nantClientCustomizationProviderTestIT.java | 16 +- .../security/AuthenticationEventsTest.java | 10 +- .../ch/puzzle/okr/security/JwtHelperTest.java | 72 +-- .../security/TenantJWSKeySelectorTest.java | 30 +- .../TenantJwtIssuerValidatorTest.java | 33 +- .../okr/security/helper/ClaimHelperTest.java | 19 +- .../okr/security/helper/TokenHelperTest.java | 17 +- .../okr/security/helper/UrlHelperTest.java | 7 +- .../ActionAuthorizationServiceTest.java | 52 +- .../AuthorizationRegistrationServiceIT.java | 41 +- .../AuthorizationServiceTest.java | 190 ++++---- .../CheckInAuthorizationServiceTest.java | 35 +- .../CompletedAuthorizationServiceTest.java | 33 +- .../KeyResultAuthorizationServiceTest.java | 55 ++- .../ObjectiveAuthorizationServiceTest.java | 74 +-- .../OverviewAuthorizationServiceTest.java | 32 +- .../TeamAuthorizationServiceTest.java | 40 +- .../UserAuthorizationServiceTest.java | 15 +- .../authorization/UserUpdateHelperTest.java | 24 +- .../business/ActionBusinessServiceTest.java | 81 +++- .../AlignmentBusinessServiceTest.java | 42 +- ...AlignmentSelectionBusinessServiceTest.java | 24 +- .../business/CheckInBusinessServiceTest.java | 60 ++- .../CompletedBusinessServiceTest.java | 38 +- .../business/KeyResultBusinessServiceIT.java | 118 +++-- .../KeyResultBusinessServiceTest.java | 155 ++++-- .../ObjectiveBusinessServiceTest.java | 135 ++++-- .../business/OverviewBusinessServiceTest.java | 140 +++--- .../business/QuarterBusinessServiceTest.java | 105 ++-- .../business/TeamBusinessServiceTest.java | 83 +++- .../business/UserBusinessServiceTest.java | 65 ++- .../clientconfig/ClientConfigServiceIT.java | 20 +- .../clientconfig/ClientConfigServiceTest.java | 48 +- .../ActionPersistenceServiceIT.java | 31 +- .../AlignmentPersistenceServiceIT.java | 30 +- ...lignmentSelectionPersistenceServiceIT.java | 43 +- .../persistence/AuthorizationCriteriaIT.java | 23 +- .../AuthorizationCriteriaParametersTest.java | 105 ++-- .../AuthorizationCriteriaTest.java | 39 +- .../CheckInPersistenceServiceIT.java | 17 +- .../CompletedPersistenceServiceIT.java | 31 +- .../KeyResultPersistenceServiceIT.java | 81 ++-- .../ObjectivePersistenceServiceIT.java | 101 ++-- .../OverviewPersistenceServiceIT.java | 74 +-- .../persistence/PersistenceBaseTestIT.java | 38 +- .../QuarterPersistenceServiceIT.java | 31 +- .../persistence/TeamPersistenceServiceIT.java | 9 +- .../persistence/UserPersistenceServiceIT.java | 38 +- .../UserTeamPersistenceServiceIT.java | 3 +- .../ActionValidationServiceTest.java | 249 ++++++---- .../AlignmentValidationServiceTest.java | 19 +- .../CheckInValidationServiceTest.java | 223 ++++++--- .../CompletedValidationServiceTest.java | 80 ++-- .../KeyResultValidationServiceTest.java | 225 +++++---- .../ObjectiveValidationServiceTest.java | 447 +++++++++++++----- .../OverviewValidationServiceTest.java | 10 +- .../QuarterValidationServiceTest.java | 39 +- .../validation/TeamValidationServiceTest.java | 55 ++- .../validation/UserValidationServiceTest.java | 256 ++++++---- .../validation/ValidationBaseTest.java | 51 +- .../ch/puzzle/okr/test/AssertionHelper.java | 16 +- .../puzzle/okr/test/CheckInTestHelpers.java | 63 ++- .../puzzle/okr/test/KeyResultTestHelpers.java | 144 ++++-- .../okr/test/SpringIntegrationTest.java | 3 +- .../java/ch/puzzle/okr/test/TestHelper.java | 31 +- .../test/dto/builder/ObjectiveDtoBuilder.java | 14 +- .../quarter/check/QuarterRangeChecker.java | 1 - .../check/QuarterRangeCheckerTest.java | 12 +- .../quarter/generate/QuarterLabelTest.java | 66 +-- .../util/quarter/generate/QuartersTest.java | 231 +++++---- .../generate/h2/QuarterFunctionTest.java | 18 +- 268 files changed, 6044 insertions(+), 4298 deletions(-) diff --git a/backend/src/main/java/ch/puzzle/okr/Constants.java b/backend/src/main/java/ch/puzzle/okr/Constants.java index c7cf839961..63989d249c 100644 --- a/backend/src/main/java/ch/puzzle/okr/Constants.java +++ b/backend/src/main/java/ch/puzzle/okr/Constants.java @@ -1,12 +1,11 @@ package ch.puzzle.okr; +import static java.util.Map.entry; + import ch.puzzle.okr.dto.checkin.*; import ch.puzzle.okr.dto.keyresult.*; - import java.util.Map; -import static java.util.Map.entry; - public class Constants { private Constants() { } @@ -29,11 +28,11 @@ private Constants() { public static final String CHECK_IN_KEY_RESULT_ID_ATTRIBUTE_NAME = "keyResultId"; public static final String KEY_RESULT_TYPE_ATTRIBUTE_NAME = "keyResultType"; - public static final Map> KEY_RESULT_MAP = Map.ofEntries( - entry(KEY_RESULT_TYPE_METRIC, KeyResultMetricDto.class), - entry(KEY_RESULT_TYPE_ORDINAL, KeyResultOrdinalDto.class)); + public static final Map> KEY_RESULT_MAP = Map + .ofEntries(entry(KEY_RESULT_TYPE_METRIC, KeyResultMetricDto.class), + entry(KEY_RESULT_TYPE_ORDINAL, KeyResultOrdinalDto.class)); - public static final Map> CHECK_IN_MAP = Map.ofEntries( - entry(KEY_RESULT_TYPE_METRIC, CheckInMetricDto.class), - entry(KEY_RESULT_TYPE_ORDINAL, CheckInOrdinalDto.class)); + public static final Map> CHECK_IN_MAP = Map + .ofEntries(entry(KEY_RESULT_TYPE_METRIC, CheckInMetricDto.class), + entry(KEY_RESULT_TYPE_ORDINAL, CheckInOrdinalDto.class)); } 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 2e517f4d59..40180a1765 100644 --- a/backend/src/main/java/ch/puzzle/okr/ForwardFilter.java +++ b/backend/src/main/java/ch/puzzle/okr/ForwardFilter.java @@ -5,14 +5,11 @@ import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; +import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; import org.springframework.web.filter.GenericFilterBean; -import java.io.IOException; -import java.util.Arrays; - public class ForwardFilter extends GenericFilterBean { private static final Logger logger = LoggerFactory.getLogger(ForwardFilter.class); 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..f0e5fe5652 100644 --- a/backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java +++ b/backend/src/main/java/ch/puzzle/okr/OpenAPI30Configuration.java @@ -12,9 +12,15 @@ public class OpenAPI30Configuration { @Bean 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"))); + 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"))); } } diff --git a/backend/src/main/java/ch/puzzle/okr/SecurityConfig.java b/backend/src/main/java/ch/puzzle/okr/SecurityConfig.java index b4b8a07e6f..29706319e3 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 @@ -58,10 +58,12 @@ public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http, @Value("${c http.addFilterAfter(new ForwardFilter(), BasicAuthenticationFilter.class); logger.debug("*** apiSecurityFilterChain reached"); setHeaders(http); - return http.cors(Customizer.withDefaults()) + 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(); + .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())) + .build(); } @Bean @@ -75,14 +77,15 @@ 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())) + .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)) @@ -96,32 +99,31 @@ private HttpSecurity setHeaders(HttpSecurity http) throws Exception { 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..7252d122bb 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") @@ -30,8 +29,8 @@ public ActionController(ActionAuthorizationService actionAuthorizationService, A @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); } 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..f63a090ea3 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; } @@ -35,11 +34,12 @@ public AlignmentController(AlignmentSelectionMapper alignmentSelectionMapper, @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) { - return ResponseEntity.status(HttpStatus.OK) - .body(alignmentSelectionMapper.toDto(alignmentSelectionBusinessService - .getAlignmentSelectionByQuarterIdAndTeamIdNot(quarterFilter, 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))); } } 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..976e0ceb24 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/CheckInController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/CheckInController.java @@ -34,7 +34,8 @@ public CheckInController(CheckInMapper checkInMapper, CheckInAuthorizationServic @ApiResponse(responseCode = "404", description = "Did not find a Check-in with a specified ID", content = @Content) }) @GetMapping("/{id}") public ResponseEntity getCheckInById(@PathVariable long id) { - return ResponseEntity.status(HttpStatus.OK) + return ResponseEntity + .status(HttpStatus.OK) .body(checkInMapper.toDto(this.checkInAuthorizationService.getEntityById(id))); } @@ -47,9 +48,8 @@ public ResponseEntity getCheckInById(@PathVariable long id) { @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) }) @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)); @@ -63,8 +63,8 @@ public ResponseEntity updateCheckIn( @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) }) @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); @@ -75,8 +75,8 @@ public ResponseEntity createCheckIn( @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") }) @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..1fd85d9089 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/ClientConfigController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/ClientConfigController.java @@ -20,7 +20,8 @@ public ClientConfigController(ClientConfigService configService) { @GetMapping("/config") public ResponseEntity getConfig(HttpServletRequest request) { - return ResponseEntity.status(HttpStatus.OK) + return ResponseEntity + .status(HttpStatus.OK) .body(configService.getConfigBasedOnActiveEnv(request.getServerName())); } 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..b7cbfcaeb9 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; } 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..a52c61761e 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; @@ -66,8 +65,8 @@ public KeyResultDto getKeyResultById(@PathVariable long id) { @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) }) @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(); } @@ -98,15 +97,15 @@ public ResponseEntity createKeyResult(@RequestBody KeyResultDto ke @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) }) @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); - return ResponseEntity.status(isKeyResultImUsed ? IM_USED : OK) + KeyResultWithActionList updatedKeyResult = keyResultAuthorizationService + .updateEntities(id, keyResult, actionList); + return ResponseEntity + .status(isKeyResultImUsed ? IM_USED : OK) .body(keyResultMapper.toDto(updatedKeyResult.keyResult(), updatedKeyResult.actionList())); } 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 7ca8ae39d8..411c11787a 100644 --- a/backend/src/main/java/ch/puzzle/okr/controller/ObjectiveController.java +++ b/backend/src/main/java/ch/puzzle/okr/controller/ObjectiveController.java @@ -1,9 +1,12 @@ package ch.puzzle.okr.controller; -import ch.puzzle.okr.dto.checkin.CheckInDto; -import ch.puzzle.okr.dto.keyresult.KeyResultDto; +import static org.springframework.http.HttpStatus.IM_USED; +import static org.springframework.http.HttpStatus.OK; + import ch.puzzle.okr.dto.DuplicateObjectiveDto; import ch.puzzle.okr.dto.ObjectiveDto; +import ch.puzzle.okr.dto.checkin.CheckInDto; +import ch.puzzle.okr.dto.keyresult.KeyResultDto; import ch.puzzle.okr.mapper.ObjectiveMapper; import ch.puzzle.okr.mapper.keyresult.KeyResultMapper; import ch.puzzle.okr.models.Action; @@ -17,15 +20,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.IM_USED; -import static org.springframework.http.HttpStatus.OK; - @RestController @RequestMapping("api/v2/objectives") public class ObjectiveController { @@ -35,8 +34,8 @@ public class ObjectiveController { private final ActionAuthorizationService actionAuthorizationService; public ObjectiveController(ObjectiveAuthorizationService objectiveAuthorizationService, - ObjectiveMapper objectiveMapper, KeyResultMapper keyResultMapper, - ActionAuthorizationService actionAuthorizationService) { + ObjectiveMapper objectiveMapper, KeyResultMapper keyResultMapper, + ActionAuthorizationService actionAuthorizationService) { this.objectiveAuthorizationService = objectiveAuthorizationService; this.objectiveMapper = objectiveMapper; this.keyResultMapper = keyResultMapper; @@ -50,9 +49,10 @@ public ObjectiveController(ObjectiveAuthorizationService objectiveAuthorizationS @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) }) @GetMapping("/{id}") - public ResponseEntity getObjective( - @Parameter(description = "The ID for getting an Objective.", required = true) @PathVariable Long id) { - return ResponseEntity.status(HttpStatus.OK) + 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))); } @@ -63,9 +63,10 @@ public ResponseEntity getObjective( @ApiResponse(responseCode = "401", description = "Not authorized to read KeyResults from an Objective", content = @Content), @ApiResponse(responseCode = "404", description = "Did not find an Objective with the specified ID to get KeyResults from.", content = @Content) }) @GetMapping("/{id}/keyResults") - public ResponseEntity> getKeyResultsFromObjective( - @Parameter(description = "The ID for getting all KeyResults of an Objective", required = true) @PathVariable long id) { - return ResponseEntity.status(OK) + public ResponseEntity> getKeyResultsFromObjective(@Parameter(description = "The ID for getting all KeyResults of an Objective", required = true) + @PathVariable long id) { + return ResponseEntity + .status(OK) .body(objectiveAuthorizationService.getAllKeyResultsByObjective(id).stream().map(keyResult -> { List actionList = actionAuthorizationService.getActionsByKeyResult(keyResult); return keyResultMapper.toDto(keyResult, actionList); @@ -77,8 +78,8 @@ public ResponseEntity> getKeyResultsFromObjective( @ApiResponse(responseCode = "401", description = "Not authorized to delete an Objective", content = @Content), @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); } @@ -89,8 +90,8 @@ public void deleteObjectiveById( @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) }) @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); @@ -100,11 +101,13 @@ public ResponseEntity createObjective( @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 DuplicateObjectiveDto duplicateObjectiveDto) { + 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 DuplicateObjectiveDto duplicateObjectiveDto) { Objective objective = objectiveMapper.toObjective(duplicateObjectiveDto.objective()); - List keyResults = duplicateObjectiveDto.keyResults().stream().map(keyResultMapper::toKeyResult) + List keyResults = duplicateObjectiveDto + .keyResults() + .stream() + .map(keyResultMapper::toKeyResult) .toList(); ObjectiveDto duplicatedObjectiveDto = objectiveMapper .toDto(objectiveAuthorizationService.duplicateEntity(id, objective, keyResults)); @@ -122,9 +125,8 @@ public ResponseEntity duplicateObjective( @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) }) @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 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..3ea4163af9 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; } @@ -37,11 +36,13 @@ public OverviewController(OverviewMapper overviewMapper, @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) }) @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..a3c16c47e7 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 { 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..51cb9daeed 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 { @@ -45,8 +44,8 @@ public List getAllTeams() { @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) }) @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)); } @@ -59,9 +58,8 @@ public ResponseEntity createTeam( @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) }) @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)); } @@ -71,8 +69,8 @@ public ResponseEntity updateTeam( @ApiResponse(responseCode = "401", description = "Not authorized to delete an Team", content = @Content), @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); } @@ -81,9 +79,8 @@ public void deleteTeamById( @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") }) @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); } @@ -93,22 +90,19 @@ public void addUsersToTeam( @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") }) @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") + + "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") }) @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..36decfb050 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,7 +24,7 @@ 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; @@ -53,8 +52,8 @@ public UserDto getCurrentUser() { @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); } @@ -63,9 +62,8 @@ public UserDto getUserById( @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); } @@ -74,8 +72,8 @@ public UserDto setOkrChampion( @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); } @@ -86,8 +84,8 @@ public List createUsers( @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); } 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 5cf3d6406f..c4f9ffecad 100644 --- a/backend/src/main/java/ch/puzzle/okr/deserializer/CheckInDeserializer.java +++ b/backend/src/main/java/ch/puzzle/okr/deserializer/CheckInDeserializer.java @@ -1,14 +1,13 @@ package ch.puzzle.okr.deserializer; +import static ch.puzzle.okr.Constants.*; + import ch.puzzle.okr.dto.checkin.*; import ch.puzzle.okr.service.business.KeyResultBusinessService; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.*; -import org.springframework.stereotype.Component; - import java.io.IOException; - -import static ch.puzzle.okr.Constants.*; +import org.springframework.stereotype.Component; @Component public class CheckInDeserializer extends JsonDeserializer implements MetricOrdinalDeserializer { @@ -17,7 +16,7 @@ public class CheckInDeserializer extends JsonDeserializer implements private final KeyResultBusinessService keyResultBusinessService; public CheckInDeserializer(DeserializerHelper deserializerHelper, - KeyResultBusinessService keyResultBusinessService) { + KeyResultBusinessService keyResultBusinessService) { this.deserializerHelper = deserializerHelper; this.keyResultBusinessService = keyResultBusinessService; } diff --git a/backend/src/main/java/ch/puzzle/okr/deserializer/DeserializerHelper.java b/backend/src/main/java/ch/puzzle/okr/deserializer/DeserializerHelper.java index b305a24da8..d908110618 100644 --- a/backend/src/main/java/ch/puzzle/okr/deserializer/DeserializerHelper.java +++ b/backend/src/main/java/ch/puzzle/okr/deserializer/DeserializerHelper.java @@ -3,18 +3,18 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ResponseStatusException; -import java.io.IOException; -import java.util.Map; - @Component public class DeserializerHelper { public T deserializeMetricOrdinal(JsonParser jsonParser, Map> validTypes, - MetricOrdinalDeserializer deserializer) throws IOException { + MetricOrdinalDeserializer deserializer) + throws IOException { ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec(); ObjectNode root = mapper.readTree(jsonParser); 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 7515e14d7c..4cdbb7960c 100644 --- a/backend/src/main/java/ch/puzzle/okr/deserializer/KeyResultDeserializer.java +++ b/backend/src/main/java/ch/puzzle/okr/deserializer/KeyResultDeserializer.java @@ -1,13 +1,12 @@ package ch.puzzle.okr.deserializer; +import static ch.puzzle.okr.Constants.*; + import ch.puzzle.okr.dto.keyresult.KeyResultDto; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.*; - import java.io.IOException; -import static ch.puzzle.okr.Constants.*; - public class KeyResultDeserializer extends JsonDeserializer implements MetricOrdinalDeserializer { private final DeserializerHelper deserializerHelper; diff --git a/backend/src/main/java/ch/puzzle/okr/dto/DuplicateObjectiveDto.java b/backend/src/main/java/ch/puzzle/okr/dto/DuplicateObjectiveDto.java index d4f5bd7f8a..232fd14ae2 100644 --- a/backend/src/main/java/ch/puzzle/okr/dto/DuplicateObjectiveDto.java +++ b/backend/src/main/java/ch/puzzle/okr/dto/DuplicateObjectiveDto.java @@ -1,7 +1,6 @@ package ch.puzzle.okr.dto; import ch.puzzle.okr.dto.keyresult.KeyResultDto; - import java.util.List; public record DuplicateObjectiveDto(ObjectiveDto objective, List keyResults) { 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 9bab43b985..d4537437f8 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 zone, boolean writeable) - implements CheckInDto { + Long keyResultId, LocalDateTime createdOn, LocalDateTime modifiedOn, Zone zone, + 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 92068a47a1..16bb51003f 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 zone, 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..1108cd6d01 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; @@ -13,7 +12,5 @@ public record KeyResultMetricDto(Long id, int version, String keyResultType, Str KeyResultLastCheckInMetricDto lastCheckIn, LocalDateTime createdOn, LocalDateTime modifiedOn, boolean writeable, List actionList) implements KeyResultDto { @Override - public List getActionList() { - return actionList; - } + public List getActionList() { return actionList; } } 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..e48980a636 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; @@ -12,7 +11,5 @@ public record KeyResultOrdinalDto(Long id, int version, String keyResultType, St KeyResultObjectiveDto objective, KeyResultLastCheckInOrdinalDto lastCheckIn, LocalDateTime createdOn, LocalDateTime modifiedOn, boolean writeable, List actionList) implements KeyResultDto { @Override - public List getActionList() { - return actionList; - } + public List getActionList() { return actionList; } } \ No newline at end of file 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 131d126373..e01f1a6781 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 zone, Integer confidence, LocalDateTime createdOn) - implements OverviewLastCheckInDto { +public record OverviewLastCheckInOrdinalDto(Long id, String zone, 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..298b83c621 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; @@ -55,7 +54,5 @@ public OkrResponseStatusException(HttpStatus status, List errors) { this.errors = errors; } - public List getErrors() { - return errors; - } + public List getErrors() { return 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..7be672faea 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) { @@ -27,14 +31,21 @@ public List toActions(List actionDtos, KeyResult keyResult) { } public List toActions(List actionDtos) { - return actionDtos.stream() + return actionDtos + .stream() .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..a19d82f6bb 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..53e29e39cc 100644 --- a/backend/src/main/java/ch/puzzle/okr/mapper/CompletedMapper.java +++ b/backend/src/main/java/ch/puzzle/okr/mapper/CompletedMapper.java @@ -15,13 +15,14 @@ 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() // + return Completed.Builder + .builder() // .withId(completedDto.id()) // .withObjective(objectiveMapper.toObjective(completedDto.objective())) // .withComment(completedDto.comment()) // 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..1334d6d663 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,31 @@ 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..5a3a0959cd 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..2f9f48005b 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,11 @@ public TeamDto toDto(Team team) { } public Team toTeam(TeamDto teamDto) { - return Team.Builder.builder().withId(teamDto.id()).withVersion(teamDto.version()).withName(teamDto.name()) + 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..6ad179fd5d 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,22 @@ 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())) + 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()); + 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..0b4a411c15 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 { @@ -15,10 +14,13 @@ public UserOkrDataDto toDto(List keyResults) { } private List toUserKeyResultDataDtos(List keyResults) { - return keyResults.stream() // + return keyResults + .stream() // .map(keyResult -> new UserKeyResultDataDto( // - keyResult.getId(), keyResult.getTitle(), // - keyResult.getObjective().getId(), keyResult.getObjective().getTitle() // + keyResult.getId(), + keyResult.getTitle(), // + keyResult.getObjective().getId(), + keyResult.getObjective().getTitle() // )) // .toList(); } 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..e6a0642fac 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,9 @@ 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 +40,9 @@ 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..fcf153ae06 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,19 +16,20 @@ 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() // + return CheckInMetric.Builder + .builder() // .withValue(checkInMetricDto.value()) // .withId(checkInMetricDto.id()) // .withVersion(checkInMetricDto.version()) // 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 5bc4f811b8..da32c06a86 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,19 +15,21 @@ 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() // + return CheckInOrdinal.Builder + .builder() // .withZone(checkInOrdinalDto.zone()) // .withId(checkInOrdinalDto.id()) // .withVersion(checkInOrdinalDto.version()) // 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..2f9434045f 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,9 @@ 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 +44,9 @@ 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..e84d2520ef 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,42 +32,44 @@ 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() // + return KeyResultMetric.Builder + .builder() // .withBaseline(keyResultMetricDto.baseline()) // .withStretchGoal(keyResultMetricDto.stretchGoal()) // .withUnit(keyResultMetricDto.unit()) // @@ -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..1e7f286e2c 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,43 +32,44 @@ 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() // + return KeyResultOrdinal.Builder + .builder() // .withCommitZone(keyResultOrdinalDto.commitZone()) // .withTargetZone(keyResultOrdinalDto.targetZone()) // .withStretchZone(keyResultOrdinalDto.stretchZone()) // @@ -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..e10ca96c1e 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; @@ -45,68 +44,42 @@ private Action(Builder builder) { keyResult = builder.keyResult; } - public Long getId() { - return id; - } + public Long getId() { return id; } public void resetId() { id = null; } - public String getAction() { - return action; - } + public String getAction() { return action; } - public void setAction(String action) { - this.action = action; - } + public void setAction(String action) { this.action = action; } - public int getPriority() { - return priority; - } + public int getPriority() { return priority; } - public void setPriority(int priority) { - this.priority = priority; - } + public void setPriority(int priority) { this.priority = priority; } - public boolean isChecked() { - return isChecked; - } + public boolean isChecked() { return isChecked; } - public void setChecked(boolean checked) { - isChecked = checked; - } + public void setChecked(boolean checked) { isChecked = checked; } - public KeyResult getKeyResult() { - return keyResult; - } + public KeyResult getKeyResult() { return keyResult; } - public void setKeyResult(KeyResult keyResult) { - this.keyResult = keyResult; - } + public void setKeyResult(KeyResult keyResult) { this.keyResult = keyResult; } - public int getVersion() { - return version; - } + public int getVersion() { return version; } - public void setVersion(int version) { - this.version = version; - } + public void setVersion(int version) { this.version = version; } @Override - public boolean isWriteable() { - return writeable; - } + public boolean isWriteable() { return writeable; } @Override - public void setWriteable(boolean writeable) { - this.writeable = writeable; - } + public void setWriteable(boolean writeable) { this.writeable = 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 +90,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..19e0de22ac 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Completed.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Completed.java @@ -32,34 +32,22 @@ private Completed(Builder builder) { setComment(builder.comment); } - public Long getId() { - return id; - } + public Long getId() { return id; } - public int getVersion() { - return version; - } + public int getVersion() { return version; } - public Objective getObjective() { - return objective; - } + public Objective getObjective() { return objective; } - public void setObjective(Objective objective) { - this.objective = objective; - } + public void setObjective(Objective objective) { this.objective = objective; } - public String getComment() { - return comment; - } + public String getComment() { return comment; } - public void setComment(String comment) { - this.comment = comment; - } + public void setComment(String comment) { this.comment = comment; } @Override public String toString() { return "Completed{" + "id=" + id + ", version=" + version + ", objective=" + objective + ", comment='" + comment - + '\'' + '}'; + + '\'' + '}'; } @Override @@ -70,7 +58,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/Objective.java b/backend/src/main/java/ch/puzzle/okr/models/Objective.java index 85a96b59dd..281c0d7353 100644 --- a/backend/src/main/java/ch/puzzle/okr/models/Objective.java +++ b/backend/src/main/java/ch/puzzle/okr/models/Objective.java @@ -4,7 +4,6 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; - import java.time.LocalDateTime; import java.util.Objects; @@ -70,102 +69,58 @@ private Objective(Builder builder) { setModifiedBy(builder.modifiedBy); } - public Long getId() { - return id; - } + public Long getId() { return id; } - public int getVersion() { - return version; - } + public int getVersion() { return version; } - public String getTitle() { - return title; - } + public String getTitle() { return title; } - public void setTitle(String title) { - this.title = title; - } + public void setTitle(String title) { this.title = title; } - public User getCreatedBy() { - return createdBy; - } + public User getCreatedBy() { return createdBy; } - public void setCreatedBy(User createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } - public Team getTeam() { - return team; - } + public Team getTeam() { return team; } - public void setTeam(Team team) { - this.team = team; - } + public void setTeam(Team team) { this.team = team; } - public Quarter getQuarter() { - return quarter; - } + public Quarter getQuarter() { return quarter; } - public void setQuarter(Quarter quarter) { - this.quarter = quarter; - } + public void setQuarter(Quarter quarter) { this.quarter = quarter; } - public String getDescription() { - return description; - } + public String getDescription() { return description; } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { this.description = description; } - public LocalDateTime getModifiedOn() { - return modifiedOn; - } + public LocalDateTime getModifiedOn() { return modifiedOn; } - public void setModifiedOn(LocalDateTime modifiedOn) { - this.modifiedOn = modifiedOn; - } + public void setModifiedOn(LocalDateTime modifiedOn) { this.modifiedOn = modifiedOn; } - public State getState() { - return state; - } + public State getState() { return state; } - public void setState(State state) { - this.state = state; - } + public void setState(State state) { this.state = state; } - public LocalDateTime getCreatedOn() { - return createdOn; - } + public LocalDateTime getCreatedOn() { return createdOn; } - public void setCreatedOn(LocalDateTime createdOn) { - this.createdOn = createdOn; - } + public void setCreatedOn(LocalDateTime createdOn) { this.createdOn = createdOn; } - public User getModifiedBy() { - return modifiedBy; - } + public User getModifiedBy() { return modifiedBy; } - public void setModifiedBy(User modifiedBy) { - this.modifiedBy = modifiedBy; - } + public void setModifiedBy(User modifiedBy) { this.modifiedBy = modifiedBy; } @Override - public boolean isWriteable() { - return writeable; - } + public boolean isWriteable() { return writeable; } @Override - public void setWriteable(boolean writeable) { - this.writeable = writeable; - } + public void setWriteable(boolean writeable) { this.writeable = writeable; } @Override public String toString() { return "Objective{" + "id=" + id + ", version=" + version + ", title='" + title + '\'' + ", createdBy=" - + createdBy + ", team=" + team + ", quarter=" + quarter + ", description='" + description + '\'' - + ", modifiedOn=" + modifiedOn + ", state=" + state + ", createdOn=" + createdOn + ", modifiedBy=" - + modifiedBy + ", writeable=" + writeable + '\'' + '}'; + + createdBy + ", team=" + team + ", quarter=" + quarter + ", description='" + description + '\'' + + ", modifiedOn=" + modifiedOn + ", state=" + state + ", createdOn=" + createdOn + ", modifiedBy=" + + modifiedBy + ", writeable=" + writeable + '\'' + '}'; } @Override @@ -176,17 +131,27 @@ public boolean equals(Object o) { return false; Objective objective = (Objective) o; return Objects.equals(id, objective.id) && version == objective.version - && Objects.equals(title, objective.title) && Objects.equals(createdBy, objective.createdBy) - && Objects.equals(team, objective.team) && Objects.equals(quarter, objective.quarter) - && Objects.equals(description, objective.description) - && Objects.equals(modifiedOn, objective.modifiedOn) && state == objective.state - && Objects.equals(createdOn, objective.createdOn) && Objects.equals(modifiedBy, objective.modifiedBy); + && Objects.equals(title, objective.title) && Objects.equals(createdBy, objective.createdBy) + && Objects.equals(team, objective.team) && Objects.equals(quarter, objective.quarter) + && Objects.equals(description, objective.description) && Objects.equals(modifiedOn, objective.modifiedOn) + && state == objective.state && Objects.equals(createdOn, objective.createdOn) + && Objects.equals(modifiedBy, objective.modifiedBy); } @Override public int hashCode() { - return Objects.hash(id, version, title, createdBy, team, quarter, description, modifiedOn, state, createdOn, - modifiedBy); + return Objects + .hash(id, + version, + title, + createdBy, + team, + quarter, + description, + modifiedOn, + state, + createdOn, + modifiedBy); } public static final class Builder { 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..244a76e965 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; @@ -31,38 +30,24 @@ private Quarter(Builder builder) { setEndDate(builder.endDate); } - public Long getId() { - return id; - } + public Long getId() { return id; } - public String getLabel() { - return label; - } + public String getLabel() { return label; } - public void setLabel(String label) { - this.label = label; - } + public void setLabel(String label) { this.label = label; } - public LocalDate getStartDate() { - return startDate; - } + public LocalDate getStartDate() { return startDate; } - public void setStartDate(LocalDate startDate) { - this.startDate = startDate; - } + public void setStartDate(LocalDate startDate) { this.startDate = startDate; } - public LocalDate getEndDate() { - return endDate; - } + public LocalDate getEndDate() { return endDate; } - public void setEndDate(LocalDate endDate) { - this.endDate = endDate; - } + public void setEndDate(LocalDate endDate) { this.endDate = endDate; } @Override public String toString() { return "Quarter{" + "id=" + id + ", label='" + label + '\'' + ", startDate=" + startDate + ", endDate=" - + endDate + '}'; + + endDate + '}'; } @Override @@ -73,7 +58,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 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..a2bbadb7bf 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; @@ -38,39 +37,23 @@ private Team(Builder builder) { setUserTeamList(builder.userTeamList); } - public Long getId() { - return id; - } + public Long getId() { return id; } - public int getVersion() { - return version; - } + public int getVersion() { return version; } - public String getName() { - return name; - } + public String getName() { return name; } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { this.name = name; } - public List getUserTeamList() { - return userTeamList; - } + public List getUserTeamList() { return userTeamList; } - public void setUserTeamList(List userTeamList) { - this.userTeamList = userTeamList; - } + public void setUserTeamList(List userTeamList) { this.userTeamList = userTeamList; } @Override - public boolean isWriteable() { - return writeable; - } + public boolean isWriteable() { return writeable; } @Override - public void setWriteable(boolean writeable) { - this.writeable = writeable; - } + public void setWriteable(boolean writeable) { this.writeable = writeable; } @Override public String toString() { @@ -85,7 +68,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..b9267ad9ac 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; @@ -58,58 +57,34 @@ private User(Builder builder) { setOkrChampion(builder.isOkrChampion); } - public Long getId() { - return id; - } + public Long getId() { return id; } - public int getVersion() { - return version; - } + public int getVersion() { return version; } - public String getFirstname() { - return firstname; - } + public String getFirstname() { return firstname; } - public void setFirstname(String firstname) { - this.firstname = firstname; - } + public void setFirstname(String firstname) { this.firstname = firstname; } - public String getLastname() { - return lastname; - } + public String getLastname() { return lastname; } - public void setLastname(String lastname) { - this.lastname = lastname; - } + public void setLastname(String lastname) { this.lastname = lastname; } - public String getEmail() { - return email; - } + public String getEmail() { return email; } - public void setEmail(String email) { - this.email = email; - } + public void setEmail(String email) { this.email = email; } - public List getUserTeamList() { - return userTeamList; - } + public List getUserTeamList() { return userTeamList; } - public void setUserTeamList(List userTeamList) { - this.userTeamList = userTeamList; - } + public void setUserTeamList(List userTeamList) { this.userTeamList = userTeamList; } - public boolean isOkrChampion() { - return isOkrChampion; - } + public boolean isOkrChampion() { return isOkrChampion; } - public void setOkrChampion(boolean okrChampion) { - isOkrChampion = okrChampion; - } + public void setOkrChampion(boolean okrChampion) { isOkrChampion = 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 +95,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..eefce72615 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 @@ -38,45 +37,25 @@ private UserTeam(Builder builder) { this.isTeamAdmin = builder.isTeamAdmin; } - public Long getId() { - return id; - } + public Long getId() { return id; } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { this.id = id; } - public int getVersion() { - return version; - } + public int getVersion() { return version; } - public void setVersion(int version) { - this.version = version; - } + public void setVersion(int version) { this.version = version; } - public User getUser() { - return user; - } + public User getUser() { return user; } - public void setUser(User user) { - this.user = user; - } + public void setUser(User user) { this.user = user; } - public Team getTeam() { - return team; - } + public Team getTeam() { return team; } - public void setTeam(Team team) { - this.team = team; - } + public void setTeam(Team team) { this.team = team; } - public boolean isTeamAdmin() { - return isTeamAdmin; - } + public boolean isTeamAdmin() { return isTeamAdmin; } - public void setTeamAdmin(boolean teamAdmin) { - isTeamAdmin = teamAdmin; - } + public void setTeamAdmin(boolean teamAdmin) { isTeamAdmin = teamAdmin; } @Override public boolean equals(Object o) { @@ -88,7 +67,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 +78,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..56a09b20b1 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; @@ -30,21 +29,13 @@ protected Alignment(Alignment.Builder builder) { setAlignedObjective(builder.alignedObjective); } - public Long getId() { - return id; - } + public Long getId() { return id; } - public int getVersion() { - return version; - } + public int getVersion() { return version; } - public Objective getAlignedObjective() { - return alignedObjective; - } + public Objective getAlignedObjective() { return alignedObjective; } - public void setAlignedObjective(Objective alignedObjective) { - this.alignedObjective = alignedObjective; - } + public void setAlignedObjective(Objective alignedObjective) { this.alignedObjective = alignedObjective; } @Override public String toString() { @@ -59,7 +50,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..27afd767cb 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 @@ -33,25 +32,15 @@ private AlignmentSelection(Builder builder) { keyResultTitle = builder.keyResultTitle; } - public AlignmentSelectionId getAlignmentSelectionId() { - return alignmentSelectionId; - } + public AlignmentSelectionId getAlignmentSelectionId() { return alignmentSelectionId; } - public Long getTeamId() { - return teamId; - } + public Long getTeamId() { return teamId; } - public String getObjectiveTitle() { - return objectiveTitle; - } + public String getObjectiveTitle() { return objectiveTitle; } - public Long getQuarterId() { - return quarterId; - } + public Long getQuarterId() { return quarterId; } - public String getKeyResultTitle() { - return keyResultTitle; - } + public String getKeyResultTitle() { return keyResultTitle; } @Override public boolean equals(Object o) { @@ -61,10 +50,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 +64,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..612ae992cb 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; @@ -27,13 +26,9 @@ public static AlignmentSelectionId of(Long objectiveId, Long keyResultId) { return new AlignmentSelectionId(objectiveId, keyResultId); } - public Long getObjectiveId() { - return objectiveId; - } + public Long getObjectiveId() { return objectiveId; } - public Long getKeyResultId() { - return keyResultId; - } + public Long getKeyResultId() { return keyResultId; } @Override public String toString() { 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..cc08c09024 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; @@ -22,14 +21,10 @@ private KeyResultAlignment(Builder builder) { } @Override - public KeyResult getAlignmentTarget() { - return targetKeyResult; - } + public KeyResult getAlignmentTarget() { return targetKeyResult; } @Override - public void setAlignmentTarget(KeyResult alignmentTarget) { - this.targetKeyResult = alignmentTarget; - } + public void setAlignmentTarget(KeyResult alignmentTarget) { this.targetKeyResult = alignmentTarget; } @Override public boolean equals(Object o) { 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..0c15ff93e2 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 @@ -24,14 +23,10 @@ private ObjectiveAlignment(Builder builder) { } @Override - public Objective getAlignmentTarget() { - return targetObjective; - } + public Objective getAlignmentTarget() { return targetObjective; } @Override - public void setAlignmentTarget(Objective alignmentTarget) { - targetObjective = alignmentTarget; - } + public void setAlignmentTarget(Objective alignmentTarget) { targetObjective = alignmentTarget; } @Override public boolean equals(Object o) { 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..a2acf2cc24 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,9 @@ public boolean isUserMemberInTeam(Long teamId) { } public boolean isUserAdminInTeam(Long teamId) { - return this.user.getUserTeamList().stream() + 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..d657e784ec 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; @@ -53,90 +51,52 @@ public abstract class CheckIn implements WriteableInterface { private transient boolean writeable; /* Getter and Setter */ - public Long getId() { - return id; - } + public Long getId() { return id; } - public int getVersion() { - return version; - } + public int getVersion() { return version; } - public String getChangeInfo() { - return changeInfo; - } + public String getChangeInfo() { return changeInfo; } - public void setChangeInfo(String changeInfo) { - this.changeInfo = changeInfo; - } + public void setChangeInfo(String changeInfo) { this.changeInfo = changeInfo; } - public String getInitiatives() { - return initiatives; - } + public String getInitiatives() { return initiatives; } - public void setInitiatives(String initiatives) { - this.initiatives = initiatives; - } + public void setInitiatives(String initiatives) { this.initiatives = initiatives; } - public Integer getConfidence() { - return confidence; - } + public Integer getConfidence() { return confidence; } - public void setConfidence(Integer confidence) { - this.confidence = confidence; - } + public void setConfidence(Integer confidence) { this.confidence = confidence; } - public KeyResult getKeyResult() { - return keyResult; - } + public KeyResult getKeyResult() { return keyResult; } - public void setKeyResult(KeyResult keyResult) { - this.keyResult = keyResult; - } + public void setKeyResult(KeyResult keyResult) { this.keyResult = keyResult; } - public User getCreatedBy() { - return createdBy; - } + public User getCreatedBy() { return createdBy; } - public void setCreatedBy(User createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } - public LocalDateTime getCreatedOn() { - return createdOn; - } + public LocalDateTime getCreatedOn() { return createdOn; } - public void setCreatedOn(LocalDateTime createdOn) { - this.createdOn = createdOn; - } + public void setCreatedOn(LocalDateTime createdOn) { this.createdOn = createdOn; } - public LocalDateTime getModifiedOn() { - return modifiedOn; - } + public LocalDateTime getModifiedOn() { return modifiedOn; } - public void setModifiedOn(LocalDateTime modifiedOn) { - this.modifiedOn = modifiedOn; - } + public void setModifiedOn(LocalDateTime modifiedOn) { this.modifiedOn = modifiedOn; } - public String getCheckInType() { - return checkInType; - } + public String getCheckInType() { return checkInType; } @Override - public boolean isWriteable() { - return writeable; - } + public boolean isWriteable() { return writeable; } @Override - public void setWriteable(boolean writeable) { - this.writeable = writeable; - } + public void setWriteable(boolean writeable) { this.writeable = 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 +107,25 @@ 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..e2ae268b30 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 { @@ -16,13 +15,9 @@ public class CheckInMetric extends CheckIn { private Double valueMetric; /* Getter and Setter */ - public Double getValue() { - return valueMetric; - } + public Double getValue() { return valueMetric; } - public void setValue(Double value) { - this.valueMetric = value; - } + public void setValue(Double value) { this.valueMetric = value; } /* Constructor */ public CheckInMetric() { 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..14e87cdbe4 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 { @@ -19,13 +18,9 @@ public class CheckInOrdinal extends CheckIn { private Zone zone; /* Getter and Setter */ - public Zone getZone() { - return zone; - } + public Zone getZone() { return zone; } - public void setZone(Zone zone) { - this.zone = zone; - } + public void setZone(Zone zone) { this.zone = zone; } /* Constructor */ public CheckInOrdinal() { 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 1da614d05c..d23582c27b 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; @@ -54,98 +53,58 @@ public abstract class KeyResult implements WriteableInterface { private transient boolean writeable; - public Long getId() { - return id; - } + public Long getId() { return id; } - public int getVersion() { - return version; - } + public int getVersion() { return version; } - public Objective getObjective() { - return objective; - } + public Objective getObjective() { return objective; } - public void setObjective(Objective objective) { - this.objective = objective; - } + public void setObjective(Objective objective) { this.objective = objective; } - public String getTitle() { - return title; - } + public String getTitle() { return title; } - public void setTitle(String title) { - this.title = title; - } + public void setTitle(String title) { this.title = title; } - public String getDescription() { - return description; - } + public String getDescription() { return description; } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { this.description = description; } - public User getOwner() { - return owner; - } + public User getOwner() { return owner; } - public void setOwner(User owner) { - this.owner = owner; - } + public void setOwner(User owner) { this.owner = owner; } - public User getCreatedBy() { - return createdBy; - } + public User getCreatedBy() { return createdBy; } - public void setCreatedBy(User createdBy) { - this.createdBy = createdBy; - } + public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } - public LocalDateTime getCreatedOn() { - return createdOn; - } + public LocalDateTime getCreatedOn() { return createdOn; } - public void setCreatedOn(LocalDateTime createdOn) { - this.createdOn = createdOn; - } + public void setCreatedOn(LocalDateTime createdOn) { this.createdOn = createdOn; } - public LocalDateTime getModifiedOn() { - return modifiedOn; - } + public LocalDateTime getModifiedOn() { return modifiedOn; } - public void setModifiedOn(LocalDateTime modifiedOn) { - this.modifiedOn = modifiedOn; - } + public void setModifiedOn(LocalDateTime modifiedOn) { this.modifiedOn = modifiedOn; } - public String getKeyResultType() { - return keyResultType; - } + public String getKeyResultType() { return keyResultType; } public void resetId() { this.id = null; } - private void setKeyResultType(String keyResultType) { - this.keyResultType = keyResultType; - } + private void setKeyResultType(String keyResultType) { this.keyResultType = keyResultType; } @Override - public boolean isWriteable() { - return writeable; - } + public boolean isWriteable() { return writeable; } @Override - public void setWriteable(boolean writeable) { - this.writeable = writeable; - } + public void setWriteable(boolean writeable) { this.writeable = 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 @@ -156,17 +115,26 @@ 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..85ec1cb19e 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 { @@ -22,29 +21,17 @@ public class KeyResultMetric extends KeyResult { @Enumerated(EnumType.STRING) private Unit unit; - public Double getBaseline() { - return baseline; - } + public Double getBaseline() { return baseline; } - public void setBaseline(Double baseline) { - this.baseline = baseline; - } + public void setBaseline(Double baseline) { this.baseline = baseline; } - public Double getStretchGoal() { - return stretchGoal; - } + public Double getStretchGoal() { return stretchGoal; } - public void setStretchGoal(Double stretchGoal) { - this.stretchGoal = stretchGoal; - } + public void setStretchGoal(Double stretchGoal) { this.stretchGoal = stretchGoal; } - public Unit getUnit() { - return unit; - } + public Unit getUnit() { return unit; } - public void setUnit(Unit unit) { - this.unit = unit; - } + public void setUnit(Unit unit) { this.unit = unit; } public KeyResultMetric() { super(); @@ -54,8 +41,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 +55,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..c13d0f1bf1 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 { @@ -24,29 +23,17 @@ public class KeyResultOrdinal extends KeyResult { @Size(max = 400, message = "Attribute stretchZone has a max length of 400 characters") private String stretchZone; - public String getCommitZone() { - return commitZone; - } + public String getCommitZone() { return commitZone; } - public void setCommitZone(String commitZone) { - this.commitZone = commitZone; - } + public void setCommitZone(String commitZone) { this.commitZone = commitZone; } - public String getTargetZone() { - return targetZone; - } + public String getTargetZone() { return targetZone; } - public void setTargetZone(String targetZone) { - this.targetZone = targetZone; - } + public void setTargetZone(String targetZone) { this.targetZone = targetZone; } - public String getStretchZone() { - return stretchZone; - } + public String getStretchZone() { return stretchZone; } - public void setStretchZone(String stretchZone) { - this.stretchZone = stretchZone; - } + public void setStretchZone(String stretchZone) { this.stretchZone = stretchZone; } public KeyResultOrdinal() { super(); @@ -56,8 +43,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 +57,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..faa60a55de 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 @@ -65,107 +64,63 @@ private Overview(Builder builder) { checkInCreatedOn = builder.checkInCreatedOn; } - public OverviewId getOverviewId() { - return overviewId; - } + public OverviewId getOverviewId() { return overviewId; } - public int getTeamVersion() { - return teamVersion; - } + public int getTeamVersion() { return teamVersion; } - public String getTeamName() { - return teamName; - } + public String getTeamName() { return teamName; } - public String getObjectiveTitle() { - return objectiveTitle; - } + public String getObjectiveTitle() { return objectiveTitle; } - public State getObjectiveState() { - return objectiveState; - } + public State getObjectiveState() { return objectiveState; } - public LocalDateTime getObjectiveCreatedOn() { - return objectiveCreatedOn; - } + public LocalDateTime getObjectiveCreatedOn() { return objectiveCreatedOn; } - public Long getQuarterId() { - return quarterId; - } + public Long getQuarterId() { return quarterId; } - public String getQuarterLabel() { - return quarterLabel; - } + public String getQuarterLabel() { return quarterLabel; } - public String getKeyResultTitle() { - return keyResultTitle; - } + public String getKeyResultTitle() { return keyResultTitle; } - public String getKeyResultType() { - return keyResultType; - } + public String getKeyResultType() { return keyResultType; } - public Double getBaseline() { - return baseline; - } + public Double getBaseline() { return baseline; } - public Double getStretchGoal() { - return stretchGoal; - } + public Double getStretchGoal() { return stretchGoal; } - public String getUnit() { - return unit; - } + public String getUnit() { return unit; } - public String getCommitZone() { - return commitZone; - } + public String getCommitZone() { return commitZone; } - public String getTargetZone() { - return targetZone; - } + public String getTargetZone() { return targetZone; } - public String getStretchZone() { - return stretchZone; - } + public String getStretchZone() { return stretchZone; } - public Double getCheckInValue() { - return checkInValue; - } + public Double getCheckInValue() { return checkInValue; } - public String getCheckInZone() { - return checkInZone; - } + public String getCheckInZone() { return checkInZone; } - public Integer getConfidence() { - return confidence; - } + public Integer getConfidence() { return confidence; } - public LocalDateTime getCheckInCreatedOn() { - return checkInCreatedOn; - } + public LocalDateTime getCheckInCreatedOn() { return checkInCreatedOn; } @Override - public boolean isWriteable() { - return writeable; - } + public boolean isWriteable() { return writeable; } @Override - public void setWriteable(boolean writeable) { - this.writeable = writeable; - } + public void setWriteable(boolean writeable) { this.writeable = 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..45f8fed20f 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; @@ -31,26 +30,18 @@ public static OverviewId of(Long teamId, Long objectiveId, Long keyResultId, Lon return new OverviewId(teamId, objectiveId, keyResultId, checkInId); } - public Long getTeamId() { - return teamId; - } + public Long getTeamId() { return teamId; } - public Long getObjectiveId() { - return objectiveId; - } + public Long getObjectiveId() { return objectiveId; } - public Long getKeyResultId() { - return keyResultId; - } + public Long getKeyResultId() { return keyResultId; } - public Long getCheckInId() { - return checkInId; - } + public Long getCheckInId() { return checkInId; } @Override public String toString() { return "OverviewId{" + "teamId=" + teamId + ", objectiveId=" + objectiveId + ", keyResultId=" + keyResultId - + ", checkInId=" + checkInId + '}'; + + ", checkInId=" + checkInId + '}'; } @Override @@ -61,7 +52,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..44a6801348 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializer.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/FlywayMultitenantMigrationInitializer.java @@ -11,7 +11,8 @@ 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; } @@ -20,10 +21,11 @@ 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")); + .map(TenantConfigProvider.TenantConfig::dataSourceConfig) + .orElseThrow(() -> new EntityNotFoundException("Cannot find tenant for configuring flyway migration")); - Flyway tenantSchemaFlyway = Flyway.configure() // + Flyway tenantSchemaFlyway = Flyway + .configure() // .dataSource(dataSourceConfig.url(), dataSourceConfig.name(), dataSourceConfig.password()) // .locations(scriptLocations) // .baselineOnMigrate(Boolean.TRUE) // 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..901d325405 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"; @@ -16,9 +15,7 @@ public class HibernateContext { public record DbConfig(String url, String username, String password, String multiTenancy) { - public boolean isValid() { - return !hasNullValues() && !hasEmptyValues(); - } + public boolean isValid() { return !hasNullValues() && !hasEmptyValues(); } private boolean hasNullValues() { return url() == null || username() == null || password() == null || multiTenancy() == null; 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..e75e0b1cfa 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); @@ -45,9 +44,7 @@ private String convertTenantIdToSchemaName(String tenantIdentifier) { } @Override - protected ConnectionProvider getAnyConnectionProvider() { - return getConnectionProvider(DEFAULT_TENANT_ID); - } + protected ConnectionProvider getAnyConnectionProvider() { return getConnectionProvider(DEFAULT_TENANT_ID); } @Override protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { @@ -55,24 +52,27 @@ protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) { } protected ConnectionProvider getConnectionProvider(String tenantIdentifier) { - return Optional.ofNullable(tenantIdentifier) // + return Optional + .ofNullable(tenantIdentifier) // .map(connectionProviderMap::get) // .orElseGet(() -> createNewConnectionProvider(tenantIdentifier)); } private ConnectionProvider createNewConnectionProvider(String tenantIdentifier) { - return Optional.ofNullable(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))); + .orElseThrow(() -> new ConnectionProviderException(String + .format("Cannot create new connection provider for tenant: %s", tenantIdentifier))); } private ConnectionProvider createConnectionProvider(String tenantIdentifier) { - return Optional.ofNullable(tenantIdentifier) // + return Optional + .ofNullable(tenantIdentifier) // .map(this::getHibernatePropertiesForTenantIdentifier) // .map(this::initConnectionProvider) // .orElse(null); @@ -109,7 +109,5 @@ private Map convertPropertiesToMap(Properties properties) { return configProperties; } - protected Properties getHibernateProperties() { - return HibernateContext.getHibernateConfig(); - } + protected Properties getHibernateProperties() { return HibernateContext.getHibernateConfig(); } } \ No newline at end of file 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..0b3b91ef3f 100644 --- a/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantConfigProvider.java +++ b/backend/src/main/java/ch/puzzle/okr/multitenancy/TenantConfigProvider.java @@ -1,56 +1,78 @@ 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)); + tenantConfigs + .put(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); + return Arrays + .stream(env + .getProperty(MessageFormat.format("okr.tenants.{0}.user.champion.emails", tenantId), "") + .split(EMAIL_DELIMITER)) + .map(String::trim) + .toArray(String[]::new); } - public List getTenantConfigs() { - return this.tenantConfigs.values().stream().toList(); - } + public List getTenantConfigs() { return this.tenantConfigs.values().stream().toList(); } 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 3749a7ec1f..b2886711d6 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 { @@ -23,12 +22,18 @@ public class TenantClientCustomizationProvider { private static final String ADD_OBJECTIVE_OUTLINE_COLOR = ".okr-add-objective-outline-color"; private final Map tenantCustomizations = new HashMap<>(); - private final List customCssStyles = List.of(TOPBAR_BACKGROUND_COLOR, BANNER_BACKGROUND_COLOR, - OVERVIEW_BACKGROUND_COLOR, TEAM_HEADER_COLOR, ADD_OBJECTIVE_TEXT_COLOR, ADD_OBJECTIVE_ICON, - ADD_OBJECTIVE_OUTLINE_COLOR); + private final List customCssStyles = List + .of(TOPBAR_BACKGROUND_COLOR, + BANNER_BACKGROUND_COLOR, + OVERVIEW_BACKGROUND_COLOR, + TEAM_HEADER_COLOR, + ADD_OBJECTIVE_TEXT_COLOR, + ADD_OBJECTIVE_ICON, + ADD_OBJECTIVE_OUTLINE_COLOR); private final Environment env; - 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); @@ -37,14 +42,29 @@ 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..12ab5a8af3 100644 --- a/backend/src/main/java/ch/puzzle/okr/repository/AlignmentRepository.java +++ b/backend/src/main/java/ch/puzzle/okr/repository/AlignmentRepository.java @@ -3,12 +3,11 @@ 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); 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..dcd03ab8bc 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,13 @@ 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); + @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..a1089c7d09 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 { 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..6e2034416e 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); @@ -39,9 +38,9 @@ public class JwtHelper { 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) { + @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; @@ -53,7 +52,8 @@ public User getUserFromJwt(Jwt token) { logger.debug("claims {}", claims); try { - return User.Builder.builder() // + return User.Builder + .builder() // .withFirstname(claims.get(firstname).toString()) // .withLastname(claims.get(lastname).toString()) // .withEmail(claims.get(email).toString()) // @@ -66,18 +66,20 @@ public User getUserFromJwt(Jwt token) { public String getTenantFromToken(Jwt token) { TokenHelper helper = new TokenHelper(); - List>> getTenantFromTokenFunctions = Arrays.asList( // - helper::getTenantFromTokenUsingClaimIss, // - helper::getTenantFromTokenUsingClaimTenant // - ); + List>> getTenantFromTokenFunctions = Arrays + .asList( // + helper::getTenantFromTokenUsingClaimIss, // + helper::getTenantFromTokenUsingClaimTenant // + ); return getFirstMatchingTenantUsingListOfHelperFunctions(token, getTenantFromTokenFunctions); } private String getFirstMatchingTenantUsingListOfHelperFunctions(Jwt token, - List>> getTenantFunctions) { + List>> getTenantFunctions) { - return getTenantFunctions.stream() // + return getTenantFunctions + .stream() // .map(func -> func.apply(token)) // .filter(Optional::isPresent) // .map(Optional::get) // @@ -88,28 +90,32 @@ private String getFirstMatchingTenantUsingListOfHelperFunctions(Jwt token, public String getTenantFromJWTClaimsSet(JWTClaimsSet claimSet) { ClaimHelper helper = new ClaimHelper(); - List>> getTenantFromClaimsSetFunctions = Arrays.asList( // - helper::getTenantFromClaimsSetUsingClaimIss, // - helper::getTenantFromClaimsSetUsingClaimTenant // - ); + List>> getTenantFromClaimsSetFunctions = Arrays + .asList( // + helper::getTenantFromClaimsSetUsingClaimIss, // + helper::getTenantFromClaimsSetUsingClaimTenant // + ); return getFirstMatchingTenantUsingListOfHelperFunctions(claimSet, getTenantFromClaimsSetFunctions); } private String getFirstMatchingTenantUsingListOfHelperFunctions(JWTClaimsSet claimSet, - List>> getTenantFunctions) { + List>> getTenantFunctions) { - return getTenantFunctions.stream() // + return getTenantFunctions + .stream() // .map(func -> func.apply(claimSet)) // .filter(Optional::isPresent) // .map(Optional::get) // - .map(this::getMatchingTenantFromConfigOrThrow).findFirst() // + .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) + return this.tenantConfigProvider + .getTenantConfigById(tenant) .orElseThrow(() -> new EntityNotFoundException(MessageFormat.format("Cannot find tenant {0}", tenant))) .tenantId(); } 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..0df2cbc8a2 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,9 +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) // + return this.selectors + .computeIfAbsent(toTenant(jwtClaimsSet), this::fromTenant) // .selectJWSKeys(jwsHeader, securityContext); } @@ -42,7 +43,8 @@ private String toTenant(JWTClaimsSet claimSet) { } private JWSKeySelector fromTenant(String tenantId) { - return this.tenantConfigProvider.getJwkSetUri(tenantId)// + return this.tenantConfigProvider + .getJwkSetUri(tenantId)// .map(this::fromUri) // .orElseThrow(() -> new IllegalArgumentException("unknown tenant")); } 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..4f84b487bc 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; @@ -31,7 +30,8 @@ public OAuth2TokenValidatorResult validate(Jwt token) { } private JwtIssuerValidator createValidatorForTenant(String tenant) { - return this.tenantConfigProvider.getTenantConfigById(tenant) // + return this.tenantConfigProvider + .getTenantConfigById(tenant) // .map(TenantConfigProvider.TenantConfig::issuerUrl) // .map(this::createValidator) // .orElseThrow(() -> new IllegalArgumentException("unknown tenant")); 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..364f77dc83 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,27 @@ 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..33980f8fad 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; } 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..b249332663 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,53 @@ 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)); + Objective objective = objectivePersistenceService + .findObjectiveById(keyResult.getObjective().getId(), + 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)); + Objective objective = objectivePersistenceService + .findObjectiveByKeyResultId(checkIn.getKeyResult().getId(), + 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) { @@ -108,59 +121,76 @@ 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)); + Objective objective = objectivePersistenceService + .findObjectiveById(keyResult.getObjective().getId(), + 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)); + Objective objective = objectivePersistenceService + .findObjectiveByKeyResultId(checkIn.getKeyResult().getId(), + 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..0dc6078cef 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; } @@ -60,12 +60,8 @@ public void deleteEntityById(ID id) { businessService.deleteEntityById(id); } - public AuthorizationService getAuthorizationService() { - return authorizationService; - } + public AuthorizationService getAuthorizationService() { return authorizationService; } - public BS getBusinessService() { - return (BS) businessService; - } + public BS getBusinessService() { return (BS) businessService; } } 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 c98338d477..97d8fbb38b 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 @@ -4,16 +4,14 @@ import ch.puzzle.okr.models.authorization.AuthorizationUser; import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.service.business.ObjectiveBusinessService; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - import java.util.List; +import org.springframework.stereotype.Service; @Service 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..76f9a9f1df 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,15 @@ 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 +39,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 +49,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..9ec8444c6e 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; @@ -54,14 +54,16 @@ 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)); + AuthorizationService + .checkRoleWriteAndReadAll(authorizationService.updateOrAddAuthorizationUser(), + 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)); + AuthorizationService + .checkRoleWriteAndReadAll(authorizationService.updateOrAddAuthorizationUser(), + OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_WRITE, USER)); return userBusinessService.createUsers(userList); } @@ -71,8 +73,9 @@ public boolean isUserMemberOfTeams(long id) { } public void deleteEntityById(long id) { - AuthorizationService.checkRoleWriteAndReadAll(authorizationService.updateOrAddAuthorizationUser(), - OkrResponseStatusException.of(ErrorKey.NOT_AUTHORIZED_TO_DELETE, USER)); + AuthorizationService + .checkRoleWriteAndReadAll(authorizationService.updateOrAddAuthorizationUser(), + 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/AlignmentBusinessService.java b/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentBusinessService.java index ea7d9644a9..4c4261fcf6 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentBusinessService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/business/AlignmentBusinessService.java @@ -5,9 +5,8 @@ import ch.puzzle.okr.models.keyresult.KeyResult; import ch.puzzle.okr.service.persistence.AlignmentPersistenceService; import ch.puzzle.okr.service.validation.AlignmentValidationService; -import org.springframework.stereotype.Service; - import java.util.List; +import org.springframework.stereotype.Service; @Service public class AlignmentBusinessService { @@ -15,7 +14,7 @@ public class AlignmentBusinessService { private final AlignmentValidationService validation; public AlignmentBusinessService(AlignmentPersistenceService alignmentPersistenceService, - AlignmentValidationService validation) { + AlignmentValidationService validation) { this.alignmentPersistenceService = alignmentPersistenceService; this.validation = validation; } 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..893a075c76 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); + return alignmentSelectionPersistenceService + .getAlignmentSelectionByQuarterIdAndTeamIdNot(quarterId, 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 { @@ -28,8 +26,9 @@ public class KeyResultBusinessService implements BusinessServiceInterface acti @Transactional public void deleteEntityById(Long id) { validator.validateOnDelete(id); - checkInBusinessService.getCheckInsByKeyResultId(id) + checkInBusinessService + .getCheckInsByKeyResultId(id) .forEach(checkIn -> checkInBusinessService.deleteEntityById(checkIn.getId())); - actionBusinessService.getActionsByKeyResultId(id) + actionBusinessService + .getActionsByKeyResultId(id) .forEach(action -> actionBusinessService.deleteEntityById(action.getId())); keyResultPersistenceService.deleteById(id); } @@ -126,7 +127,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 40f7eefd80..05f217180c 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 static final Logger logger = LoggerFactory.getLogger(ObjectiveBusinessService.class); @@ -29,8 +28,9 @@ public class ObjectiveBusinessService implements BusinessServiceInterface keyResultBusinessService.hasKeyResultAnyCheckIns(kr.getId())); } @@ -105,8 +107,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 @@ -121,7 +123,7 @@ public Objective createEntity(Objective objective, AuthorizationUser authorizati */ @Transactional public Objective duplicateObjective(Long id, Objective objective, AuthorizationUser authorizationUser, - List keyResults) { + List keyResults) { Objective duplicatedObjective = createEntity(objective, authorizationUser); for (KeyResult keyResult : keyResults) { duplicateKeyResult(authorizationUser, keyResult, duplicatedObjective); @@ -130,7 +132,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); @@ -141,7 +143,8 @@ private void duplicateKeyResult(AuthorizationUser authorizationUser, KeyResult k } private KeyResult makeCopyOfKeyResultMetric(KeyResult keyResult, Objective duplicatedObjective) { - return KeyResultMetric.Builder.builder() // + return KeyResultMetric.Builder + .builder() // .withObjective(duplicatedObjective) // .withTitle(keyResult.getTitle()) // .withDescription(keyResult.getDescription()) // @@ -153,7 +156,8 @@ private KeyResult makeCopyOfKeyResultMetric(KeyResult keyResult, Objective dupli } private KeyResult makeCopyOfKeyResultOrdinal(KeyResult keyResult, Objective duplicatedObjective) { - return KeyResultOrdinal.Builder.builder() // + return KeyResultOrdinal.Builder + .builder() // .withObjective(duplicatedObjective) // .withTitle(keyResult.getTitle()) // .withDescription(keyResult.getDescription()) // 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..677d6a626a 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,8 @@ 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..9da9e91722 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; } @@ -49,9 +48,7 @@ public List getQuarters() { return mostCurrentQuarterList; } - public Quarter getCurrentQuarter() { - return quarterPersistenceService.getCurrentQuarter(); - } + public Quarter getCurrentQuarter() { return quarterPersistenceService.getCurrentQuarter(); } private String shortenYear(int fullYear) { return padWithZeros(2, fullYear % 100); @@ -66,9 +63,11 @@ 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 +78,12 @@ 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); } @@ -92,9 +95,7 @@ private boolean inLastMonthOfQuarter(int currentQuarter, int nextQuarter) { return Math.abs(nextQuarter - currentQuarter) == 2; } - YearMonth getCurrentYearMonth() { - return YearMonth.now(); - } + YearMonth getCurrentYearMonth() { return YearMonth.now(); } Map generateQuarters() { Map quarters = new HashMap<>(); 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..e4b46423a7 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(); @@ -72,7 +72,8 @@ public Team updateTeam(Team team, Long id) { @Transactional public void deleteTeam(Long id) { validator.validateOnDelete(id); - objectiveBusinessService.getEntitiesByTeamId(id) + objectiveBusinessService + .getEntitiesByTeamId(id) .forEach(objective -> objectiveBusinessService.deleteEntityById(objective.getId())); deleteUserTeamList(id); cacheService.emptyAuthorizationUsersCache(); @@ -81,7 +82,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 +124,12 @@ 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() + 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")); + "No team found to remove from userTeam list")); userTeamList.remove(userTeamToRemove); team.getUserTeamList().remove(userTeamToRemove); userTeamPersistenceService.delete(userTeamToRemove); @@ -133,10 +138,13 @@ 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() + 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)); + 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..6abee4d545 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,15 +23,13 @@ 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; } - public List getAllUsers() { - return userPersistenceService.findAll(); - } + public List getAllUsers() { return userPersistenceService.findAll(); } public User getUserById(Long ownerId) { return userPersistenceService.findById(ownerId); @@ -55,9 +52,12 @@ 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() + 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)); + 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..29cc6ab69d 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,7 +76,7 @@ private Optional getTenantConfig(String hostn } private Optional getTenantClientCustomization(String hostname, - String... tenantsFromUrl) { + String... tenantsFromUrl) { for (String tenant : tenantsFromUrl) { Optional tenantCustomization = tenantClientCustomizationProvider .getTenantClientCustomizationsById(tenant); 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..8bbdab3f3b 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 { @@ -16,9 +15,7 @@ protected ActionPersistenceService(ActionRepository repository) { } @Override - public String getModelName() { - return ACTION; - } + public String getModelName() { return ACTION; } public List getActionsByKeyResultIdOrderByPriorityAsc(Long keyResultId) { return getRepository().getActionsByKeyResultIdOrderByPriorityAsc(keyResultId); 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..5844c60bd3 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 { @@ -18,9 +17,7 @@ protected AlignmentPersistenceService(AlignmentRepository repository) { } @Override - public String getModelName() { - return ALIGNMENT; - } + public String getModelName() { return ALIGNMENT; } public List findByAlignedObjectiveId(Long alignedObjectiveId) { return getRepository().findByAlignedObjectiveId(alignedObjectiveId); 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..02a5dbc7ed 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 { @@ -29,8 +28,9 @@ public String appendOverview(List teamIds, String objectiveQuery, Authoriz sb.append("\n and o.overviewId.teamId in (:" + PARAM_TEAM_IDS + ")"); } if (shouldAddObjectiveFilter(objectiveQuery)) { - sb.append("\n and lower(coalesce(o.objectiveTitle, '')) like lower(concat('%',:" + PARAM_OBJECTIVE_QUERY - + ",'%'))"); + 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 +50,14 @@ 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 +68,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..dbe00df18d 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 { @@ -16,9 +15,7 @@ protected CheckInPersistenceService(CheckInRepository repository) { } @Override - public String getModelName() { - return CHECK_IN; - } + public String getModelName() { return CHECK_IN; } public List getCheckInsByKeyResultIdOrderByCheckInDateDesc(Long keyResultId) { return getRepository().findCheckInsByKeyResultIdOrderByCreatedOnDesc(keyResultId); 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..7f89566973 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 { @@ -14,9 +14,7 @@ protected CompletedPersistenceService(CompletedRepository repository) { } @Override - public String getModelName() { - return COMPLETED; - } + public String getModelName() { return COMPLETED; } public Completed getCompletedByObjectiveId(Long objectiveId) { return getRepository().findByObjectiveId(objectiveId); 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 392ef8266e..837096e64e 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,16 +1,15 @@ 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 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.KEY_RESULT; - @Service public class KeyResultPersistenceService extends PersistenceBase { private static final Logger logger = LoggerFactory.getLogger(KeyResultPersistenceService.class); @@ -20,9 +19,7 @@ protected KeyResultPersistenceService(KeyResultRepository repository) { } @Override - public String getModelName() { - return KEY_RESULT; - } + public String getModelName() { return KEY_RESULT; } public List getKeyResultsByObjective(Long objectiveId) { return getRepository().findByObjectiveId(objectiveId); @@ -43,7 +40,8 @@ public KeyResult updateEntity(KeyResult keyResult) { } public List getKeyResultsOwnedByUser(long userId) { - return findAll().stream() // + return findAll() + .stream() // .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..81bf044d05 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,20 +28,19 @@ public class ObjectivePersistenceService extends PersistenceBase authorizationCriteria; protected ObjectivePersistenceService(ObjectiveRepository repository, EntityManager entityManager, - AuthorizationCriteria authorizationCriteria) { + AuthorizationCriteria authorizationCriteria) { super(repository); this.entityManager = entityManager; this.authorizationCriteria = authorizationCriteria; } @Override - public String getModelName() { - return OBJECTIVE; - } + public String getModelName() { return OBJECTIVE; } /** - * 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 +54,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 +63,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..8b189636da 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 @@ -35,9 +34,7 @@ protected PersistenceBase(CrudRepository repository) { } @SuppressWarnings(value = "unchecked casts") - public R getRepository() { - return (R) repository; - } + public R getRepository() { return (R) repository; } public T findById(ID id) throws OkrResponseStatusException { checkIdNull(id); @@ -59,8 +56,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()); } } @@ -76,6 +74,7 @@ public void deleteById(ID id) { private List iteratorToList(Iterable iterable) { return StreamSupport - .stream(Spliterators.spliteratorUnknownSize(iterable.iterator(), Spliterator.ORDERED), false).toList(); + .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..bb5a87902e 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 { @@ -17,9 +16,7 @@ protected QuarterPersistenceService(QuarterRepository repository) { } @Override - public String getModelName() { - return QUARTER; - } + public String getModelName() { return QUARTER; } public List getMostCurrentQuarters() { return getRepository().findTop6ByOrderByStartDateDescWithoutNullStartDate(); @@ -29,7 +26,5 @@ public Quarter findByLabel(String label) { return getRepository().findByLabel(label); } - public Quarter getCurrentQuarter() { - return getRepository().getActiveQuarter(LocalDate.now()); - } + public Quarter getCurrentQuarter() { return getRepository().getActiveQuarter(LocalDate.now()); } } 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..71b4f98ab1 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 { @@ -16,9 +15,7 @@ protected TeamPersistenceService(TeamRepository repository) { } @Override - public String getModelName() { - return TEAM; - } + public String getModelName() { return TEAM; } public List findTeamsByName(String name) { return getRepository().findTeamsByName(name); 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..209630b29c 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 { @@ -16,9 +15,7 @@ protected UserPersistenceService(UserRepository repository) { } @Override - public String getModelName() { - return USER; - } + public String getModelName() { return USER; } public synchronized User getOrCreateUser(User user) { Optional savedUser = getRepository().findByEmail(user.getEmail()); 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..22f932233b 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 { @@ -23,7 +22,5 @@ public void deleteAll(List userTeamList) { } @Override - public String getModelName() { - return USER_TEAM; - } + public String getModelName() { return USER_TEAM; } } 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 { AlignmentValidationService(AlignmentPersistenceService persistenceService) { super(persistenceService); diff --git a/backend/src/main/java/ch/puzzle/okr/service/validation/CheckInValidationService.java b/backend/src/main/java/ch/puzzle/okr/service/validation/CheckInValidationService.java index 87f3f14839..b1eedc6bc0 100644 --- a/backend/src/main/java/ch/puzzle/okr/service/validation/CheckInValidationService.java +++ b/backend/src/main/java/ch/puzzle/okr/service/validation/CheckInValidationService.java @@ -6,15 +6,15 @@ import ch.puzzle.okr.models.checkin.CheckIn; import ch.puzzle.okr.repository.CheckInRepository; import ch.puzzle.okr.service.persistence.CheckInPersistenceService; -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 CheckInValidationService - 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..560d61d2fe 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,16 @@ 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..48ed7abf15 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 @@ -39,9 +38,7 @@ public abstract class ValidationBase> violations) { } private List createErrorDtos(Set> violations) { - return violations.stream() // + 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(); + }) + .toList(); } // example: 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 9ea2c7511b..449f9a640b 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,19 @@ 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,7 +37,11 @@ void repositoryAccessedOnlyByPersistenceService() { @Test void mapperAccessedByControllerOrAuthorization() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..mapper..").should().onlyBeAccessed() + ArchRule rule = classes() + .that() + .resideInAPackage("..mapper..") + .should() + .onlyBeAccessed() .byAnyPackage("..controller..", "..mapper..", "..authorization.."); rule.check(importedClasses); @@ -40,7 +50,11 @@ void mapperAccessedByControllerOrAuthorization() { @Test void authorizationServiceAccessedByControllerOrAuthorization() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..service.authorization..").should().onlyBeAccessed() + ArchRule rule = classes() + .that() + .resideInAPackage("..service.authorization..") + .should() + .onlyBeAccessed() .byAnyPackage("..controller..", "..authorization.."); rule.check(importedClasses); @@ -49,7 +63,11 @@ void authorizationServiceAccessedByControllerOrAuthorization() { @Test void businessServiceAccessedByControllerOrAuthorizationServiceOrMapper() { JavaClasses importedClasses = getMainSourceClasses(); - ArchRule rule = classes().that().resideInAPackage("..service.business..").should().onlyBeAccessed() + ArchRule rule = classes() + .that() + .resideInAPackage("..service.business..") + .should() + .onlyBeAccessed() .byAnyPackage("..controller..", "..authorization..", "..mapper..", "..business", "..deserializer"); rule.check(importedClasses); @@ -59,8 +77,14 @@ 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 +93,14 @@ 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 +109,15 @@ 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,8 +126,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() + 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 +145,15 @@ 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,11 +161,19 @@ 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() + ArchRule rule = classes() + .that() + .haveSimpleName(repository) + .should() + .onlyHaveDependentClassesThat() + .haveSimpleName(persistenceService) + .orShould() + .haveSimpleName(repository) + .orShould() .haveSimpleName(validationService); rule.check(importedClasses); @@ -124,8 +184,13 @@ void repositoriesShouldOnlyBeCalledFromPersistenceServicesAndValidationService(S 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); } @@ -133,31 +198,48 @@ void classesInRightPackages(String passedName) { @Test 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..") // - .layer("Deserializer").definedBy("..deserializer..") // - - .whereLayer("Controller").mayNotBeAccessedByAnyLayer() // - .whereLayer("AuthorizationService").mayOnlyBeAccessedByLayers("Controller") // + 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..") // + .layer("Deserializer") + .definedBy("..deserializer..") // + + .whereLayer("Controller") + .mayNotBeAccessedByAnyLayer() // + .whereLayer("AuthorizationService") + .mayOnlyBeAccessedByLayers("Controller") // .whereLayer("BusinessService") - .mayOnlyBeAccessedByLayers("Controller", "AuthorizationService", "Mapper", "BusinessService", - "Deserializer") // - .whereLayer("ValidationService").mayOnlyBeAccessedByLayers("BusinessService") // + .mayOnlyBeAccessedByLayers("Controller", + "AuthorizationService", + "Mapper", + "BusinessService", + "Deserializer") // + .whereLayer("ValidationService") + .mayOnlyBeAccessedByLayers("BusinessService") // .whereLayer("PersistenceService") .mayOnlyBeAccessedByLayers("BusinessService", "PersistenceService", "ValidationService") // - .whereLayer("Repository").mayOnlyBeAccessedByLayers("PersistenceService"); // + .whereLayer("Repository") + .mayOnlyBeAccessedByLayers("PersistenceService"); // layeredArchitecture.check(importedClasses); } private static JavaClasses getMainSourceClasses() { - return new ClassFileImporter().withImportOption(new ImportOption.DoNotIncludeTests()) + return new ClassFileImporter() + .withImportOption(new ImportOption.DoNotIncludeTests()) .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..c58ec40e94 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,15 +73,24 @@ 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())) + 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()); @@ -91,8 +99,11 @@ 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())) + 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()); @@ -101,16 +112,19 @@ void updateSuccessfulOnlyOneAction() throws Exception { @Test void shouldDeleteAction() throws Exception { - mvc.perform(delete("/api/v2/action/1").with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete("/api/v2/action/1").with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void throwExceptionWhenActionWithIdCantBeFoundWhileDeleting() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Action not found")).when(actionAuthorizationService) + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Action not found")) + .when(actionAuthorizationService) .deleteActionByActionId(anyLong()); - mvc.perform(delete("/api/v2/action/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete("/api/v2/action/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) .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..f9c40ae2c2 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,49 @@ 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 AlignmentSelection alignmentSelectionEmptyKeyResults = AlignmentSelection.Builder.builder() - .withAlignmentSelectionId(AlignmentSelectionId.of(8L, null)).withObjectiveTitle("Objective 8").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(); @Test void shouldGetAllObjectivesWithKeyResults() throws Exception { @@ -62,36 +88,49 @@ void shouldGetAllObjectivesWithKeyResults() throws Exception { alignmentSelections.addAll(alignmentSelectionPuzzle); alignmentSelections.addAll(alignmentSelectionOKR); alignmentSelections.add(alignmentSelectionEmptyKeyResults); - BDDMockito.given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, 4L)) + BDDMockito + .given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, 4L)) .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))) + 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("$[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())) + BDDMockito + .given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(any(), any())) .willReturn(Collections.emptyList()); - mvc.perform(get("/api/v2/alignments/selections").contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()).andExpect(jsonPath("$", Matchers.hasSize(0))); + mvc + .perform(get("/api/v2/alignments/selections").contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnObjectiveWithEmptyKeyResultListWhenNoKeyResultsInFilteredQuarter() throws Exception { - BDDMockito.given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, 4L)) + BDDMockito + .given(alignmentSelectionBusinessService.getAlignmentSelectionByQuarterIdAndTeamIdNot(2L, 4L)) .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))); + 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))); } } 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..1c23c80fc9 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,15 +27,17 @@ class CacheControllerIT { @Test void shouldEmptyAuthorisationUsersCache() throws Exception { - mvc.perform( - post("/api/v2/caches/emptyAuthorizationUsersCache").with(SecurityMockMvcRequestPostProcessors.csrf())) + 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())) + mvc + .perform(post("/api/v2/caches/emptyAllCaches").with(SecurityMockMvcRequestPostProcessors.csrf())) .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 04201bca78..a662071aeb 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/CheckInControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/CheckInControllerIT.java @@ -1,13 +1,20 @@ 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.deserializer.DeserializerHelper; 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; @@ -27,14 +34,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) @@ -60,8 +59,10 @@ void setUp() { 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))) + 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))) @@ -74,8 +75,10 @@ void shouldGetMetricCheckInWithId() throws Exception { 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))) + 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))) @@ -86,23 +89,30 @@ void shouldGetOrdinalCheckInWithId() throws Exception { @Test void shouldNotFindTheCheckInWithId() throws Exception { - BDDMockito.given(checkInAuthorizationService.getEntityById(anyLong())) + BDDMockito + .given(checkInAuthorizationService.getEntityById(anyLong())) .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); - mvc.perform(get(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON)) + mvc + .perform(get(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void shouldReturnUpdatedCheckIn() throws Exception { - BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) + BDDMockito + .given(keyResultBusinessService.getEntityById(anyLong())) .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))) + 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))) @@ -111,26 +121,36 @@ void shouldReturnUpdatedCheckIn() throws Exception { @Test void shouldReturnNotFound() throws Exception { - BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) + BDDMockito + .given(keyResultBusinessService.getEntityById(anyLong())) .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); BDDMockito.given(checkInMapper.toCheckIn(any())).willReturn(checkInMetric); - BDDMockito.given(checkInAuthorizationService.updateEntity(anyLong(), any())) + BDDMockito + .given(checkInAuthorizationService.updateEntity(anyLong(), any())) .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found")); - mvc.perform(put(CHECK_IN_5_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) + mvc + .perform(put(CHECK_IN_5_URL) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void shouldCreateKeyResultMetric() throws Exception { - BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) + BDDMockito + .given(keyResultBusinessService.getEntityById(anyLong())) .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))) + 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))) @@ -140,13 +160,18 @@ void shouldCreateKeyResultMetric() throws Exception { @Test void shouldCreateKeyResultOrdinal() throws Exception { - BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) + BDDMockito + .given(keyResultBusinessService.getEntityById(anyLong())) .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))) + 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))) @@ -156,12 +181,16 @@ void shouldCreateKeyResultOrdinal() throws Exception { @Test void shouldThrowExceptionWhenKeyResultIdMissing() throws Exception { - BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) + BDDMockito + .given(keyResultBusinessService.getEntityById(anyLong())) .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)) + mvc + .perform(post(CHECK_IN_BASE_URL) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON_WITHOUT_KEY_RESULT_ID)) .andExpect(MockMvcResultMatchers.status().is4xxClientError()); } @@ -171,17 +200,22 @@ void shouldReturnClientErrorForKeyResultNotOfTypeMetricOrOrdinal() throws Except class NonMetricOrOrdinalKeyResult extends KeyResult { } - BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) + BDDMockito + .given(keyResultBusinessService.getEntityById(anyLong())) .willReturn(new NonMetricOrOrdinalKeyResult()); - mvc.perform(post(CHECK_IN_BASE_URL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf()).content(JSON)) + mvc + .perform(post(CHECK_IN_BASE_URL) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(JSON)) .andExpect(MockMvcResultMatchers.status().is4xxClientError()); } @Test void shouldDeleteCheckInById() throws Exception { - mvc.perform(delete(CHECK_IN_5_URL).with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete(CHECK_IN_5_URL).with(SecurityMockMvcRequestPostProcessors.csrf())) .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..e538605b3b 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) @@ -36,7 +35,8 @@ public class ClientConfigControllerIT { void shouldGetClientConfig() throws Exception { BDDMockito.given(configService.getConfigBasedOnActiveEnv(anyString())).willReturn(createClientConfigDto()); - mvc.perform(get("/config").contentType(MediaType.APPLICATION_JSON)) + 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"))) @@ -54,8 +54,16 @@ void shouldGetClientConfig() throws Exception { 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..9732dcb64e 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) @@ -56,18 +56,22 @@ class CompletedControllerIT { @MockBean private CompletedMapper completedMapper; - private final Completed successfulCompleted = Completed.Builder.builder() // + private final Completed successfulCompleted = Completed.Builder + .builder() // .withId(COMPLETED_ID) // - .withObjective(Objective.Builder.builder() // + .withObjective(Objective.Builder + .builder() // .withId(OBJECTIVE_ID) // .build()) // .withComment(COMPLETED_COMMENT) // .build(); - private final CompletedDto completedDto = CompletedDtoBuilder.builder() // + private final CompletedDto completedDto = CompletedDtoBuilder + .builder() // .withId(COMPLETED_ID) // .withComment(COMPLETED_COMMENT) // - .withObjectiveDto(ObjectiveDtoBuilder.builder() // + .withObjectiveDto(ObjectiveDtoBuilder + .builder() // .withId(OBJECTIVE_ID) // .build()) // .build(); @@ -87,10 +91,11 @@ void setUp() { 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())) // + 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))) // @@ -101,7 +106,8 @@ void createShouldCreateCompleted() throws Exception { @DisplayName("delete() should delete Completed") @Test void deleteShouldDeleteCompleted() throws Exception { - mvc.perform(delete("/api/v2/completed/1").with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete("/api/v2/completed/1").with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(MockMvcResultMatchers.status().isOk()); } @@ -109,9 +115,11 @@ void deleteShouldDeleteCompleted() throws Exception { @Test void deleteShouldThrowExceptionWhenCompletedWithIdCantBeFound() throws Exception { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Completed not found")) - .when(completedAuthorizationService).deleteCompletedByObjectiveId(anyLong()); + .when(completedAuthorizationService) + .deleteCompletedByObjectiveId(anyLong()); - mvc.perform(delete("/api/v2/completed/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete("/api/v2/completed/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) .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 dbf4ed5d04..b6d333745e 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.deserializer.DeserializerHelper; import ch.puzzle.okr.mapper.ActionMapper; import ch.puzzle.okr.mapper.checkin.CheckInMapper; @@ -12,6 +22,9 @@ import ch.puzzle.okr.service.business.KeyResultBusinessService; 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; @@ -31,20 +44,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) @@ -82,8 +81,10 @@ void shouldGetMetricKeyResultWithId() throws Exception { BDDMockito.given(keyResultAuthorizationService.getEntityById(anyLong())).willReturn(metricKeyResult); 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))) + 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))) @@ -102,8 +103,10 @@ void shouldGetOrdinalKeyResultWithId() throws Exception { BDDMockito.given(keyResultAuthorizationService.getEntityById(anyLong())).willReturn(ordinalKeyResult); 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))) + 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))) @@ -120,11 +123,14 @@ void shouldGetOrdinalKeyResultWithId() throws Exception { @Test void shouldNotFindTheKeyResultWithGivenId() throws Exception { - BDDMockito.given(keyResultAuthorizationService.getEntityById(anyLong())) + BDDMockito + .given(keyResultAuthorizationService.getEntityById(anyLong())) .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()); + mvc + .perform(get(URL_TO_KEY_RESULT_55).contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isNotFound()) + .andExpect(status().isNotFound()); } @Test @@ -134,33 +140,44 @@ void shouldReturnCheckInsFromKeyResult() throws Exception { BDDMockito.given(checkInMapper.toDto(checkIn1)).willReturn(checkInDto1); 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))) + 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("$[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())) + BDDMockito + .given(keyResultAuthorizationService.getAllCheckInsByKeyResult(anyLong())) .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))); + mvc + .perform(get(URL_TO_KEY_RESULT_1_CHECK_IN).contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnErrorWhenKeyResultDoesntExistWhenGettingCheckInsFromKeyResult() throws Exception { - BDDMockito.given(keyResultAuthorizationService.getAllCheckInsByKeyResult(anyLong())) + BDDMockito + .given(keyResultAuthorizationService.getAllCheckInsByKeyResult(anyLong())) .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()); + mvc + .perform(get(URL_TO_KEY_RESULT_1_CHECK_IN).contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isNotFound()) + .andExpect(status().isNotFound()); } @Test @@ -169,9 +186,13 @@ 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))) + 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))) @@ -194,9 +215,13 @@ 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))) + 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))) @@ -214,10 +239,22 @@ 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); @@ -227,9 +264,13 @@ 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))) + 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))) @@ -247,15 +288,21 @@ 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())) + 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())) + mvc + .perform(post(URL_BASE) + .content(CREATE_BODY_KEY_RESULT_TYPE_UNKNOWN) + .contentType(MediaType.APPLICATION_JSON) + .with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(MockMvcResultMatchers.status().is4xxClientError()); } @@ -265,9 +312,13 @@ 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))) + 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))) @@ -282,32 +333,44 @@ void createEntityWithEnumKeys() throws Exception { @Test void createEntityShouldThrowErrorWhenInvalidDto() throws Exception { - BDDMockito.given(keyResultMapper.toKeyResult(any())) + BDDMockito + .given(keyResultMapper.toKeyResult(any())) .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Error")); - BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) + BDDMockito + .given(keyResultBusinessService.getEntityById(anyLong())) .willReturn(KeyResultOrdinal.Builder.builder().withId(1L).build()); - mvc.perform(post(URL_BASE).content(CREATE_BODY_ORDINAL).contentType(MediaType.APPLICATION_JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) + 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())) + BDDMockito + .given(keyResultAuthorizationService.updateEntities(anyLong(), any(), anyList())) .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())) + BDDMockito + .given(keyResultAuthorizationService.updateEntities(anyLong(), any(), anyList())) .willReturn(new KeyResultWithActionList(metricKeyResult, List.of())); - BDDMockito.given(keyResultBusinessService.getEntityById(anyLong())) + BDDMockito + .given(keyResultBusinessService.getEntityById(anyLong())) .willReturn(KeyResultMetric.Builder.builder().withId(1L).build()); - 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))) + 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))) @@ -315,7 +378,8 @@ void shouldReturnUpdatedKeyResult() throws Exception { .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(); + .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()); @@ -323,15 +387,20 @@ void shouldReturnUpdatedKeyResult() throws Exception { @Test void shouldReturnUpdatedKeyResultWithImUsed() throws Exception { - BDDMockito.given(keyResultAuthorizationService.updateEntities(anyLong(), any(), anyList())) + BDDMockito + .given(keyResultAuthorizationService.updateEntities(anyLong(), any(), anyList())) .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))) + 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))) @@ -339,7 +408,8 @@ void shouldReturnUpdatedKeyResultWithImUsed() throws Exception { .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(); + .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()); @@ -348,34 +418,43 @@ 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())) + .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())) + BDDMockito + .given(keyResultAuthorizationService.updateEntity(any(), any())) .willThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Bad request while updating keyresult")); - mvc.perform(put(URL_TO_KEY_RESULT_10).with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(put(URL_TO_KEY_RESULT_10).with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(MockMvcResultMatchers.status().isBadRequest()); } @Test void shouldDeleteKeyResult() throws Exception { - mvc.perform(delete(URL_TO_KEY_RESULT_10).with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete(URL_TO_KEY_RESULT_10).with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void throwExceptionWhenKeyResultWithIdCantBeFoundWhileDeleting() throws Exception { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Keyresult not found")) - .when(keyResultAuthorizationService).deleteEntityById(anyLong()); + .when(keyResultAuthorizationService) + .deleteEntityById(anyLong()); - mvc.perform(delete(URL_TO_KEY_RESULT_1000).with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete(URL_TO_KEY_RESULT_1000).with(SecurityMockMvcRequestPostProcessors.csrf())) .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 4a223397f8..eeb5df3003 100644 --- a/backend/src/test/java/ch/puzzle/okr/controller/ObjectiveControllerIT.java +++ b/backend/src/test/java/ch/puzzle/okr/controller/ObjectiveControllerIT.java @@ -1,5 +1,12 @@ package ch.puzzle.okr.controller; +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 ch.puzzle.okr.deserializer.DeserializerHelper; import ch.puzzle.okr.dto.ObjectiveDto; import ch.puzzle.okr.mapper.ObjectiveMapper; @@ -10,6 +17,7 @@ import ch.puzzle.okr.service.authorization.ActionAuthorizationService; 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; @@ -28,15 +36,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.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; - @WithMockUser(value = "spring") @ExtendWith(MockitoExtension.class) @WebMvcTest(ObjectiveController.class) @@ -80,21 +79,57 @@ 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) + 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) + 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 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; @@ -121,30 +156,46 @@ void setUp() { 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))) + 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))); } @Test void getObjectiveByIdFail() throws Exception { - BDDMockito.given(objectiveAuthorizationService.getEntityById(anyLong())) + BDDMockito + .given(objectiveAuthorizationService.getEntityById(anyLong())) .willThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)); - mvc.perform(get(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON)) + mvc + .perform(get(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON)) .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)) + 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)); verify(objectiveAuthorizationService, times(1)).createEntity(any()); @@ -152,27 +203,49 @@ void shouldReturnObjectiveWhenCreatingNewObjective() throws Exception { @Test void shouldReturnResponseStatusExceptionWhenCreatingObjectiveWithNullValues() throws Exception { - 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())) + 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()); } @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()) + 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))); @@ -180,10 +253,23 @@ void shouldReturnUpdatedObjective() throws Exception { @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) + 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); @@ -191,56 +277,74 @@ void shouldReturnImUsed() throws Exception { 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())) + 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")); - - mvc.perform(put(URL_OBJECTIVE_10).contentType(MediaType.APPLICATION_JSON).content(JSON) - .with(SecurityMockMvcRequestPostProcessors.csrf())) + 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()); } @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())) + mvc + .perform(put(URL_OBJECTIVE_10).with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(MockMvcResultMatchers.status().isBadRequest()); } @Test void shouldDeleteObjective() throws Exception { - mvc.perform(delete(URL_OBJECTIVE_10).with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete(URL_OBJECTIVE_10).with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void throwExceptionWhenObjectiveWithIdCantBeFoundWhileDeleting() throws Exception { doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Objective not found")) - .when(objectiveAuthorizationService).deleteEntityById(anyLong()); + .when(objectiveAuthorizationService) + .deleteEntityById(anyLong()); - mvc.perform(delete("/api/v2/objectives/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete("/api/v2/objectives/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test void shouldReturnIsCreatedWhenObjectiveWasDuplicated() throws Exception { - BDDMockito.given(objectiveAuthorizationService.duplicateEntity(anyLong(), any(), anyList())) + BDDMockito + .given(objectiveAuthorizationService.duplicateEntity(anyLong(), any(), anyList())) .willReturn(objective1); BDDMockito.given(keyResultMapper.toDto(any(KeyResultMetric.class), any())).willReturn(keyResultMetricDto); BDDMockito.given(keyResultMapper.toDto(any(KeyResultOrdinal.class), any())).willReturn(keyResultOrdinalDto); BDDMockito.given(objectiveAuthorizationService.getAuthorizationService()).willReturn(authorizationService); BDDMockito.given(objectiveMapper.toDto(objective1)).willReturn(objective1Dto); - mvc.perform(post(URL_DUPLICATE_OBJECTIVE_5).with(SecurityMockMvcRequestPostProcessors.csrf()) - .content(DUPLICATE_OBJECTIVE).contentType(MediaType.APPLICATION_JSON)) + mvc + .perform(post(URL_DUPLICATE_OBJECTIVE_5) + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .content(DUPLICATE_OBJECTIVE) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id", Is.is(objective1Dto.id().intValue()))) .andExpect(jsonPath("$.description", Is.is(objective1Dto.description()))) .andExpect(jsonPath(JSON_PATH_TITLE, Is.is(objective1Dto.title()))); 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..5e6dc0b997 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,100 @@ 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 { @@ -92,31 +154,37 @@ void shouldGetAllTeamsWithObjective() throws Exception { overviews.addAll(overviewPuzzle); overviews.addAll(overviewOKR); overviews.add(overviewKuchen); - BDDMockito.given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) + BDDMockito + .given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) .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)) + 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("$[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("$[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())) + BDDMockito + .given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) .willReturn(Collections.emptyList()); BDDMockito.given(overviewAuthorizationService.hasWriteAllAccess()).willReturn(true); - mvc.perform(get("/api/v2/overview").contentType(MediaType.APPLICATION_JSON)) + mvc + .perform(get("/api/v2/overview").contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(jsonPath(JSON_PATH_ROOT, Matchers.hasSize(0))); } @@ -125,26 +193,31 @@ void shouldGetAllTeamsWithObjectiveIfNoTeamsExists() throws Exception { void shouldReturnOnlyFilteredObjectivesByQuarterAndTeam() throws Exception { List overviews = new ArrayList<>(overviewPuzzle); overviews.add(overviewKuchen); - BDDMockito.given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) + BDDMockito + .given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) .willReturn(overviews); - mvc.perform(get("/api/v2/overview?quarter=2&team=1,3").contentType(MediaType.APPLICATION_JSON)) + 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("$[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())) + BDDMockito + .given(overviewAuthorizationService.getFilteredOverview(anyLong(), anyList(), anyString())) .willReturn(List.of(simpleOverview)); - mvc.perform(get("/api/v2/overview?quarter=2&team=4").contentType(MediaType.APPLICATION_JSON)) + 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))) 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..28f7e95314 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,32 @@ 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 @@ -49,12 +63,16 @@ class QuarterControllerIT { 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"))) + 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].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))) @@ -65,8 +83,10 @@ void shouldGetAllQuarters() throws Exception { 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))); + mvc + .perform(get("/api/v2/quarters").contentType(MediaType.APPLICATION_JSON)) + .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..3aebd55fad 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) @@ -87,10 +86,14 @@ void setUp() { 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"))); + 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"))); } @Test @@ -105,27 +108,37 @@ void shouldGetAllTeamsWhenNoQuarterParamIsPassed() throws Exception { 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))); + mvc + .perform(get("/api/v2/teams?quarterId=1").contentType(MediaType.APPLICATION_JSON)) + .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())) + 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())) + 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()); } @@ -137,8 +150,12 @@ 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()) + 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()))); @@ -146,55 +163,76 @@ void shouldReturnUpdatedTeam() throws Exception { @Test void shouldReturnNotFound() throws Exception { - BDDMockito.given(teamAuthorizationService.updateEntity(any(), anyLong())) + BDDMockito + .given(teamAuthorizationService.updateEntity(any(), anyLong())) .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())) + 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())) + BDDMockito + .given(teamAuthorizationService.updateEntity(any(), anyLong())) .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())) + 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())) + mvc + .perform(delete(URL_TEAM_1).with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test void throwExceptionWhenOTeamWithIdCantBeFoundWhileDeleting() throws Exception { - doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Team not found")).when(teamAuthorizationService) + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Team not found")) + .when(teamAuthorizationService) .deleteEntity(anyLong()); - mvc.perform(delete(URL_TEAM_1).with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete(URL_TEAM_1).with(SecurityMockMvcRequestPostProcessors.csrf())) .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())) + 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()); } @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..87219c0775 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,20 @@ 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); @@ -72,11 +81,15 @@ void setUp() { 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))) + 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("$[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))); @@ -86,17 +99,21 @@ void shouldGetAllUsers() throws Exception { 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))); + mvc + .perform(get("/api/v1/users").contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(jsonPath("$", Matchers.hasSize(0))); } @Test void shouldReturnCurrentUser() throws Exception { - BDDMockito.given(authorizationService.updateOrAddAuthorizationUser()) + BDDMockito + .given(authorizationService.updateOrAddAuthorizationUser()) .willReturn(new AuthorizationUser(userAlice)); BDDMockito.given(userMapper.toDto(userAlice)).willReturn(userAliceDto); - mvc.perform(get("/api/v1/users/current").contentType(MediaType.APPLICATION_JSON)) + 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))) // @@ -113,7 +130,8 @@ void shouldReturnUserById() throws Exception { BDDMockito.given(userAuthorizationService.getById(2)).willReturn(userAlice); BDDMockito.given(userMapper.toDto(userAlice)).willReturn(userAliceDto); - mvc.perform(get("/api/v1/users/2").contentType(MediaType.APPLICATION_JSON)) // + 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))) // @@ -130,11 +148,12 @@ void shouldSetOkrChampion() throws Exception { BDDMockito.given(userAuthorizationService.setIsOkrChampion(2, true)).willReturn(userAlice); 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()) // - ) // + mvc + .perform(put("/api/v1/users/2/isokrchampion/true") // + .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))) // @@ -151,11 +170,12 @@ void shouldCreateUsers() throws Exception { BDDMockito.given(userAuthorizationService.createUsers(any())).willReturn(List.of(userAlice)); 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()) // - ) // + mvc + .perform(post("/api/v1/users/createall") // + .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))) // @@ -169,17 +189,20 @@ void shouldCreateUsers() throws Exception { @Test void shouldDeleteUser() throws Exception { - mvc.perform(delete("/api/v1/users/10").with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete("/api/v1/users/10").with(SecurityMockMvcRequestPostProcessors.csrf())) .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) + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found")) + .when(userAuthorizationService) .deleteEntityById(1000); - mvc.perform(delete("/api/v1/users/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) + mvc + .perform(delete("/api/v1/users/1000").with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(MockMvcResultMatchers.status().isNotFound()); } 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 ab9f43c687..2dd743dc58 100644 --- a/backend/src/test/java/ch/puzzle/okr/deserializer/CheckInDeserializerTest.java +++ b/backend/src/test/java/ch/puzzle/okr/deserializer/CheckInDeserializerTest.java @@ -1,12 +1,21 @@ package ch.puzzle.okr.deserializer; +import static ch.puzzle.okr.test.CheckInTestHelpers.*; +import static ch.puzzle.okr.test.CheckInTestHelpers.CHECK_IN_METRIC_JSON; +import static ch.puzzle.okr.test.KeyResultTestHelpers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; +import static org.mockito.Mockito.times; + import ch.puzzle.okr.Constants; import ch.puzzle.okr.models.keyresult.KeyResult; -import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.business.KeyResultBusinessService; import ch.puzzle.okr.test.*; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.*; +import java.util.stream.Stream; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -15,17 +24,6 @@ import org.mockito.*; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.stream.Stream; - -import static ch.puzzle.okr.test.CheckInTestHelpers.*; -import static ch.puzzle.okr.test.CheckInTestHelpers.CHECK_IN_METRIC_JSON; -import static ch.puzzle.okr.test.KeyResultTestHelpers.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; -import static org.mockito.Mockito.times; - @ExtendWith(MockitoExtension.class) class CheckInDeserializerTest { @Mock @@ -55,8 +53,9 @@ void deserializeShouldReturnCheckInMetricDtoForMetricJson() throws Exception { } private static Stream checkInTypes() { - return Stream.of(Arguments.of(metricKeyResult, CHECK_IN_METRIC_JSON, "metric"), - Arguments.of(ordinalKeyResult, CHECK_IN_ORDINAL_JSON, "ordinal")); + return Stream + .of(Arguments.of(metricKeyResult, CHECK_IN_METRIC_JSON, "metric"), + Arguments.of(ordinalKeyResult, CHECK_IN_ORDINAL_JSON, "ordinal")); } @DisplayName("deserialize() should call helper with correct params") diff --git a/backend/src/test/java/ch/puzzle/okr/deserializer/DeserializerHelperTest.java b/backend/src/test/java/ch/puzzle/okr/deserializer/DeserializerHelperTest.java index 7d701d6948..293c8167d1 100644 --- a/backend/src/test/java/ch/puzzle/okr/deserializer/DeserializerHelperTest.java +++ b/backend/src/test/java/ch/puzzle/okr/deserializer/DeserializerHelperTest.java @@ -1,5 +1,10 @@ package ch.puzzle.okr.deserializer; +import static ch.puzzle.okr.Constants.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.dto.checkin.*; import ch.puzzle.okr.dto.keyresult.*; import ch.puzzle.okr.models.Unit; @@ -8,6 +13,7 @@ import ch.puzzle.okr.test.KeyResultTestHelpers; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Map; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.*; @@ -15,13 +21,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.Map; - -import static ch.puzzle.okr.Constants.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) class DeserializerHelperTest { 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 c1a275e8fa..9d719a5dfd 100644 --- a/backend/src/test/java/ch/puzzle/okr/deserializer/KeyResultDeserializerTest.java +++ b/backend/src/test/java/ch/puzzle/okr/deserializer/KeyResultDeserializerTest.java @@ -1,10 +1,17 @@ package ch.puzzle.okr.deserializer; +import static ch.puzzle.okr.test.KeyResultTestHelpers.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; +import static org.mockito.Mockito.times; + import ch.puzzle.okr.Constants; import ch.puzzle.okr.test.KeyResultTestHelpers; import ch.puzzle.okr.test.TestHelper; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.*; +import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -14,16 +21,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.mockito.*; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.http.HttpStatus; -import org.springframework.web.server.ResponseStatusException; - -import java.util.stream.Stream; - -import static ch.puzzle.okr.test.KeyResultTestHelpers.*; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; -import static org.mockito.Mockito.times; @ExtendWith(MockitoExtension.class) class KeyResultDeserializerTest { @@ -61,8 +58,8 @@ void deserializeShouldReturnKeyResultMetricDtoForMetricJson() throws Exception { } private static Stream keyResultTypes() { - return Stream.of(Arguments.of(KEY_RESULT_METRIC_JSON, "metric"), - Arguments.of(KEY_RESULT_ORDINAL_JSON, "ordinal")); + return Stream + .of(Arguments.of(KEY_RESULT_METRIC_JSON, "metric"), Arguments.of(KEY_RESULT_ORDINAL_JSON, "ordinal")); } @DisplayName("deserialize() should call helper with correct params") 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..6dbde44b55 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 { @@ -48,7 +47,8 @@ void setup() { @Test void toDtoShouldMapActionToDto() { // arrange - Action action = Action.Builder.builder() // + Action action = Action.Builder + .builder() // .withId(ID) // .withVersion(VERSION) // .withAction(ACTION) // @@ -107,12 +107,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 +123,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 +134,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..2c70cc5a64 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(); @@ -24,9 +23,14 @@ 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()); + List alignmentSelections = List + .of(AlignmentSelection.Builder + .builder() + .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()); @@ -35,11 +39,19 @@ 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()); + 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()); List alignmentObjectiveDtos = alignmentSelectionMapper.toDto(alignmentSelections); assertEquals(1, alignmentObjectiveDtos.size()); @@ -48,17 +60,31 @@ 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 +93,43 @@ 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..cb223a37d0 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; @@ -49,10 +49,12 @@ void setUp() { @Test void toDtoShouldMapCompletedToDto() { // arrange - var completed = Completed.Builder.builder() // + var completed = Completed.Builder + .builder() // .withId(COMPLETED_ID) // .withComment(COMPLETED_COMMENT) // - .withObjective(Objective.Builder.builder() // + .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()) // @@ -77,8 +79,12 @@ 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..bd610940f3 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 { @@ -39,7 +38,8 @@ public class ObjectiveMapperTest { private static final LocalDateTime MODIFIED_DATE_TIME = LocalDateTime.of(2024, Month.MAY, 21, 8, 0, 0); private final Team team = Team.Builder.builder().withId(TEAM_ID).build(); - private final Quarter quarter = Quarter.Builder.builder() // + private final Quarter quarter = Quarter.Builder + .builder() // .withId(QUARTER_ID) // .withLabel(QUARTER_LABEL) // .build(); @@ -61,7 +61,8 @@ void setup() { @Test void toDtoShouldMapObjectiveToDto() { // arrange - Objective objective = Objective.Builder.builder() // + Objective objective = Objective.Builder + .builder() // .withId(ID) // .withVersion(VERSION) // .withTitle(TITLE) // 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 49236bb00e..b04dedc890 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 { @@ -39,8 +38,12 @@ void toDtoShouldReturnEmptyListWhenNoTeamFound() { @Test void toDtoShouldReturnEmptyListWhenTeamFound() { - List overviews = List.of(Overview.Builder.builder() - .withOverviewId(OverviewId.Builder.builder().withTeamId(2L).build()).withTeamName(TEAM_PUZZLE).build()); + List overviews = List + .of(Overview.Builder + .builder() + .withOverviewId(OverviewId.Builder.builder().withTeamId(2L).build()) + .withTeamName(TEAM_PUZZLE) + .build()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); @@ -49,9 +52,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()); + List overviews = List + .of(Overview.Builder + .builder() + .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()); @@ -61,11 +68,20 @@ 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()); + 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()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); @@ -75,11 +91,23 @@ 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()); + 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()); List overviewDtos = overviewMapper.toDto(overviews); assertEquals(1, overviewDtos.size()); @@ -89,17 +117,35 @@ 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 +155,43 @@ 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 +217,48 @@ 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()); @@ -174,14 +270,25 @@ 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()); + 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()); 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..7ff1416141 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 { @@ -25,7 +25,8 @@ public class TeamMapperTest { @Test void toDtoShouldMapTeamToDto() { // arrange - Team team = Team.Builder.builder() // + Team team = Team.Builder + .builder() // .withId(ID) // .withVersion(VERSION) // .withName(NAME) // 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..0c5b30384c 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 { @@ -32,16 +31,19 @@ public class UserMapperTest { @InjectMocks private TeamMapper teamMapper; - private final User user = User.Builder.builder() // + 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())) // + .withUserTeamList(List + .of(UserTeam.Builder + .builder() // + .withId(USER_TEAM_ID) // + .withTeam(Team.Builder.builder().build()) // + .build())) // .withOkrChampion(IS_OKR_CHAMPION) // .build(); @@ -56,7 +58,8 @@ void setup() { @Test void toDtoWithoutTeamListThrowsException() { // arrange - User user = User.Builder.builder() // + User user = User.Builder + .builder() // .withId(ID) // .withVersion(VERSION) // .withFirstname(FIRSTNAME) // 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 022d72105f..c1fa95407a 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..f7d493c91a 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() { @@ -24,11 +24,13 @@ public static CheckInOrdinal checkInOrdinal() { return (CheckInOrdinal) TestDataHelper.checkInOrdinal; } - private static final KeyResult keyResult = KeyResultMetric.Builder.builder() // + private static final KeyResult keyResult = KeyResultMetric.Builder + .builder() // .withId(KEY_RESULT_ID) // .build(); - private static final CheckIn checkInMetric = CheckInMetric.Builder.builder() // + private static final CheckIn checkInMetric = CheckInMetric.Builder + .builder() // .withId(CHECK_IN_ID) // .withVersion(CHECK_IN_VERSION) // .withChangeInfo(CHECK_IN_CHANGE_INFO) // @@ -40,7 +42,8 @@ public static CheckInOrdinal checkInOrdinal() { .withValue(CHECK_IN_METRIC_VALUE) // .build(); - private static final CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder() // + private static final CheckIn checkInOrdinal = CheckInOrdinal.Builder + .builder() // .withId(CHECK_IN_ID) // .withVersion(CHECK_IN_VERSION) // .withChangeInfo(CHECK_IN_CHANGE_INFO) // @@ -49,5 +52,6 @@ public static CheckInOrdinal checkInOrdinal() { .withKeyResult(keyResult) // .withCreatedOn(CHECK_IN_CREATE_DATE_TIME) // .withModifiedOn(CHECK_IN_MODIFIED_DATE_TIME) // - .withZone(CHECK_IN_ORDINAL_ZONE).build(); + .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 fde8f34372..597c9f92e1 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.zone(), actual.zone()); 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..dd69ee4c5f 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() { @@ -51,7 +51,8 @@ public static Objective objective() { return objective; } - private static final CheckIn checkInMetric = CheckInMetric.Builder.builder() // + private static final CheckIn checkInMetric = CheckInMetric.Builder + .builder() // .withId(CHECK_IN_ID) // .withVersion(CHECK_IN_VERSION) // .withValue(CHECK_IN_METRIC_VALUE) // @@ -61,7 +62,8 @@ public static Objective objective() { .withInitiatives(CHECK_IN_INITIATIVES) // .build(); - private static final CheckIn checkInOrdinal = CheckInOrdinal.Builder.builder() // + private static final CheckIn checkInOrdinal = CheckInOrdinal.Builder + .builder() // .withId(CHECK_IN_ID) // .withVersion(CHECK_IN_VERSION) // .withZone(CHECK_IN_ORDINAL_ZONE) // @@ -71,26 +73,30 @@ public static Objective objective() { .withInitiatives(CHECK_IN_INITIATIVES) // .build(); - private static final User owner = User.Builder.builder() // + private static final User owner = User.Builder + .builder() // .withId(USER_ID) // .withFirstname(USER_FIRSTNAME) // .withLastname(USER_LASTNAME) // .build(); - private static final Quarter quarter = Quarter.Builder.builder() // + private static final Quarter quarter = Quarter.Builder + .builder() // .withId(QUARTER_ID) // .withLabel(QUARTER_LABEL) // .withStartDate(QUARTER_START_DATE) // .withEndDate(QUARTER_END_DATE) // .build(); - private static final Objective objective = Objective.Builder.builder() // + private static final Objective objective = Objective.Builder + .builder() // .withId(OBJECTIVE_ID) // .withQuarter(quarter) // .withState(OBJECTIVE_STATE) // .build(); - private static final KeyResult keyResultMetric = KeyResultMetric.Builder.builder() // + private static final KeyResult keyResultMetric = KeyResultMetric.Builder + .builder() // .withId(KEY_RESULT_ID) // .withVersion(KEY_RESULT_VERSION) // .withTitle(KEY_RESULT_TITLE) // @@ -104,19 +110,23 @@ public static Objective objective() { .withModifiedOn(CHECK_IN_MODIFIED_ON) // .build(); - private static final KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() // + 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) // + .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() // + private static final Action actionForKeyResultMetric = Action.Builder + .builder() // .withId(ACTION_ID) // .withVersion(ACTION_VERSION) // .withAction(ACTION_ACTION) // @@ -125,7 +135,8 @@ public static Objective objective() { .withKeyResult(keyResultMetric) // .build(); - private static final Action actionForKeyResultOrdinal = Action.Builder.builder() // + private static final Action actionForKeyResultOrdinal = Action.Builder + .builder() // .withId(ACTION_ID) // .withVersion(ACTION_VERSION) // .withAction(ACTION_ACTION) // 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..b4283d82bc 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,21 @@ 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/models/keyresult/KeyResultTest.java b/backend/src/test/java/ch/puzzle/okr/models/keyresult/KeyResultTest.java index 47b2561baf..c6edc5f1f9 100644 --- a/backend/src/test/java/ch/puzzle/okr/models/keyresult/KeyResultTest.java +++ b/backend/src/test/java/ch/puzzle/okr/models/keyresult/KeyResultTest.java @@ -1,13 +1,12 @@ package ch.puzzle.okr.models.keyresult; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.*; - class KeyResultTest { @ParameterizedTest @@ -20,8 +19,9 @@ void resetIdShouldSetIdToNull(KeyResult keyResult) { } private static Stream provideKeyResults() { - return Stream.of(Arguments.of(KeyResultMetric.Builder.builder().withId(1L).build()), - Arguments.of(KeyResultOrdinal.Builder.builder().withId(1L).build())); + return Stream + .of(Arguments.of(KeyResultMetric.Builder.builder().withId(1L).build()), + Arguments.of(KeyResultOrdinal.Builder.builder().withId(1L).build())); } } \ No newline at end of file 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..6ca89aa5c5 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,30 +57,35 @@ 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() { return mock(Flyway.class); } - public String getLog() { - return log; - } + public String getLog() { return log; } } 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() { - return List.of(tenantConfig); - } + public List getTenantConfigs() { return List.of(tenantConfig); } @Override public Optional getTenantConfigById(String tenantId) { @@ -98,8 +106,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..53e4b1bce5 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); @@ -49,15 +48,16 @@ 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", "")); + 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", "")); } @DisplayName("extractAndSetHibernateConfig() should extract hibernate properties from environment and set it") @@ -108,7 +108,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..6cdc5b444c 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"; @@ -17,9 +16,7 @@ public class SchemaMultiTenantConnectionProviderInternalsTest { private static class ConfigurableConnectionProviderMock extends SchemaMultiTenantConnectionProvider { @Override - protected Properties getHibernateProperties() { - return new Properties(); - } + protected Properties getHibernateProperties() { return new Properties(); } public void registerProvider(String tenantIdentifier, ConnectionProvider connectionProvider) { connectionProviderMap.put(tenantIdentifier, connectionProvider); 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..261538bf80 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 { @@ -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..85aba67421 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,13 +1,13 @@ 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") @@ -16,8 +16,8 @@ public class TenantClientCustomizationProviderTest { 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..94e0be8fed 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"; @@ -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) { 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..750615e0be 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 { @@ -37,14 +36,21 @@ public class JwtHelperTest { 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 // - )); + when(tokenWithUserDataMock.getClaims()) + .thenReturn(Map + .of( // + 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 +69,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 = // @@ -81,11 +89,16 @@ void getTenantFromTokenReturnsTenantIfTenantFoundInTenantConfigProvider() { when(tokenMock.getClaimAsString(TOKEN_CLAIMS_KEY_TENANT)).thenReturn(PITC); TenantConfigProvider tenantConfigProviderMock = mock(TenantConfigProvider.class); - when(tenantConfigProviderMock.getTenantConfigById(PITC)).thenReturn(Optional.of( // - new TenantConfigProvider.TenantConfig(PITC, // - new String[] {}, "jwkSetUri", "issuerUrl", // - "clientId", null) // - )); + when(tenantConfigProviderMock.getTenantConfigById(PITC)) + .thenReturn(Optional + .of( // + new TenantConfigProvider.TenantConfig(PITC, // + new String[]{}, + "jwkSetUri", + "issuerUrl", // + "clientId", + null) // + )); JwtHelper jwtHelper = new JwtHelper(tenantConfigProviderMock, null, null, null); @@ -119,11 +132,16 @@ void getTenantFromJWTClaimsSetReturnsTenantIfTenantFoundInTenantConfigProvider() when(claimsSetMock.getStringClaim(TOKEN_CLAIMS_KEY_TENANT)).thenReturn(PITC); TenantConfigProvider tenantConfigProviderWithDataMock = mock(TenantConfigProvider.class); - when(tenantConfigProviderWithDataMock.getTenantConfigById(PITC)).thenReturn(Optional.of( // - new TenantConfigProvider.TenantConfig(PITC, // - new String[] {}, "jwkSetUri", "issuerUrl", // - "clientId", null) // - )); + when(tenantConfigProviderWithDataMock.getTenantConfigById(PITC)) + .thenReturn(Optional + .of( // + 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..e21997b017 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,10 @@ 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()); } @@ -66,19 +68,13 @@ void selectKeysReturnKeyWithMockAlgorithmIfJwkSetUriIsFound() throws KeySourceEx JWSKeySelector fromUri(String uri) { return (jwsHeader, securityContext) -> List.of(new Key() { @Override - public String getAlgorithm() { - return MOCK_ALGORITHM; - } + public String getAlgorithm() { return MOCK_ALGORITHM; } @Override - public String getFormat() { - return null; - } + public String getFormat() { return null; } @Override - public byte[] getEncoded() { - return new byte[0]; - } + public byte[] getEncoded() { return new byte[0]; } }); } }; 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..e59787ada0 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"; @@ -48,13 +47,19 @@ void validateReturnOAuth2TokenValidatorResultIfTenantConfigWithIssuerUrlIsFound( when(jwtHelper.getTenantFromToken(token)).thenReturn(PITC); 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) { + when(tenantConfigProviderWithPitcConfig.getTenantConfigById(PITC)) + .thenReturn(Optional + .of( // + 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..2774d76675 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"; 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..e258ccfb72 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"; 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..7e772e34f1 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,14 +1,13 @@ 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"; 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..950fc4e9dd 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,10 +34,22 @@ 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 @@ -71,11 +82,12 @@ void createEntityShouldReturnCreatedActionWhenAuthorized() { void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + 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 +105,12 @@ void updateEntitiesShouldUpdateActionWhenAuthorized() { void updateEntitiesShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + 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) + 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..71b0285a5b 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 @@ -86,7 +85,8 @@ void registerAuthorizationUserShouldAddAuthorizationUserToCache() { @Test void registerAuthorizationUser_shouldSetOkrChampionsToFalse() { // arrange - User user = User.Builder.builder() // + User user = User.Builder + .builder() // .withFirstname("Richard") // .withLastname("Eberhard") // .withEmail("richard.eberhard@puzzle.ch") // email not found in application-integration-test.properties @@ -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,9 +126,11 @@ 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 + // "okr.tenants.pitc.user.champion.emails" from + // application-integration-test.properties file AuthorizationUser processedUser = authorizationRegistrationService - .updateOrAddAuthorizationUser(User.Builder.builder() // + .updateOrAddAuthorizationUser(User.Builder + .builder() // .withFirstname("Alice") // .withLastname("Wunderland") // .withEmail(EMAIL_WUNDERLAND) // user.champion.emails from @@ -140,7 +145,8 @@ void registerAuthorizationUserShouldSetOkrChampionsToTrue() { @Test void registerAuthorizationUser_shouldSetFirstnameAndLastnameFromToken() { // arrange - User user = User.Builder.builder() // + User user = User.Builder + .builder() // .withFirstname("Richard") // .withLastname("Eberhard") // .withEmail("richard.eberhard@puzzle.ch") // @@ -149,7 +155,8 @@ void registerAuthorizationUser_shouldSetFirstnameAndLastnameFromToken() { String firstNameFromToken = "Richu"; String lastNameFromToken = "von Gunten"; - User userFromToken = User.Builder.builder() // + User userFromToken = User.Builder + .builder() // .withFirstname(firstNameFromToken) // .withLastname(lastNameFromToken) // .withEmail("richard.eberhard@puzzle.ch") // 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..3f3f55e225 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 @@ -49,12 +48,15 @@ class AuthorizationServiceTest { @Mock 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()); - private final List memberTeams = List.of(Team.Builder.builder().withName("Team 3").withId(3L).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()); + private final List adminTeams = List + .of(Team.Builder.builder().withName("Team 1").withId(1L).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()); + private final List otherTeams = List + .of(Team.Builder.builder().withName("Team 5").withId(5L).build(), + Team.Builder.builder().withName("Team 6").withId(6L).build()); private final User user = defaultUserWithTeams(1L, adminTeams, memberTeams); private final User okrChampion = defaultOkrChampion(1L); @@ -122,14 +124,16 @@ void hasRoleReadByObjectiveIdShouldPassThroughWhenPermitted() { void hasRoleReadByKeyResultIdShouldThrowExceptionWhenObjectiveNotFound() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); - OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "KeyResult"); + OkrResponseStatusException expectedException = OkrResponseStatusException + .of(NOT_AUTHORIZED_TO_READ, "KeyResult"); 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")); @@ -142,8 +146,8 @@ void hasRoleReadByKeyResultIdShouldThrowExceptionWhenObjectiveNotFound() { void hasRoleReadByKeyResultIdShouldPassThroughWhenPermitted() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); - OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "KeyResult"); + OkrResponseStatusException expectedException = OkrResponseStatusException + .of(NOT_AUTHORIZED_TO_READ, "KeyResult"); when(objectivePersistenceService.findObjectiveByKeyResultId(eq(id), eq(authorizationUser), any())) .thenReturn(new Objective()); @@ -155,13 +159,15 @@ void hasRoleReadByCheckInIdShouldThrowExceptionWhenObjectiveNotFound() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); - OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "Check-in"); + OkrResponseStatusException expectedException = OkrResponseStatusException + .of(NOT_AUTHORIZED_TO_READ, "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")); @@ -174,8 +180,8 @@ void hasRoleReadByCheckInIdShouldThrowExceptionWhenObjectiveNotFound() { void hasRoleReadByCheckInIdShouldPassThroughWhenPermitted() { Long id = 13L; AuthorizationUser authorizationUser = new AuthorizationUser(user); - OkrResponseStatusException expectedException = OkrResponseStatusException.of(NOT_AUTHORIZED_TO_READ, - "Check-in"); + OkrResponseStatusException expectedException = OkrResponseStatusException + .of(NOT_AUTHORIZED_TO_READ, "Check-in"); when(objectivePersistenceService.findObjectiveByCheckInId(eq(id), eq(authorizationUser), any())) .thenReturn(new Objective()); @@ -214,7 +220,9 @@ 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 +237,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 +251,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 +265,14 @@ 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")); @@ -276,8 +289,11 @@ void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedAsAdminForTeamCheckIns( CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService + .findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), + eq(authorizationUser), + any())) + .thenReturn(objective); authorizationService.hasRoleCreateOrUpdate(checkIn, authorizationUser); } @@ -290,8 +306,11 @@ void hasRoleCreateOrUpdateShouldPassThroughWhenAuthorizedAsMemberForTeamCheckIns CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService + .findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), + eq(authorizationUser), + any())) + .thenReturn(objective); authorizationService.hasRoleCreateOrUpdate(checkIn, authorizationUser); } @@ -304,11 +323,15 @@ void hasRoleCreateOrUpdateShouldThrowExceptionWhenNotInTeamForTeamCheckIns() { CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService + .findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getObjective().getId()), + 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 +382,9 @@ 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 +435,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 +449,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 +462,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)); } @@ -448,8 +476,9 @@ void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedToWriteAllCheckIns() { CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); AuthorizationUser authorizationUser = new AuthorizationUser(okrChampion); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService + .findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), eq(authorizationUser), any())) + .thenReturn(objective); assertTrue(authorizationService.hasRoleWriteForTeam(checkIn, authorizationUser)); } @@ -462,8 +491,9 @@ void hasRoleWriteForTeamShouldReturnTrueWhenAuthorizedAsAdminForCheckIns() { CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); AuthorizationUser authorizationUser = new AuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService + .findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), eq(authorizationUser), any())) + .thenReturn(objective); assertTrue(authorizationService.hasRoleWriteForTeam(checkIn, authorizationUser)); } @@ -475,8 +505,9 @@ void hasRoleWriteForTeamShouldReturnFalseWhenNotAuthorizedToWriteCheckIns() { CheckIn checkIn = CheckInMetric.Builder.builder().withKeyResult(keyResult).build(); AuthorizationUser authorizationUser = mockAuthorizationUser(user); - when(objectivePersistenceService.findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), - eq(authorizationUser), any())).thenReturn(objective); + when(objectivePersistenceService + .findObjectiveByKeyResultId(eq(checkIn.getKeyResult().getId()), eq(authorizationUser), any())) + .thenReturn(objective); assertFalse(authorizationService.hasRoleWriteForTeam(checkIn, authorizationUser)); } @@ -531,7 +562,9 @@ void hasRoleDeleteByCheckInIdShouldPassThroughWhenAuthorizedAsMemberForTeamCheck @Test void hasRoleDeleteByKeyResultIdShouldPassThroughWhenOkrChampion() { var otherTeamId = otherTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(otherTeamId).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())) @@ -543,7 +576,9 @@ void hasRoleDeleteByKeyResultIdShouldPassThroughWhenOkrChampion() { @Test void hasRoleDeleteByKeyResultIdShouldPassThroughWhenAdmin() { var otherTeamId = adminTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(otherTeamId).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())) @@ -555,7 +590,9 @@ void hasRoleDeleteByKeyResultIdShouldPassThroughWhenAdmin() { @Test void hasRoleDeleteByKeyResultIdShouldPassThroughWhenMember() { var otherTeamId = memberTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(otherTeamId).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())) @@ -567,14 +604,17 @@ void hasRoleDeleteByKeyResultIdShouldPassThroughWhenMember() { @Test void hasRoleDeleteByKeyResultIdShouldThrowExceptionWhenNotInTeam() { var otherTeamId = otherTeams.get(0).getId(); - Objective objective = Objective.Builder.builder().withTeam(Team.Builder.builder().withId(otherTeamId).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); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> authorizationService.hasRoleDeleteByKeyResultId(1L, authorizationUser)); + () -> authorizationService + .hasRoleDeleteByKeyResultId(1L, authorizationUser)); List expectedErrors = List.of(ErrorDto.of(NOT_AUTHORIZED_TO_DELETE, "KeyResult")); @@ -586,29 +626,19 @@ void hasRoleDeleteByKeyResultIdShouldThrowExceptionWhenNotInTeam() { private void setSecurityContext(Jwt token) { SecurityContextHolder.setContext(new SecurityContextImpl(new Authentication() { @Override - public Collection getAuthorities() { - return null; - } + public Collection getAuthorities() { return null; } @Override - public Object getCredentials() { - return null; - } + public Object getCredentials() { return null; } @Override - public Object getDetails() { - return null; - } + public Object getDetails() { return null; } @Override - public Object getPrincipal() { - return token; - } + public Object getPrincipal() { return token; } @Override - public boolean isAuthenticated() { - return false; - } + public boolean isAuthenticated() { return false; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { @@ -616,9 +646,7 @@ public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentExce } @Override - public String getName() { - return "unit test authentication"; - } + public String getName() { return "unit test authentication"; } })); } } 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..96a0c6a2c1 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 @@ -55,11 +55,12 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)) + .when(authorizationService) .hasRoleReadByCheckInId(id, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> checkInAuthorizationService.getEntityById(id)); + () -> checkInAuthorizationService.getEntityById(id)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -77,11 +78,12 @@ void createEntityShouldReturnCreatedCheckInWhenAuthorized() { void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)) + .when(authorizationService) .hasRoleCreateOrUpdate(checkInMetric, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> checkInAuthorizationService.createEntity(checkInMetric)); + () -> checkInAuthorizationService.createEntity(checkInMetric)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -101,11 +103,13 @@ void updateEntityShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)) + .when(authorizationService) .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) + 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..e134637ef9 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,11 @@ 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 +49,13 @@ void createCompletedShouldReturnObjectiveWhenAuthorized() { void createCompletedShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + 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 +71,13 @@ void deleteCompletedByObjectiveIdShouldPassThroughWhenAuthorized() { void deleteCompletedByObjectiveIdShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + 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..fb01a84d47 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 @@ -49,11 +48,13 @@ void createEntityShouldReturnKeyResultWhenAuthorized() { void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)) + .when(authorizationService) .hasRoleCreateOrUpdate(metricKeyResult, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> keyResultAuthorizationService.createEntity(metricKeyResult)); + () -> keyResultAuthorizationService + .createEntity(metricKeyResult)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -84,11 +85,12 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + 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()); } @@ -100,8 +102,8 @@ void updateEntitiesShouldReturnUpdatedKeyResultWhenAuthorized() { when(keyResultBusinessService.updateEntities(id, metricKeyResult, List.of())) .thenReturn(new KeyResultWithActionList(metricKeyResult, List.of())); - KeyResultWithActionList KeyResult = keyResultAuthorizationService.updateEntities(id, metricKeyResult, - List.of()); + KeyResultWithActionList KeyResult = keyResultAuthorizationService + .updateEntities(id, metricKeyResult, List.of()); assertEquals(metricKeyResult, KeyResult.keyResult()); } @@ -110,11 +112,13 @@ void updateEntitiesShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)) + .when(authorizationService) .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 +126,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 +147,12 @@ void deleteEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + 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 05a4c8338a..17abfa6b6e 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,10 +1,19 @@ package ch.puzzle.okr.service.authorization; +import static ch.puzzle.okr.test.KeyResultTestHelpers.metricKeyResult; +import static ch.puzzle.okr.test.KeyResultTestHelpers.ordinalKeyResult; +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.models.keyresult.KeyResult; -import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.business.ObjectiveBusinessService; +import java.util.ArrayList; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -14,17 +23,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.ArrayList; -import java.util.List; - -import static ch.puzzle.okr.test.KeyResultTestHelpers.metricKeyResult; -import static ch.puzzle.okr.test.KeyResultTestHelpers.ordinalKeyResult; -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 @@ -50,11 +48,13 @@ void createEntityShouldReturnObjectiveWhenAuthorized() { void createEntityShouldThrowExceptionWhenNotAuthorized() { String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)) + .when(authorizationService) .hasRoleCreateOrUpdate(newObjective, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.createEntity(newObjective)); + () -> objectiveAuthorizationService + .createEntity(newObjective)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -85,11 +85,12 @@ void getEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + 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()); } @@ -109,11 +110,13 @@ void updateEntityShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)) + .when(authorizationService) .hasRoleCreateOrUpdate(newObjective, authorizationUser); ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.updateEntity(id, newObjective)); + () -> objectiveAuthorizationService + .updateEntity(id, newObjective)); assertEquals(UNAUTHORIZED, exception.getStatusCode()); assertEquals(reason, exception.getReason()); } @@ -138,11 +141,12 @@ void deleteEntityByIdShouldThrowExceptionWhenNotAuthorized() { Long id = 13L; String reason = "junit test reason"; when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + 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()); } @@ -159,12 +163,16 @@ void duplicateEntityShouldThrowExceptionWhenNotAuthorized() { keyResults.add(metricKeyResult); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)).when(authorizationService) + doThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, reason)) + .when(authorizationService) .hasRoleCreateOrUpdate(objective, authorizationUser); // act ResponseStatusException exception = assertThrows(ResponseStatusException.class, - () -> objectiveAuthorizationService.duplicateEntity(idExistingObjective, objective, keyResults)); + () -> objectiveAuthorizationService + .duplicateEntity(idExistingObjective, + objective, + keyResults)); // assert assertEquals(UNAUTHORIZED, exception.getStatusCode()); @@ -177,22 +185,28 @@ void duplicateEntityShouldReturnDuplicatedObjectiveWhenAuthorized() { // arrange Long idExistingObjective = 13L; - Objective newObjectiveWithoutKeyResults = Objective.Builder.builder() // - .withTitle("Objective without KeyResults").build(); + Objective newObjectiveWithoutKeyResults = Objective.Builder + .builder() // + .withTitle("Objective without KeyResults") + .build(); - Objective newObjectiveWithKeyResults = Objective.Builder.builder() // - .withId(42L).withTitle("Objective with Id and KeyResults").build(); + Objective newObjectiveWithKeyResults = Objective.Builder + .builder() // + .withId(42L) + .withTitle("Objective with Id and KeyResults") + .build(); List keyResults = new ArrayList<>(); keyResults.add(metricKeyResult); when(authorizationService.updateOrAddAuthorizationUser()).thenReturn(authorizationUser); - when(objectiveBusinessService.duplicateObjective(idExistingObjective, newObjectiveWithoutKeyResults, - authorizationUser, keyResults)).thenReturn(newObjectiveWithKeyResults); + when(objectiveBusinessService + .duplicateObjective(idExistingObjective, newObjectiveWithoutKeyResults, authorizationUser, keyResults)) + .thenReturn(newObjectiveWithKeyResults); // act - Objective objective = objectiveAuthorizationService.duplicateEntity(idExistingObjective, - newObjectiveWithoutKeyResults, keyResults); + Objective objective = objectiveAuthorizationService + .duplicateEntity(idExistingObjective, newObjectiveWithoutKeyResults, keyResults); // 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..a329da5c29 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() + private final Overview overview = Overview.Builder + .builder() .withOverviewId(OverviewId.Builder.builder().withObjectiveId(1L).withTeamId(adminTeamId).build()) - .withObjectiveTitle("Objective 1").build(); + .withObjectiveTitle("Objective 1") + .build(); @DisplayName("getFilteredOverview() should do nothing when OverviewId is null") @Test 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..1a5fa86566 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,7 +122,7 @@ 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()); } 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..504c8ee5c6 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; @@ -20,14 +20,16 @@ void setup() { @Test void updateUserFromWithTokenData() { // arrange - User userFromDB = User.Builder.builder() // + User userFromDB = User.Builder + .builder() // .withId(23L) // .withFirstname("firstname_from_db") // .withLastname("lastname_from_db") // .withEmail("a@b.ch") // .build(); - User userFromToken = User.Builder.builder() // + User userFromToken = User.Builder + .builder() // .withFirstname("firstname_from_token") // .withLastname("lastname_from_token") // .build(); @@ -47,7 +49,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 +68,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..b1acd4babd 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,30 @@ 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 +95,13 @@ 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 +117,20 @@ 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 +144,13 @@ 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/AlignmentBusinessServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentBusinessServiceTest.java index 66277c8f3c..f956707a2e 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentBusinessServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/business/AlignmentBusinessServiceTest.java @@ -1,5 +1,15 @@ package ch.puzzle.okr.service.business; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.alignment.Alignment; import ch.puzzle.okr.models.alignment.KeyResultAlignment; @@ -7,6 +17,9 @@ import ch.puzzle.okr.models.keyresult.KeyResultMetric; import ch.puzzle.okr.service.persistence.AlignmentPersistenceService; import ch.puzzle.okr.service.validation.AlignmentValidationService; +import java.util.ArrayList; +import java.util.List; +import javax.swing.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -16,21 +29,6 @@ import org.springframework.http.HttpStatus; import org.springframework.test.context.bean.override.mockito.MockitoBean; -import javax.swing.*; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) class AlignmentBusinessServiceTest { @MockitoBean @@ -46,8 +44,13 @@ class AlignmentBusinessServiceTest { @BeforeEach void setUp() { - this.keyResult = KeyResultMetric.Builder.builder().withId(1L).withBaseline(10.0) - .withDescription("Awesome Keyresult").withStretchGoal(100.0).build(); + this.keyResult = KeyResultMetric.Builder + .builder() + .withId(1L) + .withBaseline(10.0) + .withDescription("Awesome Keyresult") + .withStretchGoal(100.0) + .build(); this.alignments = new ArrayList<>(); this.alignments.add(KeyResultAlignment.Builder.builder().withId(12L).withTargetKeyResult(keyResult).build()); @@ -58,10 +61,11 @@ void setUp() { @Test void updateEntityShouldThrowExceptionWhenValidationFails() { doThrow(new OkrResponseStatusException(HttpStatus.BAD_REQUEST, "Error Message")) - .when(alignmentValidationService).validateOnUpdate(eq(1L), any(KeyResultAlignment.class)); + .when(alignmentValidationService) + .validateOnUpdate(eq(1L), any(KeyResultAlignment.class)); assertThrows(OkrResponseStatusException.class, - () -> alignmentBusinessService.updateEntity(1L, new KeyResultAlignment())); + () -> alignmentBusinessService.updateEntity(1L, new KeyResultAlignment())); } @Test 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..198c69e0fc 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,16 @@ 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..fc4c173710 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,46 @@ class CheckInBusinessServiceTest { @InjectMocks private CheckInBusinessService checkInBusinessService; - private User user = User.Builder.builder().withEmail("Email").withFirstname("Firstname").withLastname("Lastname") + 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 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() { 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..addeb95a4e 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,12 @@ class CompletedBusinessServiceTest { @Mock CompletedValidationService validator; - Completed successfulCompleted = Completed.Builder.builder().withId(1L) + Completed successfulCompleted = Completed.Builder + .builder() + .withId(1L) .withObjective(Objective.Builder.builder().withId(3L).withTitle("Gute Lernende").build()) - .withComment("Wir haben es gut geschafft").build(); + .withComment("Wir haben es gut geschafft") + .build(); @InjectMocks @Spy @@ -35,10 +38,15 @@ class CompletedBusinessServiceTest { 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(); + 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(); Completed savedCompleted = completedBusinessService.createCompleted(completed); verify(completedPersistenceService, times(1)).save(completed); @@ -47,8 +55,14 @@ 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..7cbb680aa1 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,19 +55,32 @@ 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()) + 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()) + .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") + 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()) + .withObjective(Objective.Builder.builder().withId(4L).build()) + .withCreatedOn(LocalDateTime.now()) .build(); } @@ -77,18 +89,32 @@ private static CheckIn createCheckInMetric(KeyResult keyResult) { } private static CheckIn createCheckInOrdinal(KeyResult keyResult) { - return CheckInOrdinal.Builder.builder().withKeyResult(keyResult).withConfidence(5).withZone(Zone.COMMIT) + 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 @@ -134,8 +160,8 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeMetric() { createdKeyResult = keyResultBusinessService.createEntity(createKeyResultMetric(null), authorizationUser); createdKeyResult.setTitle(KEY_RESULT_UPDATED); - KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(createdKeyResult.getId(), - createdKeyResult, List.of()); + KeyResultWithActionList updatedKeyResult = keyResultBusinessService + .updateEntities(createdKeyResult.getId(), createdKeyResult, List.of()); assertSameKeyResult(createdKeyResult, updatedKeyResult.keyResult()); } @@ -147,8 +173,8 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeMetricWithActionList() { action1 = actionBusinessService.createEntity(createAction1(createdKeyResult)); action2 = actionBusinessService.createEntity(createAction2(createdKeyResult)); - KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(createdKeyResult.getId(), - createdKeyResult, List.of(action1, action2)); + KeyResultWithActionList updatedKeyResult = keyResultBusinessService + .updateEntities(createdKeyResult.getId(), createdKeyResult, List.of(action1, action2)); assertSameKeyResult(createdKeyResult, updatedKeyResult.keyResult()); assertSameActions(List.of(action1, action2), updatedKeyResult); @@ -159,21 +185,21 @@ void updateEntitiesShouldUpdateKeyResultWithSameTypeOrdinal() { createdKeyResult = keyResultBusinessService.createEntity(createKeyResultOrdinal(null), authorizationUser); createdKeyResult.setTitle(KEY_RESULT_UPDATED); - KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(createdKeyResult.getId(), - createdKeyResult, List.of()); + KeyResultWithActionList updatedKeyResult = keyResultBusinessService + .updateEntities(createdKeyResult.getId(), createdKeyResult, List.of()); assertSameKeyResult(createdKeyResult, updatedKeyResult.keyResult()); } @Test void updateEntitiesShouldRecreateKeyResultMetric() { - KeyResult savedKeyResult = keyResultBusinessService.createEntity(createKeyResultOrdinal(null), - authorizationUser); + KeyResult savedKeyResult = keyResultBusinessService + .createEntity(createKeyResultOrdinal(null), authorizationUser); Long createdKeyResultId = savedKeyResult.getId(); KeyResult changedKeyResult = createKeyResultMetric(savedKeyResult.getId()); - KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + KeyResultWithActionList updatedKeyResult = keyResultBusinessService + .updateEntities(changedKeyResult.getId(), changedKeyResult, List.of()); createdKeyResult = updatedKeyResult.keyResult(); assertRecreatedKeyResult(updatedKeyResult.keyResult(), createdKeyResultId); @@ -181,15 +207,15 @@ void updateEntitiesShouldRecreateKeyResultMetric() { @Test void updateEntitiesShouldRecreateKeyResultMetricWithActionList() { - KeyResult savedKeyResult = keyResultBusinessService.createEntity(createKeyResultOrdinal(null), - authorizationUser); + KeyResult savedKeyResult = keyResultBusinessService + .createEntity(createKeyResultOrdinal(null), 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)); + KeyResultWithActionList updatedKeyResult = keyResultBusinessService + .updateEntities(changedKeyResult.getId(), changedKeyResult, List.of(action1, action2)); createdKeyResult = updatedKeyResult.keyResult(); assertRecreatedKeyResult(updatedKeyResult.keyResult(), createdKeyResultId); @@ -198,13 +224,13 @@ void updateEntitiesShouldRecreateKeyResultMetricWithActionList() { @Test void updateEntitiesShouldRecreateKeyResultOrdinal() { - KeyResult savedKeyResult = keyResultBusinessService.createEntity(createKeyResultMetric(null), - authorizationUser); + KeyResult savedKeyResult = keyResultBusinessService + .createEntity(createKeyResultMetric(null), authorizationUser); Long createdKeyResultId = savedKeyResult.getId(); KeyResult changedKeyResult = createKeyResultOrdinal(savedKeyResult.getId()); - KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + KeyResultWithActionList updatedKeyResult = keyResultBusinessService + .updateEntities(changedKeyResult.getId(), changedKeyResult, List.of()); createdKeyResult = updatedKeyResult.keyResult(); assertRecreatedKeyResult(updatedKeyResult.keyResult(), createdKeyResultId); @@ -217,8 +243,8 @@ void updateEntitiesShouldUpdateKeyResultWithDifferentTypeAndCheckInMetric() { KeyResult changedKeyResult = createKeyResultMetric(createdKeyResult.getId()); - KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + KeyResultWithActionList updatedKeyResult = keyResultBusinessService + .updateEntities(changedKeyResult.getId(), changedKeyResult, List.of()); assertUpdatedKeyResult(changedKeyResult, updatedKeyResult.keyResult()); } @@ -234,8 +260,8 @@ void updateEntitiesShouldUpdateKeyResultWithDifferentTypeAndCheckInMetricWithAct action1.setChecked(true); action2.setChecked(true); - KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of(action1, action2)); + KeyResultWithActionList updatedKeyResult = keyResultBusinessService + .updateEntities(changedKeyResult.getId(), changedKeyResult, List.of(action1, action2)); assertUpdatedKeyResult(changedKeyResult, updatedKeyResult.keyResult()); assertUpdatedActions(List.of(action1, action2), updatedKeyResult); @@ -248,8 +274,8 @@ void updateEntitiesShouldUpdateKeyResultWithDifferentTypeAndCheckInOrdinal() { KeyResult changedKeyResult = createKeyResultOrdinal(createdKeyResult.getId()); - KeyResultWithActionList updatedKeyResult = keyResultBusinessService.updateEntities(changedKeyResult.getId(), - changedKeyResult, List.of()); + KeyResultWithActionList updatedKeyResult = keyResultBusinessService + .updateEntities(changedKeyResult.getId(), 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 03ad68583e..fe99ce8108 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(); @@ -63,21 +62,55 @@ 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(); + 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) + checkIn1 = CheckInMetric.Builder + .builder() + .withId(1L) + .withKeyResult(metricKeyResult) + .withCreatedBy(user) .build(); - checkIn2 = CheckInOrdinal.Builder.builder().withId(2L).withKeyResult(ordinalKeyResult).withCreatedBy(user) + checkIn2 = CheckInOrdinal.Builder + .builder() + .withId(2L) + .withKeyResult(ordinalKeyResult) + .withCreatedBy(user) .build(); - checkIn3 = CheckInOrdinal.Builder.builder().withId(3L).withKeyResult(ordinalKeyResult).withCreatedBy(user) + 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); } @@ -101,8 +134,11 @@ 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()); } @@ -110,8 +146,11 @@ 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()); @@ -127,8 +166,11 @@ 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()); @@ -144,8 +186,11 @@ 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); @@ -164,8 +209,11 @@ 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); @@ -183,8 +231,11 @@ 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); @@ -201,8 +252,11 @@ 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); @@ -218,8 +272,14 @@ 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()); @@ -230,9 +290,14 @@ 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()); @@ -243,8 +308,13 @@ 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()); @@ -255,8 +325,13 @@ 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 97c32e483d..fe9d31d235 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,9 @@ 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.ArrayList; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -18,19 +29,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.web.server.ResponseStatusException; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -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(); @@ -48,14 +46,31 @@ 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 @@ -89,9 +104,16 @@ 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()); @@ -105,8 +127,13 @@ 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); @@ -122,14 +149,36 @@ void updateEntityShouldHandleQuarterCorrectly(boolean hasKeyResultAnyCheckIns) { 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) + 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 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); @@ -137,12 +186,12 @@ 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()); } @@ -160,15 +209,18 @@ void shouldDeleteObjectiveAndAssociatedKeyResults() { @Test void shouldDuplicateObjective() { // arrange - Objective sourceObjective = Objective.Builder.builder() // + Objective sourceObjective = Objective.Builder + .builder() // .withId(23L) // .withTitle("Objective 1") // .build(); - KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder() // + KeyResult keyResultOrdinal = KeyResultOrdinal.Builder + .builder() // .withTitle("Ordinal 1") // .withObjective(sourceObjective) // .build(); - KeyResult keyResultMetric = KeyResultMetric.Builder.builder() // + KeyResult keyResultMetric = KeyResultMetric.Builder + .builder() // .withTitle("Metric 1") // .withObjective(sourceObjective) // .withUnit(Unit.FTE) // @@ -179,7 +231,8 @@ void shouldDuplicateObjective() { keyResults.add(keyResultMetric); // new Objective with no KeyResults - Objective newObjective = Objective.Builder.builder() // + Objective newObjective = Objective.Builder + .builder() // .withId(42L) // .withTitle("Objective 2") // .build(); @@ -187,8 +240,8 @@ void shouldDuplicateObjective() { when(objectivePersistenceService.save(any())).thenReturn(newObjective); // act - Objective duplicatedObjective = objectiveBusinessService.duplicateObjective(sourceObjective.getId(), - newObjective, authorizationUser, keyResults); + Objective duplicatedObjective = objectiveBusinessService + .duplicateObjective(sourceObjective.getId(), newObjective, authorizationUser, keyResults); // 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..926211695d 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,62 @@ private static List createOverviews() { private static List createOverviews(AuthorizationUser authorizationUser) { long index = 1L; - List overviews = new ArrayList<>(List.of( - Overview.Builder.builder() + 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())); + .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()))); + .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,50 +150,53 @@ 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) + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)) + .when(overviewValidationService) .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) + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)) + .when(overviewValidationService) .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) + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)) + .when(overviewValidationService) .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 @@ -178,9 +208,13 @@ void getFilteredOverviewShouldReturnSortedListUserTeamsFirst() { 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..1765144005 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,13 +73,26 @@ 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) + 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); @@ -113,18 +125,19 @@ 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")); + 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")); } @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 +147,13 @@ 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 +163,31 @@ 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..b08ef58e2a 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,18 +64,44 @@ 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) + this.objectiveCompleted = Objective.Builder + .builder() + .withId(6L) + .withTitle("Objective 1") + .withState(SUCCESSFUL) .build(); this.objectiveList = List.of(objective, objective, objective, objectiveCompleted); } @@ -109,9 +134,14 @@ void getAllTeamsSortedShouldReturnSortedListUserTeamsFirst() { 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()); + 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 +176,9 @@ 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 +223,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 +243,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 +266,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..f7bfb6a83c 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 @@ -38,14 +37,16 @@ class UserBusinessServiceTest { @BeforeEach void setUp() { - User userAlice = User.Builder.builder() // + User userAlice = User.Builder + .builder() // .withId(2L) // .withFirstname("Alice") // .withLastname("Wunderland") // .withEmail("wunderland@puzzle.ch") // .build(); - User userBob = User.Builder.builder() // + User userBob = User.Builder + .builder() // .withId(9L) // .withFirstname("Bob") // .withLastname("Baumeister") // @@ -81,8 +82,13 @@ 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 +101,13 @@ 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 +120,13 @@ 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 +139,20 @@ void getOrCreateUserShouldReturnSavedUserWhenUserNotFound() { @Test void getOrCreateUserShouldThrowResponseStatusExceptionWhenInvalidUser() { - 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); + 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); 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..119b5cb2ce 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,16 @@ 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..2872c53151 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,21 +1,20 @@ 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") @@ -38,7 +37,7 @@ void getConfigBasedOnActiveEnvShouldBeSuccessfulWhenTenantIsConfiguredProperly(S @ParameterizedTest @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); @@ -55,7 +54,7 @@ void getConfigBasedOnActiveEnvShouldThrowExceptionIfClientCustomizationIsNotFoun @ParameterizedTest @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,7 +81,8 @@ 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)) // @@ -97,23 +97,23 @@ private ClientConfigService mockClientConfigService(TenantConfigProvider.TenantC 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..4647ec9a18 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,10 +30,20 @@ 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) + 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()) + .withKeyResult(KeyResultMetric.Builder + .builder() + .withBaseline(1.0) + .withStretchGoal(13.0) + .withId(8L) + .withObjective(Objective.Builder.builder().withId(1L).build()) + .build()) .build(); } @@ -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..211c249fe2 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,12 @@ class AlignmentPersistenceServiceIT { private Alignment createdAlignment; private static ObjectiveAlignment createObjectiveAlignment(Long id) { - return ObjectiveAlignment.Builder.builder().withId(id) + return ObjectiveAlignment.Builder + .builder() + .withId(id) .withAlignedObjective(Objective.Builder.builder().withId(5L).build()) - .withTargetObjective(Objective.Builder.builder().withId(4L).build()).build(); + .withTargetObjective(Objective.Builder.builder().withId(4L).build()) + .build(); } private static KeyResultAlignment createKeyResultAlignment(Long id) { @@ -39,9 +41,13 @@ private static KeyResultAlignment createKeyResultAlignment(Long id) { } private static KeyResultAlignment createKeyResultAlignment(Long id, int version) { - return KeyResultAlignment.Builder.builder().withId(id).withVersion(version) + return KeyResultAlignment.Builder + .builder() + .withId(id) + .withVersion(version) .withAlignedObjective(Objective.Builder.builder().withId(5L).build()) - .withTargetKeyResult(KeyResultMetric.Builder.builder().withId(8L).build()).build(); + .withTargetKeyResult(KeyResultMetric.Builder.builder().withId(8L).build()) + .build(); } @BeforeEach @@ -105,7 +111,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..2e790ee582 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 @@ -37,8 +36,9 @@ void getAlignmentSelectionByQuarterIdAndTeamIdNotShouldReturnAlignmentSelections .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) { @@ -46,17 +46,18 @@ 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)); + 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)); } } 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..ca93e83964 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,8 @@ 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 +74,8 @@ 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 +84,8 @@ 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..cfdc7f4865 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") @@ -43,7 +42,8 @@ void setParametersShouldBeSuccessfulWithDefaultAuthorizationUser() { @Test void setParametersShouldBeSuccessfulWhenUserIsOkrChampion() { // arrange - var user = User.Builder.builder() // + var user = User.Builder + .builder() // .withId(23L) // .withFirstname("Hanna") // .withLastname("muster") // @@ -87,11 +87,12 @@ void setParametersShouldBeSuccessfulWhenTeamIdsOrObjectiveQueryAreEmpty(List provideListAndString() { - return Stream.of( // - Arguments.of(List.of(), null), // - Arguments.of(List.of(), ""), // - Arguments.of(null, null), // - Arguments.of(null, "")); + return Stream + .of( // + 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,30 +119,37 @@ 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 { private final StringBuilder log = new StringBuilder(); - public String getLog() { - return log.toString(); - } + public String getLog() { return log.toString(); } @Override public TypedQuery setParameter(Parameter parameter, T t) { - log.append(parameter.getName()).append(", ") // - .append(t.getClass().getSimpleName()).append("=").append(t) // + 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(", ") // + TemporalType temporalType) { + log + .append(parameter.getName()) + .append(", ") // + .append(calendar.getTime()) + .append(", ") // .append(temporalType.name()) // .append("\n"); return null; @@ -149,8 +157,11 @@ public TypedQuery setParameter(Parameter parameter, Calenda @Override public TypedQuery setParameter(Parameter parameter, Date date, TemporalType temporalType) { - log.append(parameter.getName()).append(", ") // - .append(date).append(", ") // + log + .append(parameter.getName()) + .append(", ") // + .append(date) + .append(", ") // .append(temporalType.name()) // .append("\n"); return null; @@ -158,16 +169,23 @@ public TypedQuery setParameter(Parameter parameter, Date date, @Override public TypedQuery setParameter(String s, Object o) { - log.append(s).append(", ") // - .append(o.getClass().getSimpleName()).append("=").append(o) // + 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(", ") // + log + .append(s) + .append(", ") // + .append(calendar.getTime()) + .append(", ") // .append(temporalType.name()) // .append("\n"); return null; @@ -175,8 +193,11 @@ public TypedQuery setParameter(String s, Calendar calendar, TemporalT @Override public TypedQuery setParameter(String s, Date date, TemporalType temporalType) { - log.append(s).append(", ") // - .append(date).append(", ") // + log + .append(s) + .append(", ") // + .append(date) + .append(", ") // .append(temporalType.name()) // .append("\n"); return null; @@ -184,16 +205,23 @@ public TypedQuery setParameter(String s, Date date, TemporalType temp @Override public TypedQuery setParameter(int i, Object o) { - log.append(i).append(", ") // - .append(o.getClass().getSimpleName()).append("=").append(o) // + 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(", ") // + log + .append(i) + .append(", ") // + .append(calendar.getTime()) + .append(", ") // .append(temporalType.name()) // .append("\n"); return null; @@ -201,8 +229,11 @@ public TypedQuery setParameter(int i, Calendar calendar, TemporalType @Override public TypedQuery setParameter(int i, Date date, TemporalType temporalType) { - log.append(i).append(", ") // - .append(date).append(", ") // + 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..f409da5784 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") @@ -36,7 +35,8 @@ void appendObjectiveShouldBeSuccessfulWithDefaultAuthorizationUser() { @Test void appendObjectiveShouldBeSuccessfulWhenUserIsOkrChampion() { // arrange - var user = User.Builder.builder() // + var user = User.Builder + .builder() // .withId(23L) // .withFirstname("Hanna") // .withLastname("muster") // @@ -57,7 +57,7 @@ void appendObjectiveShouldBeSuccessfulWhenUserIsOkrChampion() { @ParameterizedTest @MethodSource("provideListAndString") void appendOverviewShouldBeSuccessfulWhenTeamIdsOrObjectiveQueryAreEmpty(List teamIds, - String objectiveQuery) { + String objectiveQuery) { // arrange var criteria = new AuthorizationCriteria(); @@ -70,11 +70,12 @@ void appendOverviewShouldBeSuccessfulWhenTeamIdsOrObjectiveQueryAreEmpty(List provideListAndString() { - return Stream.of( // - Arguments.of(List.of(), null), // - Arguments.of(List.of(), ""), // - Arguments.of(null, null), // - Arguments.of(null, "")); + return Stream + .of( // + 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 +93,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..a11b61e128 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 { 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 6894bfe27d..2e2d44d376 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,13 @@ private static Completed createCompleted(Long id) { } private static Completed createCompleted(Long id, int version) { - return Completed.Builder.builder().withId(id).withVersion(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(); + .withComment(WIR_HABEN_ES_GUT_GESCHAFFT) + .build(); } private static final String COMPLETED = "Completed"; @@ -91,7 +94,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 +110,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 +119,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"))); @@ -130,7 +133,7 @@ void deleteCompletedShouldThrowExceptionWhenCompletedNotFound() { long noExistentId = getNonExistentId(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> completedPersistenceService.findById(noExistentId)); + () -> completedPersistenceService.findById(noExistentId)); List expectedErrors = List .of(new ErrorDto("MODEL_WITH_ID_NOT_FOUND", List.of(COMPLETED, String.valueOf(noExistentId)))); 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 40296fdf4f..bd99d34753 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,10 +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()) + 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()) + .withObjective(Objective.Builder.builder().withId(4L).build()) + .withCreatedOn(LocalDateTime.now()) .build(); } @@ -42,11 +48,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") + 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()) + .withObjective(Objective.Builder.builder().withId(4L).build()) + .withCreatedOn(LocalDateTime.now()) .build(); } @@ -100,7 +113,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 +125,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))); @@ -128,8 +141,8 @@ void recreateEntityShouldUpdateKeyResultNoTypeChange() { createdKeyResult.setTitle(KEY_RESULT_UPDATED); Long keyResultId = createdKeyResult.getId(); - KeyResult recreatedKeyResult = keyResultPersistenceService.recreateEntity(createdKeyResult.getId(), - createdKeyResult); + KeyResult recreatedKeyResult = keyResultPersistenceService + .recreateEntity(createdKeyResult.getId(), createdKeyResult); assertNotNull(createdKeyResult.getId()); assertEquals(KEY_RESULT_UPDATED, recreatedKeyResult.getTitle()); @@ -138,7 +151,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 +168,21 @@ 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); + KeyResult recreatedKeyResult = keyResultPersistenceService + .recreateEntity(keyResultOrdinal.getId(), keyResultOrdinal); assertNotNull(createdKeyResult.getId()); assertEquals(createdKeyResult.getObjective().getId(), recreatedKeyResult.getObjective().getId()); @@ -172,7 +192,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 +232,8 @@ 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 +256,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))); @@ -249,7 +270,7 @@ void deleteKeyResultShouldThrowExceptionWhenKeyResultNotFound() { long nonExistentId = getNonExistentId(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> keyResultPersistenceService.findById(nonExistentId)); + () -> keyResultPersistenceService.findById(nonExistentId)); List expectedErrors = List.of(ErrorDto.of(MODEL_NOT_FOUND, List.of(KEYRESULT, nonExistentId))); 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..b2f83eb360 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,8 @@ 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 +89,11 @@ 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,8 @@ 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 +117,8 @@ 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 +128,11 @@ 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 +143,9 @@ 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 +156,8 @@ 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 +167,11 @@ 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 +182,11 @@ 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 +229,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(); @@ -244,19 +258,20 @@ private static Stream invalidTeamsAndQuarters() { var validQuarter = Quarter.Builder.builder().withId(CURRENT_QUARTER_ID).build(); 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)); + 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)); } @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..1eb6486749 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,46 @@ 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 + 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 private final AuthorizationUser authorizationUser = defaultAuthorizationUser(); @Autowired @@ -58,8 +58,8 @@ 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 +73,24 @@ 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 ad42955688..b0fd2a31ea 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,20 +22,9 @@ import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.web.server.ResponseStatusException; -import java.util.List; -import java.util.stream.Collectors; - -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 */ @@ -69,7 +67,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); @@ -111,9 +109,7 @@ void saveShouldThrowExceptionInTheCaseOfOptimisticLockingFailure() throws Respon var persistenceBaseForTest = new PersistenceBase<>(testRepository) { @Override - public String getModelName() { - return "for_test"; - } + public String getModelName() { return "for_test"; } }; // act + assert @@ -162,7 +158,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()); @@ -180,7 +176,11 @@ private void assertEntityNotFound(long entityId) { } private static User createUserWithUniqueName(String name) { - return User.Builder.builder().withFirstname(name).withLastname("Muster").withEmail("hans.muster@puzzle.ch") + return User.Builder + .builder() + .withFirstname(name) + .withLastname("Muster") + .withEmail("hans.muster@puzzle.ch") .build(); } } \ No newline at end of file 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..4dd6d02829 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 { @@ -46,14 +45,18 @@ void getMostCurrentQuartersShouldReturnCurrentQuarterAndFutureQuarterAndGJForTes } private void assertGJForTestsQuarterIsFoundOnce(List quarters) { - long foundGJForTestsQuartersCount = quarters.stream() - .filter(quarter -> quarter.getLabel().equals(GJ_FOR_TEST_QUARTER_LABEL)).count(); + long foundGJForTestsQuartersCount = quarters + .stream() + .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(); + long foundCurrentQuartersCount = quarters + .stream() + .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..8fe2ac1b85 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 { @@ -45,11 +44,13 @@ void tearDown() { @Test void saveShouldSaveUserWithEmptyUserTeamList() { // arrange - var newUser = User.Builder.builder() // + var newUser = User.Builder + .builder() // .withFirstname("Hans") // .withLastname("Muster") // .withEmail("muster@puzzle.ch") // - .withUserTeamList(List.of()).build(); + .withUserTeamList(List.of()) + .build(); // act createdUser = userPersistenceService.save(newUser); @@ -63,11 +64,13 @@ void saveShouldSaveUserWithEmptyUserTeamList() { @Test void saveShouldSaveUserWithNullUserTeamList() { // arrange - var newUser = User.Builder.builder() // + var newUser = User.Builder + .builder() // .withFirstname("Hans") // .withLastname("Muster") // .withEmail("muster@puzzle.ch") // - .withUserTeamList(null).build(); + .withUserTeamList(null) + .build(); // act createdUser = userPersistenceService.save(newUser); @@ -81,7 +84,8 @@ void saveShouldSaveUserWithNullUserTeamList() { @Test void saveAllShouldSaveAllUsersInTheInputList() { // arrange - var newUser = User.Builder.builder() // + var newUser = User.Builder + .builder() // .withFirstname("Hans") // .withLastname("Muster") // .withEmail("muster@puzzle.ch") // @@ -115,7 +119,8 @@ void getOrCreateUserShouldReturnSingleUserWhenUserFound() { @Test void getOrCreateUserShouldReturnSavedUserWhenUserNotFound() { // arrange - var newUser = User.Builder.builder() // + var newUser = User.Builder + .builder() // .withId(null) // .withFirstname("firstname") // .withLastname("lastname") // @@ -193,13 +198,14 @@ 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() // + User newUser = User.Builder + .builder() // .withId(null) // .withFirstname("firstname") // .withLastname("lastname") // @@ -214,7 +220,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..28b6351ec0 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,31 @@ 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() // + private final KeyResult keyResult = KeyResultMetric.Builder + .builder() // .withId(10L) // - .withTitle("KR Title").build(); // + .withTitle("KR Title") + .build(); // - private final Action action1 = Action.Builder.builder() // + private final Action action1 = Action.Builder + .builder() // .withId(null) // .withAction("Neue Katze") // .withIsChecked(false) // .withPriority(0) // - .withKeyResult(keyResult).build(); + .withKeyResult(keyResult) + .build(); - private final Action action2 = Action.Builder.builder() // + private final Action action2 = Action.Builder + .builder() // .withId(2L) // .withAction("Neues Lama") // .withIsChecked(true) // // - .withPriority(1).withKeyResult(keyResult).build(); + .withPriority(1) + .withKeyResult(keyResult) + .build(); @Mock ActionPersistenceService actionPersistenceService; @@ -60,10 +66,12 @@ 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) { @@ -74,33 +82,67 @@ private static Stream actionPairArgument() { Long id = 3L; 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()))); + 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()))); } @BeforeEach @@ -120,11 +162,12 @@ 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"))); + List expectedErrors = List + .of( // + new ErrorDto("MODEL_NULL", List.of("Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -132,11 +175,12 @@ 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"))); + List expectedErrors = List + .of( // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("ID", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -144,12 +188,18 @@ 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 +211,12 @@ 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"))); + List expectedErrors = List + .of( // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action")), // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("keyResult", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -190,11 +241,12 @@ 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"))); + List expectedErrors = List + .of( // + new ErrorDto("MODEL_NULL", List.of("Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -202,13 +254,14 @@ 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"))); + List expectedErrors = List + .of( // + new ErrorDto("ATTRIBUTE_NULL", List.of("ID", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -216,14 +269,15 @@ 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"))); + List expectedErrors = List + .of( // + new ErrorDto("ATTRIBUTE_CHANGED", List.of("ID", "1", "2"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -236,7 +290,7 @@ void validateOnUpdateShouldThrowExceptionWhenEntityDoesNotExist() { // 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 +313,42 @@ 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"))); + List expectedErrors = List + .of( // + 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) + 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(); + .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"))); + List expectedErrors = List + .of( // + new ErrorDto("ATTRIBUTE_CANNOT_CHANGE", List.of("KeyResult", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -295,13 +356,19 @@ 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 +380,32 @@ 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"))); + List expectedErrors = List + .of( // + 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) + 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"))); + List expectedErrors = List + .of( // + new ErrorDto("ATTRIBUTE_NOT_NULL", List.of("action", "Action"))); assertOkrResponseStatusException(exception, expectedErrors); } diff --git a/backend/src/test/java/ch/puzzle/okr/service/validation/AlignmentValidationServiceTest.java b/backend/src/test/java/ch/puzzle/okr/service/validation/AlignmentValidationServiceTest.java index 3ab1fee119..2f6ae1b47d 100644 --- a/backend/src/test/java/ch/puzzle/okr/service/validation/AlignmentValidationServiceTest.java +++ b/backend/src/test/java/ch/puzzle/okr/service/validation/AlignmentValidationServiceTest.java @@ -1,11 +1,18 @@ package ch.puzzle.okr.service.validation; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import ch.puzzle.okr.ErrorKey; import ch.puzzle.okr.dto.ErrorDto; import ch.puzzle.okr.exception.OkrResponseStatusException; import ch.puzzle.okr.models.alignment.Alignment; import ch.puzzle.okr.models.alignment.KeyResultAlignment; import ch.puzzle.okr.service.persistence.AlignmentPersistenceService; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -15,14 +22,6 @@ import org.springframework.http.HttpStatus; import org.springframework.test.context.bean.override.mockito.MockitoBean; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) class AlignmentValidationServiceTest { @MockitoBean @@ -71,11 +70,11 @@ void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { Alignment alignment = KeyResultAlignment.Builder.builder().withId(3L).build(); OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnUpdate(1L, alignment)); + () -> validator.validateOnUpdate(1L, alignment)); assertEquals(HttpStatus.BAD_REQUEST, exception.getStatusCode()); assertEquals(List.of(new ErrorDto(ErrorKey.ATTRIBUTE_CHANGED.name(), List.of("ID", "1", "3"))), - exception.getErrors()); + exception.getErrors()); verify(validator, times(1)).throwExceptionWhenIdHasChanged(1L, 3L); } 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..1792f668c2 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,95 @@ 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) + 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 KeyResult keyResultOrdinal = KeyResultOrdinal.Builder.builder().withCommitZone("Commit Zone") - .withTargetZone("Target Zone").withTitle("Keyresult Ordinal").withObjective(objective).withOwner(user) + 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 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 +137,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 +160,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 +170,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,10 +179,11 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { @ParameterizedTest @MethodSource("confidenceValidationArguments") void validateOnCreateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confidence, - List expectedErrors) { + List expectedErrors) { // arrange - CheckIn checkIn = CheckInMetric.Builder.builder() // + CheckIn checkIn = CheckInMetric.Builder + .builder() // .withValue(40.9) // .withChangeInfo("ChangeInfo") // .withInitiatives("Initiatives") // @@ -146,27 +196,30 @@ void validateOnCreateShouldThrowExceptionWhenConfidenceIsInvalid(Integer confide // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(checkIn)); + () -> validator.validateOnCreate(checkIn)); assertOkrResponseStatusException(exception, expectedErrors); } @Test void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { // arrange - CheckIn checkInInvalid = CheckInMetric.Builder.builder() // + CheckIn checkInInvalid = CheckInMetric.Builder + .builder() // .withId(null) // - .withChangeInfo("ChangeInfo").build(); + .withChangeInfo("ChangeInfo") + .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> 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"))); + () -> 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"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -186,7 +239,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 +249,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 +262,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 +275,27 @@ 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) + 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,17 +303,31 @@ 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()); @@ -267,7 +342,8 @@ void validateOnUpdateShouldThrowExceptionWhenCheckInsOfKeyResultIsEmpty() { void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { // arrange Long id = 11L; - CheckIn checkInInvalid = CheckInMetric.Builder.builder() // + CheckIn checkInInvalid = CheckInMetric.Builder + .builder() // .withId(id) // .withChangeInfo("ChangeInfo") // .withKeyResult(KeyResultMetric.Builder.builder().withId(13L).build()) // @@ -276,13 +352,14 @@ void validateOnUpdateShouldThrowExceptionWhenAttrsAreMissing() { // 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"))); + 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"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -297,7 +374,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..38849e0379 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,45 @@ 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.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") + 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 @@ -68,8 +88,11 @@ void setUp() { private CompletedValidationService validator; 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"))))); + return Stream + .of(arguments(StringUtils.repeat('1', 5000), + List + .of(new ErrorDto("ATTRIBUTE_SIZE_BETWEEN", + List.of("comment", "Completed", "0", "4096"))))); } @Test @@ -84,7 +107,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); @@ -93,7 +116,8 @@ void validateOnCreateShouldThrowExceptionWhenModelIsNull() { @Test void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { // arrange - Completed completed = Completed.Builder.builder() // + Completed completed = Completed.Builder + .builder() // .withId(300L) // .withObjective(this.objective) // .withComment("Not valid") // @@ -101,7 +125,7 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { // 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); @@ -111,14 +135,15 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { @MethodSource("nameValidationArguments") void validateOnCreateShouldThrowExceptionWhenCommentIsInvalid(String comment, List expectedErrors) { // arrange - Completed completed = Completed.Builder.builder() // + Completed completed = Completed.Builder + .builder() // .withObjective(this.objective) // .withComment(comment) // .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnCreate(completed)); + () -> validator.validateOnCreate(completed)); assertOkrResponseStatusException(exception, expectedErrors); } @@ -126,7 +151,8 @@ void validateOnCreateShouldThrowExceptionWhenCommentIsInvalid(String comment, Li @Test void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { // arrange - Completed completedInvalid = Completed.Builder.builder() // + Completed completedInvalid = Completed.Builder + .builder() // .withId(null) // .withComment("Valid comment") // .withObjective(null) // @@ -134,7 +160,7 @@ void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { // 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..9428f12c87 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,65 @@ 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) + 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 keyResultOrdinal = KeyResultOrdinal.Builder.builder().withCommitZone("Ein Baum") - .withTargetZone("Zwei Bäume").withTitle("Keyresult Ordinal").withObjective(objective).withOwner(user) + 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 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 +107,30 @@ 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 +145,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 +165,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 +175,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); @@ -140,7 +185,8 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { @MethodSource("nameValidationArguments") void validateOnCreateShouldThrowExceptionWhenTitleIsInvalid(String title, List errors) { // arrange - KeyResult keyResult = KeyResultMetric.Builder.builder() // + KeyResult keyResult = KeyResultMetric.Builder + .builder() // .withBaseline(3.0) // .withStretchGoal(5.0) // .withUnit(Unit.EUR) // @@ -154,30 +200,32 @@ void validateOnCreateShouldThrowExceptionWhenTitleIsInvalid(String title, List validator.validateOnCreate(keyResult)); + () -> validator.validateOnCreate(keyResult)); assertOkrResponseStatusException(exception, errors); } @Test void validateOnCreateShouldThrowExceptionWhenAttrsAreMissing() { // arrange - KeyResult keyResultInvalid = KeyResultMetric.Builder.builder() // + KeyResult keyResultInvalid = KeyResultMetric.Builder + .builder() // .withId(null) // .withTitle("Title") // .build(); // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> 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"))); + () -> 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"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -185,10 +233,20 @@ 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 +263,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 +273,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 +286,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()); @@ -243,7 +301,8 @@ void validateOnUpdateShouldThrowExceptionWhenIdHasChanged() { void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String title, List errors) { // arrange Long id = 3L; - KeyResult keyResult = KeyResultMetric.Builder.builder() // + KeyResult keyResult = KeyResultMetric.Builder + .builder() // .withBaseline(3.0) // .withStretchGoal(5.0) // .withUnit(Unit.FTE) // @@ -258,7 +317,7 @@ void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String title, List validator.validateOnUpdate(id, keyResult)); + () -> validator.validateOnUpdate(id, keyResult)); assertOkrResponseStatusException(exception, errors); } @@ -267,7 +326,8 @@ void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String title, List 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"))); + () -> 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"))); assertOkrResponseStatusException(exception, expectedErrors); } @@ -300,7 +361,7 @@ void validateOnDeleteShouldBeSuccessfulWhenValidKeyResultId() { void validateOnDeleteShouldThrowExceptionIfKeyResultIdIsNull() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.validateOnGet(null)); + () -> validator.validateOnGet(null)); verify(validator, times(1)).throwExceptionWhenIdIsNull(null); @@ -315,21 +376,25 @@ void validateOnUpdateShouldThrowExceptionWhenObjectiveIdOfKeyResultHasChanged() Long keyResultId = 1L; Long objectiveId = 2L; Objective objective = Objective.Builder.builder().withId(objectiveId).build(); - KeyResult keyResult = KeyResultMetric.Builder.builder() // + KeyResult keyResult = KeyResultMetric.Builder + .builder() // .withId(keyResultId) // - .withObjective(objective).build(); + .withObjective(objective) + .build(); Long savedObjectiveId = 3L; Objective savedObjective = Objective.Builder.builder().withId(savedObjectiveId).build(); - KeyResult savedKeyResultWithDifferentObjectiveId = KeyResultMetric.Builder.builder() // + KeyResult savedKeyResultWithDifferentObjectiveId = KeyResultMetric.Builder + .builder() // .withId(keyResultId) // - .withObjective(savedObjective).build(); + .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))); 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..2fae85f0be 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,87 @@ 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.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.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.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 +142,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 +163,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 +175,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 +187,21 @@ 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 +210,20 @@ 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"))); + 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"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); @@ -178,14 +232,25 @@ 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 +259,25 @@ 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 +287,25 @@ 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 +326,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 +338,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 +352,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 +367,23 @@ 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 +392,22 @@ void validateOnUpdateShouldThrowExceptionWhenTitleIsInvalid(String title, List 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"))); + () -> 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"))); assertEquals(BAD_REQUEST, exception.getStatusCode()); assertThat(expectedErrors).hasSameElementsAs(exception.getErrors()); @@ -314,12 +416,20 @@ 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 +440,26 @@ 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 +469,26 @@ 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 +498,32 @@ 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()); @@ -385,14 +534,26 @@ void validateOnUpdateShouldThrowExceptionWheTeamHasChanged() { @ParameterizedTest @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(); + 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(); + 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)); + () -> validator.validateOnCreate(invalidObjective)); List expectedErrors = List .of(new ErrorDto("ATTRIBUTE_MUST_BE_DRAFT", List.of("Objective", "Draft", state.toString()))); @@ -404,15 +565,28 @@ void validateOnCreateShouldThrowExceptionWhenQuarterIsBacklogAndStateIsNotDraft( @ParameterizedTest @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(); + 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(); + 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)); + () -> validator.validateOnUpdate(1L, invalidObjective)); List expectedErrors = List .of(new ErrorDto("ATTRIBUTE_MUST_BE_DRAFT", List.of("Objective", "Draft", state.toString()))); @@ -423,12 +597,25 @@ 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(); + 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(); + 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 +631,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..d5ba366f20 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,8 @@ void throwExceptionWhenStartEndDateQuarterIsNullShouldThrowExceptionWhenStartDat // act + assert OkrResponseStatusException okrResponseStatusException = assertThrows(OkrResponseStatusException.class, - () -> QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull(quarter)); + () -> QuarterValidationService + .throwExceptionWhenStartEndDateQuarterIsNull(quarter)); assertEquals(BAD_REQUEST, okrResponseStatusException.getStatusCode()); } @@ -72,7 +72,8 @@ void throwExceptionWhenStartEndDateQuarterIsNullShouldThrowExceptionWhenEndDateI // act + assert OkrResponseStatusException okrResponseStatusException = assertThrows(OkrResponseStatusException.class, - () -> QuarterValidationService.throwExceptionWhenStartEndDateQuarterIsNull(quarter)); + () -> QuarterValidationService + .throwExceptionWhenStartEndDateQuarterIsNull(quarter)); assertEquals(BAD_REQUEST, okrResponseStatusException.getStatusCode()); } @@ -100,7 +101,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 +115,12 @@ 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 +134,12 @@ 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..cd4bb9a9b4 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,12 @@ 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 +68,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 +89,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 +102,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 +115,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 +127,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 +139,13 @@ 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"))); + List expectedErrors = List + .of(new ErrorDto("ATTRIBUTE_NOT_NULL", 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 +155,9 @@ 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 +170,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 +182,15 @@ 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"))); + List expectedErrors = List + .of(new ErrorDto("ATTRIBUTE_NOT_NULL", 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..d229e06346 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,30 @@ class UserValidationServiceTest { @BeforeEach void setUp() { - user = User.Builder.builder().withId(1L).withFirstname("Bob").withLastname("Kaufmann") - .withEmail("kaufmann@puzzle.ch").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(); + 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 +73,80 @@ 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 +160,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 +180,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 +201,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 +213,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 +225,15 @@ void validateOnCreateShouldThrowExceptionWhenIdIsNotNull() { @ParameterizedTest @MethodSource("firstNameValidationArguments") void validateOnCreateShouldThrowExceptionWhenFirstnameIsInvalid(String name, List errors) { - User user2 = User.Builder.builder().withEmail("max@mail.com").withFirstname(name).withLastname("lastname") + 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 +243,15 @@ 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) + 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 +261,15 @@ 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") + 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 +278,15 @@ 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 +308,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 +320,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 +335,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 +351,16 @@ 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 +370,16 @@ 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 +389,16 @@ 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 +407,15 @@ 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 +434,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 +454,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..0b4b1318ad 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,7 +170,8 @@ void throwExceptionWhenIdHasChangedShouldThrowExceptionWhenIdsAreNotEqual() { // act + assert OkrResponseStatusException exception = assertThrows(OkrResponseStatusException.class, - () -> validator.throwExceptionWhenIdHasChanged(id, modelId)); + () -> validator + .throwExceptionWhenIdHasChanged(id, modelId)); // assert List expectedErrors = List @@ -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)); - - 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")) // - ); + () -> 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")) // + ); 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 9ec1fc258d..189ba7815f 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,58 @@ 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) + 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()) + .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) + 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()) + .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); public static final String CHECK_IN_METRIC_JSON = """ { 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 bdb71c1a08..ce37dc45b4 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,120 @@ 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) + 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 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 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..b3cf7c9ee6 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/SpringIntegrationTest.java +++ b/backend/src/test/java/ch/puzzle/okr/test/SpringIntegrationTest.java @@ -1,11 +1,10 @@ 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 }) @Retention(RetentionPolicy.RUNTIME) @Documented 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 c09fa3994b..fcfc6d1345 100644 --- a/backend/src/test/java/ch/puzzle/okr/test/TestHelper.java +++ b/backend/src/test/java/ch/puzzle/okr/test/TestHelper.java @@ -8,8 +8,6 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.security.oauth2.jwt.Jwt; - import java.io.IOException; import java.time.Instant; import java.util.ArrayList; @@ -18,6 +16,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() { @@ -30,7 +29,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) + return User.Builder + .builder() + .withId(id) + .withFirstname(FIRSTNAME) + .withLastname(LASTNAME) + .withEmail(EMAIL) .build(); } @@ -42,12 +46,16 @@ public static User defaultOkrChampion(Long id) { public static User defaultUserWithTeams(Long userId, List adminTeams, List memberTeams) { var user = defaultUser(userId); - var adminUserTeams = adminTeams.stream() + var adminUserTeams = adminTeams + .stream() .map(t -> UserTeam.Builder.builder().withTeamAdmin(true).withTeam(t).withUser(user).build()); - var memberUserTeams = memberTeams.stream() + 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))); + user + .setUserTeamList(Stream + .concat(adminUserTeams, memberUserTeams) + .collect(Collectors.toCollection(ArrayList::new))); return user; } @@ -64,13 +72,14 @@ 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) { - User user = User.Builder.builder() // + boolean isOkrChampion) { + User user = User.Builder + .builder() // .withId(id) // .withFirstname(firstname) // .withLastname(lastname) // 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..6b65465213 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") @@ -103,7 +102,8 @@ void nowIsInQuarterShouldReturnFalseIfNowIsAfterQuarterEndDate() { } private Quarter quarter(LocalDate startDate, LocalDate endDate) { - return Quarter.Builder.builder() // + return Quarter.Builder + .builder() // .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..2d4b3be6f0 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") @@ -21,34 +20,35 @@ 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")); + 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")); } } 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..cb33187b06 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()); @@ -36,66 +35,80 @@ 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')")); + 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')")); } @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()); @@ -113,39 +126,48 @@ 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')")); + 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')")); } @DisplayName("currentQuarter() should throw exception if no matching quarter is found for now") @@ -159,7 +181,7 @@ void currentQuarterShouldThrowExceptionIfNoMatchingQuarterIsFoundForNow() { // act RuntimeException exception = assertThrows(RuntimeException.class, - () -> allQuartersOfCurrentYear.currentQuarter(in2Years)); + () -> allQuartersOfCurrentYear.currentQuarter(in2Years)); // assert assertEquals(RuntimeException.class, exception.getClass()); @@ -181,13 +203,16 @@ 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')") // - ); + 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')") // + ); } } 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)";