From 62d030fd87bdd60fdfcc1bfbc2abf50611e85a1a Mon Sep 17 00:00:00 2001 From: Gcolon021 <34667267+Gcolon021@users.noreply.github.com> Date: Wed, 30 Oct 2024 10:05:09 -0400 Subject: [PATCH] [ALS-7687] Create PSAMA cache unit test (#232) * Remove duplicate and unused test classes * Switch project parent to Spring Boot and update dependencies. Updated the project parent to `spring-boot-starter-parent` with version `3.3.5`. Consolidated and streamlined dependencies to align with Spring Boot configurations, ensuring compatibility and removing redundant entries. * Refactor tests to use JUnit 5 and Spring Boot Test Migrated test classes from JUnit 4 to JUnit 5, replacing @Before with @BeforeEach, @Test(expected) with assertThrows, and @RunWith with @SpringBootTest/@ContextConfiguration annotations. Updated Mockito annotations to @MockBean where appropriate and used dependency injection with @Autowired to initialize services. * Add unit tests for caching mechanisms in auth services Introduced `CacheTest` to validate caching behavior in `AccessRuleService` and `UserService`. These tests ensure the correct usage of caches like `mergedRulesCache`, `preProcessedAccessRules`, and `mergedTemplateCache`, and verify proper eviction mechanisms. * Update Dockerfiles for dynamic JAR filename handling Changed the Dockerfile COPY commands to use a wildcard for JAR filenames, ensuring compatibility with differing build outputs. Additionally, added the packaging type as 'jar' in the pom.xml to standardize project packaging. * Add AWS Secrets Manager dependency to pom.xml Included the `aws-secretsmanager-jdbc` dependency in the pom.xml to support secure secrets management with AWS Secrets Manager. This change aims to enhance security by integrating Secrets Manager into the authentication services. --- pic-sure-auth-services/Dockerfile | 2 +- pic-sure-auth-services/bdc.Dockerfile | 2 +- pic-sure-auth-services/dev.Dockerfile | 2 +- pic-sure-auth-services/pom.xml | 244 +++---- .../avillach/auth/config/SecurityConfig.java | 2 - .../auth/service/impl/BasicMailService.java | 7 +- .../auth/service/impl/PrivilegeService.java | 5 +- .../dbmi/avillach/ApplicationServiceTest.java | 28 +- .../AuthorizationServiceTestByUseCases.java | 682 ------------------ .../auth/service/PrivilegeServiceTest.java | 141 ---- .../auth/service/RoleServiceTest.java | 55 +- .../service/impl/AccessRuleServiceTest.java | 32 +- .../service/impl/ApplicationServiceTest.java | 53 +- .../impl/Auth0MatchingServiceTest.java | 47 +- .../impl/AuthenticationServiceTest.java | 62 +- .../impl/AuthorizationServiceTest.java | 27 +- .../service/impl/BasicMailServiceTest.java | 27 +- .../avillach/auth/service/impl/CacheTest.java | 247 +++++++ .../impl/ConnectionWebServiceTest.java | 23 +- .../impl/CustomUserDetailServiceTest.java | 30 +- .../service/impl/PrivilegeServiceTest.java | 40 +- .../service/impl/RASPassPortServiceTest.java | 27 +- .../auth/service/impl/RoleServiceTest.java | 60 +- .../service/impl/StudyAccessServiceTest.java | 25 +- .../auth/service/impl/TOSServiceTest.java | 33 +- .../auth/service/impl/TokenServiceTest.java | 40 +- .../impl/UserMetadataMappingServiceTest.java | 37 +- .../auth/service/impl/UserServiceTest.java | 91 ++- .../AuthenticationServiceTest.java | 58 +- .../RASAuthenticationServiceTest.java | 31 +- ...> AuthorizationServiceByUseCasesTest.java} | 72 +- .../AuthorizationServiceTest.java | 86 +-- .../FenceAuthorizationService.java | 4 - .../avillach/auth/utils/JsonUtilsTest.java | 25 +- 34 files changed, 930 insertions(+), 1417 deletions(-) delete mode 100644 pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/AuthorizationServiceTestByUseCases.java delete mode 100644 pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/PrivilegeServiceTest.java create mode 100644 pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/CacheTest.java rename pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/{AuthorizationServiceTestByUseCases.java => AuthorizationServiceByUseCasesTest.java} (90%) delete mode 100644 pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/FenceAuthorizationService.java diff --git a/pic-sure-auth-services/Dockerfile b/pic-sure-auth-services/Dockerfile index 79ed6e10..f49b1511 100644 --- a/pic-sure-auth-services/Dockerfile +++ b/pic-sure-auth-services/Dockerfile @@ -15,7 +15,7 @@ RUN mvn clean install -DskipTests FROM amazoncorretto:21.0.1-alpine3.18 # Copy jar and access token from maven build -COPY --from=build /app/pic-sure-auth-services/target/pic-sure-auth-services.jar /pic-sure-auth-service.jar +COPY --from=build /app/pic-sure-auth-services/target/pic-sure-auth-services-*.jar /pic-sure-auth-service.jar # Copy the AWS certificate COPY pic-sure-auth-services/aws_certs/certificate.der /certificate.der diff --git a/pic-sure-auth-services/bdc.Dockerfile b/pic-sure-auth-services/bdc.Dockerfile index 69a1bdad..a1f80fe3 100644 --- a/pic-sure-auth-services/bdc.Dockerfile +++ b/pic-sure-auth-services/bdc.Dockerfile @@ -20,7 +20,7 @@ ENV DATASOURCE_USERNAME=${DATASOURCE_USERNAME} ENV STACK_SPECIFIC_APPLICATION_ID=${application_id_for_base_query} # Copy jar and access token from maven build -COPY --from=build /app/pic-sure-auth-services/target/pic-sure-auth-services.jar /pic-sure-auth-service.jar +COPY --from=build /app/pic-sure-auth-services/target/pic-sure-auth-services-*.jar /pic-sure-auth-service.jar # Copy additional bdc configuration files. Root of the project COPY config/psama/bdc/psama-db-config.properties /config/psama-db-config.properties diff --git a/pic-sure-auth-services/dev.Dockerfile b/pic-sure-auth-services/dev.Dockerfile index 7eaf4df6..50eaeac1 100644 --- a/pic-sure-auth-services/dev.Dockerfile +++ b/pic-sure-auth-services/dev.Dockerfile @@ -13,7 +13,7 @@ FROM amazoncorretto:21.0.1-alpine3.18 # Copy jar and access token from maven build #COPY target/pic-sure-auth-services.jar /pic-sure-auth-service.jar -COPY --from=build /app/pic-sure-auth-services/target/pic-sure-auth-services.jar /pic-sure-auth-service.jar +COPY --from=build /app/pic-sure-auth-services/target/pic-sure-auth-services-*.jar /pic-sure-auth-service.jar EXPOSE 8090 diff --git a/pic-sure-auth-services/pom.xml b/pic-sure-auth-services/pom.xml index 7cde3c6d..8b8e25df 100644 --- a/pic-sure-auth-services/pom.xml +++ b/pic-sure-auth-services/pom.xml @@ -1,64 +1,45 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - pic-sure-auth-microapp - edu.harvard.hms.dbmi.avillach.picsure.auth.microapp - 2.0-SNAPSHOT + org.springframework.boot + spring-boot-starter-parent + 3.3.5 + edu.harvard.hms.dbmi.avillach pic-sure-auth-services + 2.0-SNAPSHOT + pic-sure-auth-services jar - + + + + + + + + + + + + + - 2.3.0 + 21 - org.apache.httpcomponents.client5 - httpclient5 - 5.2.1 - - - org.slf4j - slf4j-api - - - - - - - - org.springframework - spring-web - 6.1.5 + org.springframework.boot + spring-boot-starter - org.springframework.boot spring-boot-starter-web 3.2.3 - - - - org.springframework.boot - spring-boot-autoconfigure - 3.2.3 - - - org.springframework.boot - spring-boot-starter-security - 3.2.4 - - - - org.springframework.boot - spring-boot-starter-mail - 3.2.4 - org.springframework.boot @@ -82,62 +63,15 @@ spring-context 6.1.10 - - - net.bytebuddy - byte-buddy - 1.14.13 - - - - com.mysql - mysql-connector-j - 8.2.0 - - - com.amazonaws.secretsmanager - aws-secretsmanager-jdbc - 2.0.0 - - - - io.jsonwebtoken - jjwt-api - 0.12.5 - - - io.jsonwebtoken - jjwt-impl - 0.12.5 - runtime - - - io.jsonwebtoken - jjwt-jackson - 0.12.5 - runtime - - - com.auth0 - auth0 - 2.10.1 - - - junit - junit - 4.13.1 - test - - com.jayway.jsonpath - json-path - 2.9.0 + org.springframework.boot + spring-boot-starter-test + 3.3.4 - org.mockito - mockito-core - 2.23.4 - test + org.springframework.boot + spring-boot-starter-security + 3.2.4 com.github.spullara.mustache.java @@ -156,7 +90,6 @@ jakarta.mail-api 2.1.3 - io.swagger.core.v3 @@ -210,67 +143,76 @@ jackson-annotations 2.17.0 + + + net.bytebuddy + byte-buddy + 1.14.13 + + + + com.mysql + mysql-connector-j + 8.2.0 + + + com.amazonaws.secretsmanager + aws-secretsmanager-jdbc + 2.0.0 + + + com.jayway.jsonpath + json-path + 2.9.0 + + + + io.jsonwebtoken + jjwt-api + 0.12.5 + + + io.jsonwebtoken + jjwt-impl + 0.12.5 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.12.5 + runtime + + + com.auth0 + auth0 + 2.10.1 + + + org.apache.httpcomponents.client5 + httpclient5 + 5.2.1 + + + org.slf4j + slf4j-api + + + + + junit + junit + 4.13.1 + test + - - - dev - - - org.springframework.boot - spring-boot-devtools - true - - - - + - ${project.artifactId} - - org.apache.maven.plugins - maven-compiler-plugin - 3.11.0 - - 21 - 21 - - org.springframework.boot spring-boot-maven-plugin - 3.2.4 - - edu.harvard.hms.dbmi.avillach.auth.Application - JAR - - - - - repackage - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 1.5 - - - reserve-network-port - - reserve-network-port - - process-test-resources - - - test.server.port - - - - - + \ No newline at end of file diff --git a/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/config/SecurityConfig.java b/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/config/SecurityConfig.java index 036f31be..950e91c4 100644 --- a/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/config/SecurityConfig.java +++ b/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/config/SecurityConfig.java @@ -1,9 +1,7 @@ package edu.harvard.hms.dbmi.avillach.auth.config; import edu.harvard.hms.dbmi.avillach.auth.filter.JWTFilter; -import edu.harvard.hms.dbmi.avillach.auth.service.impl.AccessRuleService; import edu.harvard.hms.dbmi.avillach.auth.service.impl.CacheEvictionService; -import edu.harvard.hms.dbmi.avillach.auth.service.impl.SessionService; import edu.harvard.hms.dbmi.avillach.auth.service.impl.UserService; import edu.harvard.hms.dbmi.avillach.auth.utils.JWTUtil; import org.springframework.beans.factory.annotation.Autowired; diff --git a/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/BasicMailService.java b/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/BasicMailService.java index 64848210..f55a8d79 100644 --- a/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/BasicMailService.java +++ b/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/BasicMailService.java @@ -43,8 +43,11 @@ public class BasicMailService implements MailService { @Autowired - public BasicMailService(JavaMailSender mailSender, @Value("${application.template.path}") String templatePath, @Value("${application.system.name}") String systemName, - @Value("${application.access.grant.email.subject") String accessGrantEmailSubject, @Value("${application.admin.users}") String adminUsers) { + public BasicMailService(JavaMailSender mailSender, + @Value("${application.template.path}") String templatePath, + @Value("${application.system.name}") String systemName, + @Value("${application.access.grant.email.subject") String accessGrantEmailSubject, + @Value("${application.admin.users}") String adminUsers) { this.mailSender = mailSender; this.templatePath = templatePath; this.systemName = systemName; diff --git a/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/PrivilegeService.java b/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/PrivilegeService.java index cc02f9cd..8bfdbe7c 100644 --- a/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/PrivilegeService.java +++ b/pic-sure-auth-services/src/main/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/PrivilegeService.java @@ -12,7 +12,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.event.ApplicationContextEvent; -import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; @@ -46,7 +45,9 @@ public class PrivilegeService { private static final String topmedAccessionField = "\\\\_Topmed Study Accession with Subject ID\\\\"; @Autowired - protected PrivilegeService(PrivilegeRepository privilegeRepository, ApplicationService applicationService, AccessRuleService accessRuleService, + protected PrivilegeService(PrivilegeRepository privilegeRepository, + ApplicationService applicationService, + AccessRuleService accessRuleService, @Value("${fence.variant.annotation.columns}") String variantAnnotationColumns, @Value("${fence.harmonized.consent.group.concept.path}") String fenceHarmonizedConsentGroupConceptPath, @Value("${fence.parent.consent.group.concept.path}") String fenceParentConceptPath, diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/ApplicationServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/ApplicationServiceTest.java index 74ebd3af..f9d4364d 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/ApplicationServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/ApplicationServiceTest.java @@ -4,14 +4,14 @@ import edu.harvard.hms.dbmi.avillach.auth.repository.ApplicationRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.PrivilegeRepository; import edu.harvard.hms.dbmi.avillach.auth.service.impl.ApplicationService; +import edu.harvard.hms.dbmi.avillach.auth.utils.FenceMappingUtility; import edu.harvard.hms.dbmi.avillach.auth.utils.JWTUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.ContextConfiguration; import java.security.SecureRandom; import java.util.Base64; @@ -19,19 +19,19 @@ import static org.mockito.Mockito.spy; -@RunWith(MockitoJUnitRunner.class) +@SpringBootTest +@ContextConfiguration(classes = {ApplicationService.class, JWTUtil.class}) public class ApplicationServiceTest { - @InjectMocks private ApplicationService applicationService; - @Mock + @MockBean private PrivilegeRepository privilegeRepository; - @Mock + @MockBean private ApplicationRepository applicationRepository; - @Before + @BeforeEach public void init() { JWTUtil jwtUtil = spy(new JWTUtil(generate256Base64Secret(), false)); applicationService = new ApplicationService(applicationRepository, privilegeRepository, jwtUtil); @@ -46,8 +46,8 @@ public void testGenerateToken() { String token = applicationService.generateApplicationToken(application); - Assert.assertNotNull("Token is null, given application: " + application.getUuid(), token); - Assert.assertTrue("Token is too short",token.length() > 10); + Assertions.assertNotNull(token, "Token is null, given application: " + application.getUuid()); + Assertions.assertTrue(token.length() > 10, "Token is too short"); } /** diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/AuthorizationServiceTestByUseCases.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/AuthorizationServiceTestByUseCases.java deleted file mode 100644 index 541d9165..00000000 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/AuthorizationServiceTestByUseCases.java +++ /dev/null @@ -1,682 +0,0 @@ -package edu.harvard.hms.dbmi.avillach; - -import com.fasterxml.jackson.databind.ObjectMapper; -import edu.harvard.hms.dbmi.avillach.auth.entity.AccessRule; -import edu.harvard.hms.dbmi.avillach.auth.repository.AccessRuleRepository; -import edu.harvard.hms.dbmi.avillach.auth.service.impl.RoleService; -import edu.harvard.hms.dbmi.avillach.auth.service.impl.SessionService; -import edu.harvard.hms.dbmi.avillach.auth.service.impl.authorization.AuthorizationService; -import edu.harvard.hms.dbmi.avillach.auth.service.impl.AccessRuleService; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.Mockito; - -import java.io.IOException; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -/** - *

This is a test class from the view of high level use cases (user input aspect)

- *
- *

This class should contain the following use cases:

- * - * - * We also have a class testing from the aspect of design, which means each test case is just testing one feature. - * @see AuthorizationServiceTest - */ -public class AuthorizationServiceTestByUseCases extends AuthorizationService{ - - - ObjectMapper mapper = new ObjectMapper(); - - - private static AccessRule rule_caseA; - private static AccessRule rule_caseB; - private static AccessRule rule_caseC; - private static AccessRule rule_caseD; - private static AccessRule rule_caseE; - private static AccessRule rule_caseE_2; - private static AccessRule rule_caseF; - - - - private static AccessRule AR_CategoryFilter_String_contains; - private static AccessRule AR_CategoryFilter_Array_Contains; - private static AccessRule AR_ExpectedResultType_String_contains; - - - public static String sample_caseAB_pass = "{\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"\\\\demographics\\\\SEX\\\\\": [\n" + - " \"male\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ],\n" + - " \"expectedResultType\": \"COUNT\",\n" + - " \"fields\": [\n" + - " \"\\\\demographics\\\\SEX\\\\\",\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ]\n" + - " },\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseAB_fail = "{\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"\\\\laboratory\\\\SEX\\\\\": [\n" + - " \"male\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ],\n" + - " \"expectedResultType\": \"DATAFRAME\",\n" + - " \"fields\": [\n" + - " \"\\\\demographics\\\\SEX\\\\\",\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ]\n" + - " },\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseCD_pass = "{\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"\\\\demographics\\\\SEX\\\\\": [\n" + - " \"male\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ],\n" + - " \"expectedResultType\": \"dataframe\",\n" + - " \"fields\": [\n" + - " \"\\\\demographics\\\\SEX\\\\\",\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ]\n" + - " },\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseCD_fail = "{\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"\\\\demographics\\\\SEX\\\\\": [\n" + - " \"male\",\n" + - " \"female\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ],\n" + - " \"expectedResultType\": \"dataframe\",\n" + - " \"fields\": [\n" + - " \"\\\\demographics\\\\SEX\\\\\",\n" + - " \"\\\\demographics\\\\AGE\\\\\",\n" + - " \"\\\\laboratory\\\\AGE\\\\\"\n" + - " ]\n" + - " },\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseCD_fail_2 = "{\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"\\\\laboratory\\\\SEX\\\\\": [\n" + - " \"male\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ],\n" + - " \"expectedResultType\": \"dataframe\",\n" + - " \"fields\": [\n" + - " \"\\\\demographics\\\\SEX\\\\\",\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ]\n" + - " },\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseE_pass = "{\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"\\\\demographics\\\\SEX\\\\\": [\n" + - " \"male\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ],\n" + - " \"expectedResultType\": \"dataframe\",\n" + - " \"fields\": [\n" + - " \"\\\\demographics\\\\SEX\\\\\",\n" + - " \"\\\\laboratory\\\\AGE\\\\\"\n" + - " ]\n" + - " },\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseE_2_pass = "{\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"\\\\demographics\\\\SEX\\\\\": [\n" + - " \"female\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ],\n" + - " \"expectedResultType\": \"dataframe\",\n" + - " \"fields\": [\n" + - " \"\\\\demographics\\\\SEX\\\\\",\n" + - " \"\\\\examination\\\\AGE\\\\\"\n" + - " ]\n" + - " },\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseE_fail = "{\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"\\\\demographics\\\\SEX\\\\\": [\n" + - " \"nothing\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ],\n" + - " \"expectedResultType\": \"dataframe\",\n" + - " \"fields\": [\n" + - " \"\\\\demographics\\\\SEX\\\\\",\n" + - " \"\\\\examination\\\\AGE\\\\\",\n" + - " \"\\\\laboratory\\\\AGE\\\\\"\n" + - " ]\n" + - " },\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseE_2_fail = "{\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"\\\\demographics\\\\SEX\\\\\": [\n" + - " \"nothing\"\n" + - " ],\n" + - " \"\\\\laboratory\\\\SEX\\\\\": [\n" + - " \"male\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " \"\\\\demographics\\\\AGE\\\\\"\n" + - " ],\n" + - " \"expectedResultType\": \"dataframe\",\n" + - " \"fields\": [\n" + - " \"\\\\demographics\\\\SEX\\\\\",\n" + - " \"\\\\examination\\\\AGE\\\\\"\n" + - " ]\n" + - " },\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseF_pass = "{\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"3,112222,112222,C,T\": [\n" + - " \"1/1\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " ],\n" + - " \"variantInfoFilters\": [\n" + - " {\n" + - " \"categoryVariantInfoFilters\": {\n" + - " \"HD\": [\n" + - " \"\\\"Asthma,_severe\\\"\"\n" + - " ]\n" + - " },\n" + - " \"numericVariantInfoFilters\": {}\n" + - " }\n" + - " ],\n" + - " \"expectedResultType\": \"COUNT\"\n" + - " },\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseF_fail = "{\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"3,112222,112222,C,T\": [\n" + - " \"1/1\"\n" + - " ],\n" + - " \"\\\\demographics\\\\SEX\\\\\": [\n" + - " \"male\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " ],\n" + - " \"variantInfoFilters\": [\n" + - " {\n" + - " \"categoryVariantInfoFilters\": {\n" + - " \"HD\": [\n" + - " \"\\\"Asthma,_severe\\\"\"\n" + - " ]\n" + - " },\n" + - " \"numericVariantInfoFilters\": {}\n" + - " }\n" + - " ],\n" + - " \"expectedResultType\": \"COUNT\"\n" + - " },\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseF_fail_2 = "{\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"3,112222,112222,C,T\": [\n" + - " \"1/1\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " ],\n" + - " \"expectedResultType\": \"COUNT\"\n" + - " },\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseF_fail_3 = "{\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"3,112222,112222,C,T\": [\n" + - " \"1/1\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " ],\n" + - " \"variantInfoFilters\": [\n" + - " {\n" + - " \"categoryVariantInfoFilters\": {\n" + - " \"HD\": [\n" + - " \"\\\"Asthma,_severe\\\"\"\n" + - " ]\n" + - " },\n" + - " \"numericVariantInfoFilters\": {}\n" + - " }\n" + - " ],\n" + - " \"expectedResultType\": \"CROSS_COUNT\"\n" + - " },\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseF_fail_4 = "{\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"3,112222,112222,C,T\": [\n" + - " \"1/1\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {},\n" + - " \"requiredFields\": [\n" + - " \"\\\\000_UDN ID\\\\\"\n" + - " ],\n" + - " \"variantInfoFilters\": [\n" + - " {\n" + - " \"categoryVariantInfoFilters\": {\n" + - " \"HD\": [\n" + - " \"\\\"Asthma,_severe\\\"\"\n" + - " ]\n" + - " },\n" + - " \"numericVariantInfoFilters\": {}\n" + - " }\n" + - " ],\n" + - " \"expectedResultType\": \"COUNT\"\n" + - " },\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public static String sample_caseF_fail_5 = "{\n" + - " \"resourceUUID\": \"8e8c7ed0-87ea-4342-b8da-f939e46bac26\",\n" + - " \"query\": {\n" + - " \"categoryFilters\": {\n" + - " \"3,112222,112222,C,T\": [\n" + - " \"1/1\"\n" + - " ]\n" + - " },\n" + - " \"numericFilters\": {\"nothing\":null},\n" + - " \"requiredFields\": [\n" + - " ],\n" + - " \"variantInfoFilters\": [\n" + - " {\n" + - " \"categoryVariantInfoFilters\": {\n" + - " \"HD\": [\n" + - " \"\\\"Asthma,_severe\\\"\"\n" + - " ]\n" + - " },\n" + - " \"numericVariantInfoFilters\": {}\n" + - " }\n" + - " ],\n" + - " \"expectedResultType\": \"COUNT\"\n" + - " },\n" + - " \"resourceCredentials\": {}\n" + - "}"; - - public AuthorizationServiceTestByUseCases(AccessRuleService accessRuleService, SessionService sessionService, RoleService roleService, String strictConnections) { - super(accessRuleService, sessionService, roleService, strictConnections); - } - - @BeforeClass - public static void init() { - initialTestCaseA(); - initialTestCaseB(); - initialTestCaseC(); - initialTestCaseD(); - initialTestCaseE(); - initialTestCaseF(); - } - - @Before - public void setUp() { - AccessRuleRepository accessRuleRepository = Mockito.mock(AccessRuleRepository.class); - accessRuleService = new AccessRuleService(accessRuleRepository, "false", "false", "false", "false","false", "false"); - } - - @Test - public void testCaseA() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_pass, Map.class), rule_caseA)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_fail, Map.class), rule_caseA)); - } - - private static void initialTestCaseA(){ - rule_caseA = new AccessRule(); - rule_caseA.setUuid(UUID.randomUUID()); - rule_caseA.setType(AccessRule.TypeNaming.NOT_CONTAINS_IGNORE_CASE); - rule_caseA.setName("rule_caseA"); - rule_caseA.setRule("$..expectedResultType"); -// rule_caseA.setRule("$..\\laboratory\\*"); - rule_caseA.setValue("DATAFRAME"); - } - - @Test - public void testCaseB() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_pass, Map.class), rule_caseB)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_fail, Map.class), rule_caseB)); - } - - private static void initialTestCaseB(){ - rule_caseB = new AccessRule(); - rule_caseB.setUuid(UUID.randomUUID()); - rule_caseB.setName("rule_caseB"); - rule_caseB.setRule("$..*"); - rule_caseB.setType(AccessRule.TypeNaming.ANY_CONTAINS); - rule_caseB.setValue("\\demographics\\"); - - AccessRule rule_caseB_sub = new AccessRule(); - rule_caseB_sub.setUuid(UUID.randomUUID()); - rule_caseB_sub.setName("rule_caseB_sub"); - rule_caseB_sub.setRule("$..*"); - rule_caseB_sub.setType(AccessRule.TypeNaming.NOT_CONTAINS_IGNORE_CASE); - rule_caseB_sub.setCheckMapNode(true); - rule_caseB_sub.setValue("\\laboratory\\"); - Set accessRuleSubSet = new HashSet<>(); - accessRuleSubSet.add(rule_caseB_sub); - rule_caseB.setSubAccessRule(accessRuleSubSet); - } - - @Test - public void testCaseC() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_pass, Map.class), rule_caseC)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail, Map.class), rule_caseC)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail_2, Map.class), rule_caseC)); - } - - private static void initialTestCaseC(){ - rule_caseC = new AccessRule(); - rule_caseC.setUuid(UUID.randomUUID()); - rule_caseC.setName("rule_caseC"); - -// AccessRule rule_caseC_gate = new AccessRule(); -// rule_caseC_gate.setName("rule_caseC_gate"); -// rule_caseC_gate.setRule("$.query.expectedResultType"); -// rule_caseC_gate.setType(AccessRule.TypeNaming.NOT_EQUALS); -// rule_caseC_gate.setValue("COUNT"); - - AccessRule rule_caseC_gate2 = new AccessRule(); - rule_caseC_gate2.setUuid(UUID.randomUUID()); - rule_caseC_gate2.setName("rule_caseC_gate2"); - rule_caseC_gate2.setRule("$.query.expectedResultType"); - rule_caseC_gate2.setType(AccessRule.TypeNaming.ALL_EQUALS_IGNORE_CASE); - rule_caseC_gate2.setValue("DATAFRAME"); - - Set rule_caseC_gates = new HashSet<>(); -// rule_caseC_gates.add(rule_caseC_gate); - rule_caseC_gates.add(rule_caseC_gate2); - rule_caseC.setGates(rule_caseC_gates); - - AccessRule rule_caseC_subRule = new AccessRule(); - rule_caseC_subRule.setUuid(UUID.randomUUID()); - rule_caseC_subRule.setName("rule_caseC_subRule"); - rule_caseC_subRule.setRule("$.query.categoryFilters"); - rule_caseC_subRule.setCheckMapNode(true); - rule_caseC_subRule.setCheckMapKeyOnly(true); - rule_caseC_subRule.setType(AccessRule.TypeNaming.ALL_CONTAINS); - rule_caseC_subRule.setValue("\\demographics\\"); - Set rule_caseC_subRules = new HashSet<>(); - rule_caseC_subRules.add(rule_caseC_subRule); - rule_caseC.setSubAccessRule(rule_caseC_subRules); - - AccessRule rule_caseC_subRule2 = new AccessRule(); - rule_caseC_subRule2.setUuid(UUID.randomUUID()); - rule_caseC_subRule2.setName("rule_caseC_subRule"); - rule_caseC_subRule2.setRule("$.query.requiredFields"); - rule_caseC_subRule2.setCheckMapNode(true); - rule_caseC_subRule2.setCheckMapKeyOnly(true); - rule_caseC_subRule2.setType(AccessRule.TypeNaming.ALL_CONTAINS); - rule_caseC_subRule2.setValue("\\demographics\\"); - rule_caseC_subRules.add(rule_caseC_subRule2); - - AccessRule rule_caseC_subRule3 = new AccessRule(); - rule_caseC_subRule3.setUuid(UUID.randomUUID()); - rule_caseC_subRule3.setName("rule_caseC_subRule"); - rule_caseC_subRule3.setRule("$.query.fields"); - rule_caseC_subRule3.setCheckMapNode(true); - rule_caseC_subRule3.setCheckMapKeyOnly(true); - rule_caseC_subRule3.setType(AccessRule.TypeNaming.ALL_CONTAINS); - rule_caseC_subRule3.setValue("\\demographics\\"); - rule_caseC_subRules.add(rule_caseC_subRule3); - } - - @Test - public void testCaseD() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_pass, Map.class), rule_caseD)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail, Map.class), rule_caseD)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail_2, Map.class), rule_caseD)); - } - - private static void initialTestCaseD(){ - rule_caseD = new AccessRule(); - rule_caseD.setUuid(UUID.randomUUID()); - rule_caseD.setName("rule_caseD"); - rule_caseD.setRule("$.query.categoryFilters.\\demographics\\SEX\\"); - rule_caseD.setType(AccessRule.TypeNaming.ALL_EQUALS); - rule_caseD.setValue("male"); - - AccessRule rule_caseD_gate = new AccessRule(); - rule_caseD_gate.setUuid(UUID.randomUUID()); - rule_caseD_gate.setName("rule_caseD_gate"); - rule_caseD_gate.setRule("$.query.expectedResultType"); - rule_caseD_gate.setType(AccessRule.TypeNaming.ALL_EQUALS_IGNORE_CASE); - rule_caseD_gate.setValue("dataframe"); - Set rule_caseD_gates = new HashSet<>(); - rule_caseD_gates.add(rule_caseD_gate); - rule_caseD.setGates(rule_caseD_gates); - } - - @Test - public void testCaseE() throws IOException { - Assert.assertTrue( - accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_pass, Map.class), rule_caseE) - || accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_pass, Map.class), rule_caseE_2) - ); - - Assert.assertTrue( - accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_2_pass, Map.class), rule_caseE) - || accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_2_pass, Map.class), rule_caseE_2) - ); - - Assert.assertFalse( - accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_fail, Map.class), rule_caseE) - || accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_fail, Map.class), rule_caseE_2) - ); - - Assert.assertFalse( - accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_2_fail, Map.class), rule_caseE) - || accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_2_fail, Map.class), rule_caseE_2) - ); - - } - - private static void initialTestCaseE(){ - rule_caseE = new AccessRule(); - rule_caseE.setUuid(UUID.randomUUID()); - rule_caseE.setName("rule_caseE"); - rule_caseE.setRule("$.query.categoryFilters.\\demographics\\SEX\\"); - rule_caseE.setType(AccessRule.TypeNaming.ALL_EQUALS); - rule_caseE.setValue("male"); - - AccessRule rule_caseE_gate = new AccessRule(); - rule_caseE_gate.setUuid(UUID.randomUUID()); - rule_caseE_gate.setName("rule_caseE_gate"); - rule_caseE_gate.setRule("$..*"); - rule_caseE_gate.setType(AccessRule.TypeNaming.ANY_CONTAINS); - rule_caseE_gate.setValue("\\laboratory\\"); - rule_caseE_gate.setCheckMapNode(true); - Set rule_caseE_gates = new HashSet<>(); - rule_caseE_gates.add(rule_caseE_gate); - rule_caseE.setGates(rule_caseE_gates); - - rule_caseE_2 = new AccessRule(); - rule_caseE_2.setUuid(UUID.randomUUID()); - rule_caseE_2.setName("rule_caseE_2"); - rule_caseE_2.setRule("$.query.categoryFilters.\\demographics\\SEX\\"); - rule_caseE_2.setType(AccessRule.TypeNaming.ALL_EQUALS); - rule_caseE_2.setValue("female"); - - AccessRule rule_caseE_2_gate = new AccessRule(); - rule_caseE_2_gate.setUuid(UUID.randomUUID()); - rule_caseE_2_gate.setName("rule_caseE_2_gate"); - rule_caseE_2_gate.setRule("$..*"); - rule_caseE_2_gate.setType(AccessRule.TypeNaming.ANY_CONTAINS); - rule_caseE_2_gate.setValue("\\examination\\"); - rule_caseE_2_gate.setCheckMapNode(true); - Set rule_caseE_2_gates = new HashSet<>(); - rule_caseE_2_gates.add(rule_caseE_2_gate); - rule_caseE_2.setGates(rule_caseE_2_gates); - } - - - @Test - public void testCaseF() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_pass, Map.class), rule_caseF)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail, Map.class), rule_caseF)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_2, Map.class), rule_caseF)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_3, Map.class), rule_caseF)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_4, Map.class), rule_caseF)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_5, Map.class), rule_caseF)); - } - - private static void initialTestCaseF(){ - rule_caseF = new AccessRule(); - rule_caseF.setUuid(UUID.randomUUID()); - rule_caseF.setName("rule_caseF"); - rule_caseF.setRule("$.query"); - rule_caseF.setType(AccessRule.TypeNaming.ANY_CONTAINS); - rule_caseF.setValue("variantInfoFilters"); - rule_caseF.setCheckMapNode(true); - rule_caseF.setCheckMapKeyOnly(true); - Set rule_caseF_subRules = new HashSet<>(); - rule_caseF.setSubAccessRule(rule_caseF_subRules); - - AccessRule rule_caseF_subRule = new AccessRule(); - rule_caseF_subRule.setUuid(UUID.randomUUID()); - rule_caseF_subRule.setName("rule_caseF_subRule"); - rule_caseF_subRule.setRule("$.query.categoryFilters"); - rule_caseF_subRule.setCheckMapNode(true); - rule_caseF_subRule.setCheckMapKeyOnly(true); - rule_caseF_subRule.setType(AccessRule.TypeNaming.ALL_REG_MATCH); - rule_caseF_subRule.setValue("^[0-9]*,[0-9]*,[0-9]*,[ATCG],[ATCG]$"); - rule_caseF_subRules.add(rule_caseF_subRule); - - - AccessRule rule_caseF_subRule_2 = new AccessRule(); - rule_caseF_subRule_2.setUuid(UUID.randomUUID()); - rule_caseF_subRule_2.setName("rule_caseF_subRule_2"); - rule_caseF_subRule_2.setRule("$.query.expectedResultType"); - rule_caseF_subRule_2.setType(AccessRule.TypeNaming.ALL_EQUALS_IGNORE_CASE); - rule_caseF_subRule_2.setValue("COUNT"); - rule_caseF_subRules.add(rule_caseF_subRule_2); - - AccessRule rule_caseF_subRule_3 = new AccessRule(); - rule_caseF_subRule_3.setUuid(UUID.randomUUID()); - rule_caseF_subRule_3.setName("rule_caseF_subRule_3"); - rule_caseF_subRule_3.setRule("$.query.numericFilters"); - rule_caseF_subRule_3.setType(AccessRule.TypeNaming.IS_EMPTY); - rule_caseF_subRules.add(rule_caseF_subRule_3); - - AccessRule rule_caseF_subRule_4 = new AccessRule(); - rule_caseF_subRule_4.setUuid(UUID.randomUUID()); - rule_caseF_subRule_4.setName("rule_caseF_subRule_4"); - rule_caseF_subRule_4.setRule("$.query.requiredFields"); - rule_caseF_subRule_4.setType(AccessRule.TypeNaming.IS_EMPTY); - rule_caseF_subRules.add(rule_caseF_subRule_4); - } - -} diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/PrivilegeServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/PrivilegeServiceTest.java deleted file mode 100644 index 28e206e9..00000000 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/PrivilegeServiceTest.java +++ /dev/null @@ -1,141 +0,0 @@ -package edu.harvard.hms.dbmi.avillach.auth.service; - -import edu.harvard.hms.dbmi.avillach.auth.entity.Privilege; -import edu.harvard.hms.dbmi.avillach.auth.repository.PrivilegeRepository; -import edu.harvard.hms.dbmi.avillach.auth.service.impl.PrivilegeService; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; - -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - -import static edu.harvard.hms.dbmi.avillach.auth.utils.AuthNaming.AuthRoleNaming.ADMIN; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -public class PrivilegeServiceTest { - - @Mock - private PrivilegeRepository privilegeRepository; - - @Mock - private SecurityContext securityContext; - - @Mock - private Authentication authentication; - - @InjectMocks - private PrivilegeService privilegeService; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - SecurityContextHolder.setContext(securityContext); - when(securityContext.getAuthentication()).thenReturn(authentication); - } - - @Test - public void testDeletePrivilegeByPrivilegeId_Success() { - UUID privilegeId = UUID.randomUUID(); - Privilege privilege = new Privilege(); - privilege.setUuid(privilegeId); - privilege.setName("USER_PRIVILEGE"); - - when(privilegeRepository.findById(privilegeId)).thenReturn(Optional.of(privilege)); - when(authentication.getName()).thenReturn("testUser"); - - List privileges = Arrays.asList(new Privilege(), new Privilege()); - when(privilegeRepository.findAll()).thenReturn(privileges); - - List result = privilegeService.deletePrivilegeByPrivilegeId(privilegeId.toString()); - - assertEquals(privileges, result); - verify(privilegeRepository, times(1)).deleteById(privilegeId); - verify(privilegeRepository, times(1)).findAll(); - } - - @Test(expected = RuntimeException.class) - public void testDeletePrivilegeByPrivilegeId_AdminPrivilege() { - UUID privilegeId = UUID.randomUUID(); - Privilege privilege = new Privilege(); - privilege.setUuid(privilegeId); - privilege.setName(ADMIN); - - when(privilegeRepository.findById(privilegeId)).thenReturn(Optional.of(privilege)); - when(authentication.getName()).thenReturn("testUser"); - - privilegeService.deletePrivilegeByPrivilegeId(privilegeId.toString()); - } - - @Test - public void testUpdatePrivileges() { - List privileges = Arrays.asList(new Privilege(), new Privilege()); - - when(privilegeRepository.saveAll(privileges)).thenReturn(privileges); - when(privilegeRepository.findAll()).thenReturn(privileges); - - List result = privilegeService.updatePrivileges(privileges); - - assertEquals(privileges, result); - verify(privilegeRepository, times(1)).saveAll(privileges); - verify(privilegeRepository, times(1)).findAll(); - } - - @Test - public void testAddPrivileges() { - List privileges = Arrays.asList(new Privilege(), new Privilege()); - - when(privilegeRepository.saveAll(privileges)).thenReturn(privileges); - - List result = privilegeService.addPrivileges(privileges); - - assertEquals(privileges, result); - verify(privilegeRepository, times(1)).saveAll(privileges); - } - - @Test - public void testGetPrivilegesAll() { - List privileges = Arrays.asList(new Privilege(), new Privilege()); - - when(privilegeRepository.findAll()).thenReturn(privileges); - - List result = privilegeService.getPrivilegesAll(); - - assertEquals(privileges, result); - verify(privilegeRepository, times(1)).findAll(); - } - - @Test - public void testGetPrivilegeById_Found() { - UUID privilegeId = UUID.randomUUID(); - Privilege privilege = new Privilege(); - privilege.setUuid(privilegeId); - - when(privilegeRepository.findById(privilegeId)).thenReturn(Optional.of(privilege)); - - Privilege result = privilegeService.getPrivilegeById(privilegeId.toString()); - - assertEquals(privilege, result); - verify(privilegeRepository, times(1)).findById(privilegeId); - } - - @Test - public void testGetPrivilegeById_NotFound() { - UUID privilegeId = UUID.randomUUID(); - - when(privilegeRepository.findById(privilegeId)).thenReturn(Optional.empty()); - - Privilege result = privilegeService.getPrivilegeById(privilegeId.toString()); - - assertNull(result); - verify(privilegeRepository, times(1)).findById(privilegeId); - } -} diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/RoleServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/RoleServiceTest.java index 8788198d..25843906 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/RoleServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/RoleServiceTest.java @@ -7,44 +7,55 @@ import edu.harvard.hms.dbmi.avillach.auth.model.CustomUserDetails; import edu.harvard.hms.dbmi.avillach.auth.repository.PrivilegeRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.RoleRepository; +import edu.harvard.hms.dbmi.avillach.auth.service.impl.PrivilegeService; import edu.harvard.hms.dbmi.avillach.auth.service.impl.RoleService; -import edu.harvard.hms.dbmi.avillach.auth.utils.AuthNaming; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import edu.harvard.hms.dbmi.avillach.auth.utils.FenceMappingUtility; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ContextConfiguration; import java.util.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +@SpringBootTest +@ContextConfiguration(classes = {RoleService.class}) public class RoleServiceTest { - @Mock + @MockBean private RoleRepository roleRepository; - @Mock + @MockBean private PrivilegeRepository privilegeRepo; - @Mock + @MockBean + private PrivilegeService privilegeService; + + @MockBean + private FenceMappingUtility fenceMappingUtility; + + @MockBean private SecurityContext securityContext; - @Mock + @MockBean private Authentication authentication; - @InjectMocks + @Autowired private RoleService roleService; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); SecurityContextHolder.setContext(securityContext); when(securityContext.getAuthentication()).thenReturn(authentication); } @@ -103,7 +114,7 @@ public void testAddRoles() { verify(roleRepository, times(1)).saveAll(roles); } - @Test(expected = RuntimeException.class) + @Test public void testAddRoles_PrivilegeNotFound() { Role role = new Role(); Privilege privilege = new Privilege(); @@ -112,7 +123,9 @@ public void testAddRoles_PrivilegeNotFound() { when(privilegeRepo.findById(privilege.getUuid())).thenReturn(Optional.empty()); - roleService.addRoles(Collections.singletonList(role)); + assertThrows(RuntimeException.class, ()-> { + roleService.addRoles(Collections.singletonList(role)); + }); } @Test @@ -127,7 +140,7 @@ public void testUpdateRoles() { verify(roleRepository, times(1)).saveAll(roles); } - @Test(expected = RuntimeException.class) + @Test public void testUpdateRoles_PrivilegeNotFound() { Role role = new Role(); Privilege privilege = new Privilege(); @@ -136,7 +149,9 @@ public void testUpdateRoles_PrivilegeNotFound() { when(privilegeRepo.findById(privilege.getUuid())).thenReturn(Optional.empty()); - roleService.updateRoles(Collections.singletonList(role)); + assertThrows(RuntimeException.class, ()->{ + roleService.updateRoles(Collections.singletonList(role)); + }); } @Test @@ -201,7 +216,7 @@ public void testAddObjectToSet_RoleExists() { assertTrue(roles.contains(role)); } - @Test(expected = RuntimeException.class) + @Test public void testAddObjectToSet_RoleNotFound() { Set roles = new HashSet<>(); Role role = new Role(); @@ -209,7 +224,9 @@ public void testAddObjectToSet_RoleNotFound() { when(roleRepository.findById(role.getUuid())).thenReturn(Optional.empty()); - roleService.addObjectToSet(roles, role); + assertThrows(RuntimeException.class, () -> { + roleService.addObjectToSet(roles, role); + }); } private Role createTopAdminRole() { diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AccessRuleServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AccessRuleServiceTest.java index 0bef2c08..d7eec767 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AccessRuleServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AccessRuleServiceTest.java @@ -2,36 +2,34 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.AccessRule; import edu.harvard.hms.dbmi.avillach.auth.repository.AccessRuleRepository; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.ContextConfiguration; import java.util.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; +@SpringBootTest +@ContextConfiguration(classes = {AccessRuleService.class}) public class AccessRuleServiceTest { - @Mock + @MockBean private AccessRuleRepository accessRuleRepo; - @InjectMocks + @Autowired private AccessRuleService accessRuleService; - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @After - public void tearDown() throws Exception { + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); } @Test @@ -42,7 +40,7 @@ public void testGetAccessRuleById_found() { Optional result = accessRuleService.getAccessRuleById(id.toString()); assertTrue(result.isPresent()); - Assert.assertSame(accessRule, result.get()); + assertSame(accessRule, result.get()); } @Test diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/ApplicationServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/ApplicationServiceTest.java index 670e24a2..3a161989 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/ApplicationServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/ApplicationServiceTest.java @@ -5,35 +5,39 @@ import edu.harvard.hms.dbmi.avillach.auth.repository.ApplicationRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.PrivilegeRepository; import edu.harvard.hms.dbmi.avillach.auth.utils.JWTUtil; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.ContextConfiguration; import java.util.*; -import static org.mockito.ArgumentMatchers.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; -import static org.junit.Assert.*; +@SpringBootTest +@ContextConfiguration(classes = {ApplicationService.class}) public class ApplicationServiceTest { - @Mock + @MockBean private ApplicationRepository applicationRepo; - @Mock + @MockBean private PrivilegeRepository privilegeRepo; - @Mock + @MockBean private JWTUtil jwtUtil; - @InjectMocks + @Autowired private ApplicationService applicationService; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test @@ -67,7 +71,7 @@ public void testGetApplicationByIdWithPrivileges_foundWithPrivileges() { Optional result = applicationService.getApplicationByIdWithPrivileges(id.toString()); assertTrue(result.isPresent()); - assertNotNull(result.get().getPrivileges()); + Assertions.assertNotNull(result.get().getPrivileges()); } @Test @@ -120,12 +124,14 @@ public void testDeleteApplicationById_existing() { assertNotNull(remainingApps); } - @Test(expected = IllegalArgumentException.class) + @Test public void testDeleteApplicationById_notFound() { UUID id = UUID.randomUUID(); when(applicationRepo.findById(id)).thenReturn(Optional.empty()); - applicationService.deleteApplicationById(id.toString()); + assertThrows(IllegalArgumentException.class, () -> { + applicationService.deleteApplicationById(id.toString()); + }); } @Test @@ -136,8 +142,8 @@ public void testUpdateApplications() { when(applicationRepo.saveAll(anyList())).thenReturn(applications); List updatedApps = applicationService.updateApplications(applications); - assertNotNull(updatedApps); - assertEquals(applications.size(), updatedApps.size()); + Assertions.assertNotNull(updatedApps); + Assertions.assertEquals(applications.size(), updatedApps.size()); } @Test @@ -153,15 +159,17 @@ public void testRefreshApplicationToken_successful() { assertEquals("newToken", token); } - @Test(expected = IllegalArgumentException.class) + @Test public void testRefreshApplicationToken_notFound() { UUID id = UUID.randomUUID(); when(applicationRepo.findById(id)).thenReturn(Optional.empty()); - applicationService.refreshApplicationToken(id.toString()); + assertThrows(IllegalArgumentException.class, () -> { + applicationService.refreshApplicationToken(id.toString()); + }); } - @Test(expected = NullPointerException.class) + @Test public void testRefreshApplicationToken_failedToGenerateToken() { UUID id = UUID.randomUUID(); Application application = new Application(); @@ -169,6 +177,9 @@ public void testRefreshApplicationToken_failedToGenerateToken() { when(applicationRepo.findById(id)).thenReturn(Optional.of(application)); when(jwtUtil.createJwtToken(any(), any(), any(), anyString(), anyLong())).thenReturn(null); - applicationService.refreshApplicationToken(id.toString()); + + assertThrows(NullPointerException.class, () -> { + applicationService.refreshApplicationToken(id.toString()); + }); } } diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/Auth0MatchingServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/Auth0MatchingServiceTest.java index 1772c8db..aa30b125 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/Auth0MatchingServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/Auth0MatchingServiceTest.java @@ -8,13 +8,15 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.UserMetadataMapping; import edu.harvard.hms.dbmi.avillach.auth.repository.ConnectionRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.UserRepository; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.ContextConfiguration; import java.io.IOException; import java.util.List; @@ -22,38 +24,37 @@ import java.util.Optional; import java.util.stream.Collectors; -import static junit.framework.TestCase.assertNotNull; -import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doAnswer; +@SpringBootTest +@ContextConfiguration(classes = {OauthUserMatchingService.class}) public class Auth0MatchingServiceTest { private static final Logger log = LoggerFactory.getLogger(Auth0MatchingServiceTest.class); - @Mock - UserRepository userRepo; + @MockBean + private UserRepository userRepo; - @Mock - UserMetadataMappingService mappingService; + @MockBean + private UserMetadataMappingService mappingService; - @Mock - UserService userService; + @MockBean + private UserService userService; - @Mock - ConnectionRepository connectionRepo; + @MockBean + private ConnectionRepository connectionRepo; - @InjectMocks - OauthUserMatchingService cut; + @Autowired + private OauthUserMatchingService cut; - User persistedUser; - ObjectMapper mapper = new ObjectMapper(); + private User persistedUser; + private final ObjectMapper mapper = new ObjectMapper(); - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); //Instead of calling the database doAnswer(invocation -> (listUnmatchedByConnectionIdMock(invocation.getArgument(0)))). when(userRepo).findByConnectionAndMatched(any(Connection.class), anyBoolean()); diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AuthenticationServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AuthenticationServiceTest.java index 621b50de..87a7aa54 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AuthenticationServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AuthenticationServiceTest.java @@ -8,13 +8,15 @@ import edu.harvard.hms.dbmi.avillach.auth.repository.UserRepository; import edu.harvard.hms.dbmi.avillach.auth.service.impl.authentication.Auth0AuthenticationService; import edu.harvard.hms.dbmi.avillach.auth.utils.RestClientUtil; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; import java.io.IOException; import java.util.HashMap; @@ -22,27 +24,28 @@ import java.util.Optional; import java.util.UUID; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; +@SpringBootTest +@ContextConfiguration(classes = {Auth0AuthenticationService.class}) public class AuthenticationServiceTest { - @Mock + @MockBean private OauthUserMatchingService matchingService; - @Mock + @MockBean private UserRepository userRepository; - @Mock + @MockBean private BasicMailService basicMailService; - @Mock + @MockBean private UserService userService; - @Mock + @MockBean private ConnectionRepository connectionRepository; - @Mock + @MockBean private RestClientUtil restClientUtil; - @Mock + @MockBean private CacheEvictionService cacheEvictionService; private Auth0AuthenticationService authenticationService; @@ -53,9 +56,9 @@ public class AuthenticationServiceTest { private final String connectionId = "conn123"; private Map authRequest; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); authRequest = new HashMap<>(); authRequest.put("access_token", accessToken); authRequest.put("redirectURI", redirectURI); @@ -64,25 +67,33 @@ public void setUp() { } // Tests missing parameters in the authentication request - @Test(expected = IllegalArgumentException.class) + @Test public void testGetToken_MissingParameters() throws IOException { - authenticationService.authenticate(new HashMap<>(), "localhost"); // Empty map should trigger the exception + assertThrows(IllegalArgumentException.class, () -> { + authenticationService.authenticate(new HashMap<>(), "localhost"); // Empty map should trigger the exception + }); } // Tests the failure in retrieving user information, expecting an IOException to be converted into a NotAuthorizedException - @Test(expected = NotAuthorizedException.class) + @Test public void testGetToken_UserInfoRetrievalFails() throws IOException { when(this.restClientUtil.retrieveGetResponseWithRequestConfiguration(anyString(), any(HttpHeaders.class), anyInt())) .thenThrow(new NotAuthorizedException("Failed to retrieve user info")); - authenticationService.authenticate(authRequest, "localhost"); + + assertThrows(NotAuthorizedException.class, () -> { + authenticationService.authenticate(authRequest, "localhost"); + }); } // Tests the scenario where the user ID is not found in the user info retrieved - @Test(expected = NotAuthorizedException.class) + @Test public void testGetToken_NoUserIdInUserInfo() throws IOException { when(this.restClientUtil.retrieveGetResponseWithRequestConfiguration(anyString(), any(), anyInt())) .thenReturn(new ResponseEntity<>("{}", HttpStatus.OK)); - authenticationService.authenticate(authRequest, "localhost"); + + assertThrows(NotAuthorizedException.class, () -> { + authenticationService.authenticate(authRequest, "localhost"); + }); } // Tests a successful token retrieval scenario @@ -109,10 +120,13 @@ public void testRetrieveUserInfo_WithRetries() throws Exception { } // Tests matching a token to a user when no existing user is found and an attempt to create a user fails - @Test(expected = NotAuthorizedException.class) + @Test public void testGetToken_NoUserMatchingAndCreationFails() throws Exception { setupNoUserMatchScenario(); - authenticationService.authenticate(authRequest, "localhost"); + + assertThrows(NotAuthorizedException.class, () -> { + authenticationService.authenticate(authRequest, "localhost"); + }); } // Test scenario where denied access email is triggered diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AuthorizationServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AuthorizationServiceTest.java index 19381278..3e7a089d 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AuthorizationServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/AuthorizationServiceTest.java @@ -6,39 +6,44 @@ import edu.harvard.hms.dbmi.avillach.auth.repository.AccessRuleRepository; import edu.harvard.hms.dbmi.avillach.auth.service.impl.authorization.AuthorizationService; import edu.harvard.hms.dbmi.avillach.auth.utils.AuthNaming; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ContextConfiguration; import java.util.*; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; +@SpringBootTest +@ContextConfiguration(classes = {AuthorizationService.class, AccessRuleService.class}) public class AuthorizationServiceTest { - @Mock + @MockBean private SecurityContext securityContext; private AuthorizationService authorizationService; private AccessRuleService accessRuleService; - @Mock + @MockBean private SessionService sessionService; - @Mock + @MockBean private AccessRuleRepository accessRuleRepository; - @Mock + @MockBean private RoleService roleService; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); SecurityContextHolder.setContext(securityContext); accessRuleService = new AccessRuleService(accessRuleRepository, "false", "false", "false", "false","false", "false"); diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/BasicMailServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/BasicMailServiceTest.java index bca3917e..2eac91e5 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/BasicMailServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/BasicMailServiceTest.java @@ -5,30 +5,31 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.User; import jakarta.mail.MessagingException; import jakarta.mail.internet.MimeMessage; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.test.context.ContextConfiguration; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +@SpringBootTest +@ContextConfiguration(classes = {BasicMailService.class}) public class BasicMailServiceTest { - @Mock + @MockBean private JavaMailSender mailSender; - @Mock + @MockBean private Mustache accessTemplate; - @Mock - private Mustache deniedTemplate; - - @InjectMocks + @Autowired private BasicMailService basicMailService; @Value("${application.template.path}") @@ -43,9 +44,9 @@ public class BasicMailServiceTest { @Value("${application.admin.users}") private String adminUsers = "admin@test.com"; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); basicMailService = new BasicMailService(mailSender, templatePath, systemName, accessGrantEmailSubject, adminUsers); } diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/CacheTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/CacheTest.java new file mode 100644 index 00000000..d57619e9 --- /dev/null +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/CacheTest.java @@ -0,0 +1,247 @@ +package edu.harvard.hms.dbmi.avillach.auth.service.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import edu.harvard.hms.dbmi.avillach.auth.config.CustomKeyGenerator; +import edu.harvard.hms.dbmi.avillach.auth.entity.Application; +import edu.harvard.hms.dbmi.avillach.auth.entity.Privilege; +import edu.harvard.hms.dbmi.avillach.auth.entity.User; +import edu.harvard.hms.dbmi.avillach.auth.repository.AccessRuleRepository; +import edu.harvard.hms.dbmi.avillach.auth.repository.ApplicationRepository; +import edu.harvard.hms.dbmi.avillach.auth.repository.ConnectionRepository; +import edu.harvard.hms.dbmi.avillach.auth.repository.UserRepository; +import edu.harvard.hms.dbmi.avillach.auth.utils.JWTUtil; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.*; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ContextConfiguration; + +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + +@SpringBootTest +@ExtendWith(MockitoExtension.class) +@ContextConfiguration(classes = { + UserService.class, + AccessRuleService.class, + CustomKeyGenerator.class, + CacheEvictionService.class + +}) +@Import(CacheTest.TestCacheConfig.class) +public class CacheTest { + + @MockBean + private AccessRuleRepository accessRuleRepository; + + @MockBean + private BasicMailService basicMailService; + + @MockBean + private TOSService tosService; + + @MockBean + private UserRepository userRepository; + + @MockBean + private ConnectionRepository connectionRepository; + + @MockBean + private ApplicationRepository applicationRepository; + + @MockBean + private RoleService roleService; + + @MockBean + private JWTUtil jwtUtil; + + @MockBean + private SessionService sessionService; + + @Autowired + private AccessRuleService accessRuleService; + + @Autowired + private UserService userService; + + @Autowired + private CacheEvictionService cacheEvictionService; + + @Autowired + private CacheManager cacheManager; + + @Mock + private User mockUser; + + @Mock + private Application mockApplication; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + Objects.requireNonNull(cacheManager.getCache("mergedRulesCache")).clear(); + Objects.requireNonNull(cacheManager.getCache("preProcessedAccessRules")).clear(); + Objects.requireNonNull(cacheManager.getCache("mergedTemplateCache")).clear(); + } + + @Test + public void testMergedRulesCache() throws JsonProcessingException { + Set mockPrivileges = new HashSet<>(); + when(mockUser.getSubject()).thenReturn("test_subject"); + when(mockUser.getPrivilegesByApplication(mockApplication)).thenReturn(mockPrivileges); + + // First call to the method - should execute the method logic and add the AccessRule set + accessRuleService.getAccessRulesForUserAndApp(mockUser, mockApplication); + verify(mockUser, times(1)).getPrivilegesByApplication(mockApplication); + + // Second call to the method with the same arguments - should hit the cache + accessRuleService.getAccessRulesForUserAndApp(mockUser, mockApplication); + verify(mockUser, times(1)).getPrivilegesByApplication(mockApplication); + } + + @Test + public void testMergedRulesCacheEvict() { + Cache cache = cacheManager.getCache("mergedRulesCache"); + + // Call the method to store the result in the cache + Set mockPrivileges = new HashSet<>(); + when(mockUser.getSubject()).thenReturn("test_subject"); + when(mockUser.getPrivilegesByApplication(mockApplication)).thenReturn(mockPrivileges); + + // First call to the method - should execute the method logic and add the AccessRule set + accessRuleService.getAccessRulesForUserAndApp(mockUser, mockApplication); + assertThat(cache.get("test_subject")).isNotNull(); + + // Evict the test_subject from the cache + accessRuleService.evictFromMergedAccessRuleCache("test_subject"); + assertThat(cache.get("test_subject")).isNull(); + } + + @Test + public void testCachedPreProcessAccessRules() { + when(mockUser.getSubject()).thenReturn("test_subject"); + Set mockedPrivileges = new HashSet<>(); + accessRuleService.cachedPreProcessAccessRules(mockUser, mockedPrivileges); + + Cache preProcessedAccessRules = cacheManager.getCache("preProcessedAccessRules"); + assertThat(preProcessedAccessRules).isNotNull(); + + // Verify the cache contains test_subject cache entry + assertThat(preProcessedAccessRules.get("test_subject")).isNotNull(); + } + + @Test + public void testCacheEvictPreProcessAccessRules() { + when(mockUser.getSubject()).thenReturn("test_subject"); + + Set mockedPrivileges = new HashSet<>(); + accessRuleService.cachedPreProcessAccessRules(mockUser, mockedPrivileges); + + Cache preProcessedAccessRules = cacheManager.getCache("preProcessedAccessRules"); + assertThat(preProcessedAccessRules).isNotNull(); + + // Verify the cache contains test_subject cache entry + assertThat(preProcessedAccessRules.get("test_subject")).isNotNull(); + + accessRuleService.evictFromPreProcessedAccessRules("test_subject"); + assertThat(preProcessedAccessRules.get("test_subject")).isNull(); + } + + @Test + public void testMergedTemplateCache() { + when(mockUser.getSubject()).thenReturn("test_subject"); + + Set mockPrivileges = new HashSet<>(); + when(mockUser.getPrivilegesByApplication(mockApplication)).thenReturn(mockPrivileges); + + // First call to the method - should execute the method logic and add the mergeTemplate + userService.mergeTemplate(mockUser, mockApplication); + verify(mockUser, times(1)).getPrivilegesByApplication(mockApplication); + + // Second call to the method - should be handled by the cache and getPrivilegesByApplication should not be called again + userService.mergeTemplate(mockUser, mockApplication); + verify(mockUser, times(1)).getPrivilegesByApplication(mockApplication); + } + + @Test + public void testCacheEvictMergedTemplateCache() { + when(mockUser.getSubject()).thenReturn("test_subject"); + + Set mockPrivileges = new HashSet<>(); + when(mockUser.getPrivilegesByApplication(mockApplication)).thenReturn(mockPrivileges); + + // First call to the method - should execute the method logic and add the mergeTemplate + userService.mergeTemplate(mockUser, mockApplication); + verify(mockUser, times(1)).getPrivilegesByApplication(mockApplication); + + Cache cache = cacheManager.getCache("mergedTemplateCache"); + assertThat(cache.get("test_subject")).isNotNull(); + + userService.evictFromCache("test_subject"); + assertThat(cache.get("test_subject")).isNull(); + } + + @Test + public void testCacheEvictionService() { + when(mockUser.getSubject()).thenReturn("test_subject"); + Set mockPrivileges = new HashSet<>(); + + when(mockUser.getPrivilegesByApplication(mockApplication)).thenReturn(mockPrivileges); + + // Initialize mergedTemplateCache + userService.mergeTemplate(mockUser, mockApplication); + + // Verify the cache contains mergedTemplateCache has test_subject + Cache mergedTemplateCache = cacheManager.getCache("mergedTemplateCache"); + assertThat(mergedTemplateCache.get("test_subject")).isNotNull(); + + // Initialize preProcessedAccessRules + when(mockUser.getSubject()).thenReturn("test_subject"); + accessRuleService.cachedPreProcessAccessRules(mockUser, mockPrivileges); + Cache preProcessedAccessRules = cacheManager.getCache("preProcessedAccessRules"); + + // Verify the cache contains test_subject cache entry + assertThat(preProcessedAccessRules).isNotNull(); + assertThat(preProcessedAccessRules.get("test_subject")).isNotNull(); + + when(mockUser.getSubject()).thenReturn("test_subject"); + when(mockUser.getPrivilegesByApplication(mockApplication)).thenReturn(mockPrivileges); + + // First call to the method - should execute the method logic and add the AccessRule set + accessRuleService.getAccessRulesForUserAndApp(mockUser, mockApplication); + Cache mergedRulesCache = cacheManager.getCache("mergedRulesCache"); + assertThat(mergedRulesCache).isNotNull(); + assertThat(mergedRulesCache.get("test_subject")).isNotNull(); + + cacheEvictionService.evictCache(mockUser); + assertThat(mergedRulesCache.get("test_subject")).isNull(); + assertThat(preProcessedAccessRules.get("test_subject")).isNull(); + assertThat(mergedTemplateCache.get("test_subject")).isNull(); + } + + @Configuration + @EnableCaching + public static class TestCacheConfig { + + @Bean + public CacheManager cacheManager() { + return new ConcurrentMapCacheManager("mergedRulesCache", "preProcessedAccessRules", "mergedTemplateCache"); + } + } + +} diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/ConnectionWebServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/ConnectionWebServiceTest.java index b1a0f108..2d7536b4 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/ConnectionWebServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/ConnectionWebServiceTest.java @@ -2,29 +2,34 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.Connection; import edu.harvard.hms.dbmi.avillach.auth.repository.ConnectionRepository; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.ContextConfiguration; import java.util.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; +@SpringBootTest +@ContextConfiguration(classes = {ConnectionWebService.class}) public class ConnectionWebServiceTest { - @Mock + @MockBean private ConnectionRepository connectionRepo; - @InjectMocks + @Autowired private ConnectionWebService service; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } private Connection createMockConnection(String id) { diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/CustomUserDetailServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/CustomUserDetailServiceTest.java index d933088d..f336ebc0 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/CustomUserDetailServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/CustomUserDetailServiceTest.java @@ -7,34 +7,38 @@ import edu.harvard.hms.dbmi.avillach.auth.enums.SecurityRoles; import edu.harvard.hms.dbmi.avillach.auth.model.CustomApplicationDetails; import edu.harvard.hms.dbmi.avillach.auth.model.CustomUserDetails; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.test.context.ContextConfiguration; import java.util.Optional; import java.util.Set; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; +@SpringBootTest +@ContextConfiguration(classes = {CustomUserDetailService.class}) public class CustomUserDetailServiceTest { - @Mock + @MockBean private UserService userService; - @Mock + @MockBean private ApplicationService applicationService; - @InjectMocks + @Autowired private CustomUserDetailService customUserDetailService; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test @@ -46,7 +50,7 @@ public void loadUserByUsername_withApplication_success() { UserDetails userDetails = customUserDetailService.loadUserByUsername("application:" + applicationName); assertNotNull(userDetails); - assertTrue(userDetails instanceof CustomApplicationDetails); + assertInstanceOf(CustomApplicationDetails.class, userDetails); } @Test @@ -74,7 +78,7 @@ public void loadUserByUsername_withUser_success() { UserDetails userDetails = customUserDetailService.loadUserByUsername(username); assertNotNull(userDetails); - assertTrue(userDetails instanceof CustomUserDetails); + assertInstanceOf(CustomUserDetails.class, userDetails); } @Test diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/PrivilegeServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/PrivilegeServiceTest.java index 5074112f..9c95e5e4 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/PrivilegeServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/PrivilegeServiceTest.java @@ -2,14 +2,16 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.Privilege; import edu.harvard.hms.dbmi.avillach.auth.repository.PrivilegeRepository; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ContextConfiguration; import java.util.Arrays; import java.util.List; @@ -17,26 +19,34 @@ import java.util.UUID; import static edu.harvard.hms.dbmi.avillach.auth.utils.AuthNaming.AuthRoleNaming.ADMIN; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; +@SpringBootTest +@ContextConfiguration(classes = {PrivilegeService.class}) public class PrivilegeServiceTest { - @Mock + @MockBean private PrivilegeRepository privilegeRepository; - @Mock + @MockBean private SecurityContext securityContext; - @Mock + @MockBean private Authentication authentication; - @InjectMocks + @MockBean + private ApplicationService applicationService; + + @MockBean + private AccessRuleService accessRuleService; + + @Autowired private PrivilegeService privilegeService; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); SecurityContextHolder.setContext(securityContext); when(securityContext.getAuthentication()).thenReturn(authentication); } @@ -58,10 +68,10 @@ public void testDeletePrivilegeByPrivilegeId_Success() { assertEquals(privileges, result); verify(privilegeRepository, times(1)).deleteById(privilegeId); - verify(privilegeRepository, times(1)).findAll(); + verify(privilegeRepository, times(2)).findAll(); } - @Test(expected = RuntimeException.class) + @Test public void testDeletePrivilegeByPrivilegeId_AdminPrivilege() { UUID privilegeId = UUID.randomUUID(); Privilege privilege = new Privilege(); @@ -71,7 +81,9 @@ public void testDeletePrivilegeByPrivilegeId_AdminPrivilege() { when(privilegeRepository.findById(privilegeId)).thenReturn(Optional.of(privilege)); when(authentication.getName()).thenReturn("testUser"); - privilegeService.deletePrivilegeByPrivilegeId(privilegeId.toString()); + assertThrows(RuntimeException.class, () -> { + privilegeService.deletePrivilegeByPrivilegeId(privilegeId.toString()); + }); } @Test diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/RASPassPortServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/RASPassPortServiceTest.java index 091f55c1..af68ecdf 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/RASPassPortServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/RASPassPortServiceTest.java @@ -5,35 +5,40 @@ import edu.harvard.hms.dbmi.avillach.auth.model.ras.RasDbgapPermission; import edu.harvard.hms.dbmi.avillach.auth.utils.JWTUtil; import edu.harvard.hms.dbmi.avillach.auth.utils.RestClientUtil; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; import java.util.Optional; import java.util.Set; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) +@SpringBootTest +@ContextConfiguration(classes = {RASPassPortService.class}) public class RASPassPortServiceTest { - @Mock + @MockBean private RestClientUtil restClientUtil; - @Mock + @MockBean private CacheEvictionService cacheEvictionService; + @MockBean + private UserService userService; private RASPassPortService rasPassPortService; private String visa; - @Before + @BeforeEach public void setUp() throws Exception { this.rasPassPortService = new RASPassPortService(restClientUtil, null, "https://test.com/", cacheEvictionService); diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/RoleServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/RoleServiceTest.java index 500aaea9..ddd6a311 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/RoleServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/RoleServiceTest.java @@ -9,42 +9,59 @@ import edu.harvard.hms.dbmi.avillach.auth.repository.PrivilegeRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.RoleRepository; import edu.harvard.hms.dbmi.avillach.auth.utils.AuthNaming; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import edu.harvard.hms.dbmi.avillach.auth.utils.FenceMappingUtility; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ContextConfiguration; import java.util.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; +@SpringBootTest +@ContextConfiguration(classes = {RoleService.class, PrivilegeService.class}) public class RoleServiceTest { - @Mock + @MockBean + private ApplicationService applicationService; + + @MockBean + private AccessRuleService accessRuleService; + + @MockBean private RoleRepository roleRepository; - @Mock + @MockBean private PrivilegeRepository privilegeRepo; - @Mock + @MockBean private SecurityContext securityContext; - @Mock + @MockBean private Authentication authentication; - @InjectMocks + @MockBean + private FenceMappingUtility fenceMappingUtility; + + @Autowired private RoleService roleService; - @Before + @Autowired + private PrivilegeService privilegeService; + + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); SecurityContextHolder.setContext(securityContext); when(securityContext.getAuthentication()).thenReturn(authentication); } @@ -103,7 +120,7 @@ public void testAddRoles() { verify(roleRepository, times(1)).saveAll(roles); } - @Test(expected = RuntimeException.class) + @Test public void testAddRoles_PrivilegeNotFound() { Role role = new Role(); Privilege privilege = new Privilege(); @@ -112,7 +129,9 @@ public void testAddRoles_PrivilegeNotFound() { when(privilegeRepo.findById(privilege.getUuid())).thenReturn(Optional.empty()); - roleService.addRoles(Collections.singletonList(role)); + assertThrows(RuntimeException.class, () -> { + roleService.addRoles(Collections.singletonList(role)); + }); } @Test @@ -127,7 +146,7 @@ public void testUpdateRoles() { verify(roleRepository, times(1)).saveAll(roles); } - @Test(expected = RuntimeException.class) + @Test public void testUpdateRoles_PrivilegeNotFound() { Role role = new Role(); Privilege privilege = new Privilege(); @@ -136,7 +155,9 @@ public void testUpdateRoles_PrivilegeNotFound() { when(privilegeRepo.findById(privilege.getUuid())).thenReturn(Optional.empty()); - roleService.updateRoles(Collections.singletonList(role)); + assertThrows(RuntimeException.class, () -> { + roleService.updateRoles(Collections.singletonList(role)); + }); } @Test @@ -201,15 +222,16 @@ public void testAddObjectToSet_RoleExists() { assertTrue(roles.contains(role)); } - @Test(expected = RuntimeException.class) + @Test public void testAddObjectToSet_RoleNotFound() { Set roles = new HashSet<>(); Role role = new Role(); role.setUuid(UUID.randomUUID()); when(roleRepository.findById(role.getUuid())).thenReturn(Optional.empty()); - - roleService.addObjectToSet(roles, role); + assertThrows(RuntimeException.class, () -> { + roleService.addObjectToSet(roles, role); + }); } private Role createTopAdminRole() { diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/StudyAccessServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/StudyAccessServiceTest.java index 2c219c91..88cef9f8 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/StudyAccessServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/StudyAccessServiceTest.java @@ -1,33 +1,36 @@ package edu.harvard.hms.dbmi.avillach.auth.service.impl; import edu.harvard.hms.dbmi.avillach.auth.model.fenceMapping.StudyMetaData; -import edu.harvard.hms.dbmi.avillach.auth.service.impl.authentication.FENCEAuthenticationService; import edu.harvard.hms.dbmi.avillach.auth.utils.FenceMappingUtility; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.ContextConfiguration; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; +@SpringBootTest +@ContextConfiguration(classes = {StudyAccessService.class}) public class StudyAccessServiceTest { - @InjectMocks + @Autowired private StudyAccessService studyAccessService; - @Mock + @MockBean private RoleService roleService; - @Mock + @MockBean private FenceMappingUtility fenceMappingUtility; - @Before + @BeforeEach public void init() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/TOSServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/TOSServiceTest.java index b4c2ad82..3a18133f 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/TOSServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/TOSServiceTest.java @@ -4,34 +4,37 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.User; import edu.harvard.hms.dbmi.avillach.auth.repository.TermsOfServiceRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.UserRepository; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.ContextConfiguration; import java.util.Date; import java.util.Optional; import java.util.UUID; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; +@SpringBootTest +@ContextConfiguration(classes = {TOSService.class}) public class TOSServiceTest { - @Mock + @MockBean private TermsOfServiceRepository termsOfServiceRepo; - @Mock + @MockBean private UserRepository userRepo; private TOSService tosService; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); tosService = new TOSService(termsOfServiceRepo, userRepo, true); } @@ -133,14 +136,16 @@ public void testAcceptTermsOfService_UserExists() { assertNotNull(result.getAcceptedTOS()); } - @Test(expected = RuntimeException.class) + @Test public void testAcceptTermsOfService_UserDoesNotExist() { when(userRepo.findBySubject(anyString())).thenReturn(null); - tosService.acceptTermsOfService("user-id"); + assertThrows(RuntimeException.class, ()->{ + tosService.acceptTermsOfService("user-id"); + }); } - @Test(expected = RuntimeException.class) + @Test public void testAcceptTermsOfService_NoTOSInDatabase() { User user = new User(); user.setSubject("user-id"); @@ -148,7 +153,9 @@ public void testAcceptTermsOfService_NoTOSInDatabase() { when(userRepo.findBySubject(anyString())).thenReturn(user); when(termsOfServiceRepo.findTopByOrderByDateUpdatedDesc()).thenReturn(Optional.empty()); - tosService.acceptTermsOfService("user-id"); + assertThrows(RuntimeException.class, () -> { + tosService.acceptTermsOfService("user-id"); + }); } @Test diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/TokenServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/TokenServiceTest.java index b26d73b5..be5dd6a6 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/TokenServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/TokenServiceTest.java @@ -5,53 +5,56 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.Role; import edu.harvard.hms.dbmi.avillach.auth.entity.User; import edu.harvard.hms.dbmi.avillach.auth.enums.SecurityRoles; -import edu.harvard.hms.dbmi.avillach.auth.exceptions.NotAuthorizedException; import edu.harvard.hms.dbmi.avillach.auth.model.*; import edu.harvard.hms.dbmi.avillach.auth.repository.UserRepository; import edu.harvard.hms.dbmi.avillach.auth.service.impl.authorization.AuthorizationService; import edu.harvard.hms.dbmi.avillach.auth.utils.AuthNaming; import edu.harvard.hms.dbmi.avillach.auth.utils.JWTUtil; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.test.context.ContextConfiguration; import java.security.SecureRandom; import java.util.*; -import static org.junit.Assert.*; +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; +@SpringBootTest +@ContextConfiguration(classes = {TokenService.class, JWTUtil.class}) public class TokenServiceTest { - @Mock + @MockBean private AuthorizationService authorizationService; - @Mock + @MockBean private UserRepository userRepository; - @Mock + @MockBean private SessionService sessionService; private JWTUtil jwtUtil; - @Mock + @MockBean private SecurityContext securityContext; private TokenService tokenService; private static final long testTokenExpiration = 1000L * 60 * 60; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); Authentication authentication = mock(Authentication.class); SecurityContextHolder.setContext(securityContext); @@ -108,7 +111,7 @@ public void testInspectToken_withEmptyToken() { assertEquals("Token not found", response.get("message")); } - @Test(expected = RuntimeException.class) + @Test public void testInspectToken_withUserPrincipal() { User user = createTestUser(); Map claims = new HashMap<>(); @@ -125,8 +128,11 @@ public void testInspectToken_withUserPrincipal() { inputMap.put("token", token); configureUserSecurityContext(user); - Map tokenInspection = tokenService.inspectToken(inputMap); - assertNotNull(tokenInspection.get("message")); + + assertThrows(RuntimeException.class, () -> { + Map tokenInspection = tokenService.inspectToken(inputMap); + assertNotNull(tokenInspection.get("message")); + }); } @@ -156,7 +162,7 @@ public void testInspectToken_withValidToken_withNoAssociatedUser() { assertEquals("user doesn't exist", response.get("message")); } - @Test(expected = NullPointerException.class) + @Test public void testInspectToken_withNoApplicationInSecurityContext() { configureApplicationSecurityContext(null); @@ -176,7 +182,9 @@ public void testInspectToken_withNoApplicationInSecurityContext() { inputMap.put("token", token); when(userRepository.findBySubject(user.getSubject())).thenReturn(null); - tokenService.inspectToken(inputMap); + assertThrows(NullPointerException.class, ()->{ + tokenService.inspectToken(inputMap); + }); } /* diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/UserMetadataMappingServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/UserMetadataMappingServiceTest.java index 6f380f7b..b9611e8d 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/UserMetadataMappingServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/UserMetadataMappingServiceTest.java @@ -4,34 +4,39 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.UserMetadataMapping; import edu.harvard.hms.dbmi.avillach.auth.repository.ConnectionRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.UserMetadataMappingRepository; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.ContextConfiguration; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.UUID; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*; +@SpringBootTest +@ContextConfiguration(classes = {UserMetadataMappingService.class}) public class UserMetadataMappingServiceTest { - @Mock + @MockBean private UserMetadataMappingRepository userMetadataMappingRepo; - @Mock + @MockBean private ConnectionRepository connectionRepo; - @InjectMocks + @Autowired private UserMetadataMappingService userMetadataMappingService; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); } @Test @@ -70,7 +75,7 @@ public void testAddMappings_Success() { verify(userMetadataMappingRepo, times(1)).saveAll(mappings); } - @Test(expected = IllegalArgumentException.class) + @Test public void testAddMappings_ConnectionNotFound() { Connection connection = new Connection(); connection.setId("invalidConnectionId"); @@ -82,7 +87,9 @@ public void testAddMappings_ConnectionNotFound() { when(connectionRepo.findById("invalidConnectionId")).thenReturn(Optional.empty()); - userMetadataMappingService.addMappings(mappings); + assertThrows(IllegalArgumentException.class, () -> { + userMetadataMappingService.addMappings(mappings); + }); } @Test @@ -110,11 +117,13 @@ public void testGetAllMappingsForConnectionById_Success() { verify(connectionRepo, times(1)).findById("testConnectionId"); } - @Test(expected = IllegalArgumentException.class) + @Test public void testGetAllMappingsForConnectionById_NotFound() { when(connectionRepo.findById("invalidConnectionId")).thenReturn(Optional.empty()); - userMetadataMappingService.getAllMappingsForConnection("invalidConnectionId"); + assertThrows(IllegalArgumentException.class, () -> { + userMetadataMappingService.getAllMappingsForConnection("invalidConnectionId"); + }); } @Test diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/UserServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/UserServiceTest.java index 02848069..cbda4a01 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/UserServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/UserServiceTest.java @@ -6,49 +6,51 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.User; import edu.harvard.hms.dbmi.avillach.auth.enums.SecurityRoles; import edu.harvard.hms.dbmi.avillach.auth.model.CustomUserDetails; -import edu.harvard.hms.dbmi.avillach.auth.model.ras.RasDbgapPermission; import edu.harvard.hms.dbmi.avillach.auth.repository.ApplicationRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.ConnectionRepository; -import edu.harvard.hms.dbmi.avillach.auth.repository.RoleRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.UserRepository; import edu.harvard.hms.dbmi.avillach.auth.utils.AuthNaming; import edu.harvard.hms.dbmi.avillach.auth.utils.JWTUtil; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import jakarta.mail.MessagingException; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ContextConfiguration; import java.security.SecureRandom; import java.util.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; +@SpringBootTest +@ContextConfiguration(classes = {JWTUtil.class, UserService.class}) public class UserServiceTest { - @Mock + @MockBean private SecurityContext securityContext; - @Mock + @MockBean private BasicMailService basicMailService; - @Mock + @MockBean private TOSService tosService; - @Mock + @MockBean private UserRepository userRepository; - @Mock + @MockBean private ConnectionRepository connectionRepository; - @Mock + @MockBean private ApplicationRepository applicationRepository; - @Mock + @MockBean private RoleService roleService; - @Mock + @MockBean private JWTUtil mockJwtUtil; private JWTUtil jwtUtil; @@ -57,9 +59,9 @@ public class UserServiceTest { private UserService userService; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); Authentication authentication = mock(Authentication.class); SecurityContextHolder.setContext(securityContext); @@ -107,12 +109,14 @@ public void testGetUserById_found() { assertEquals(testId, result.getUuid()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testGetUserById_notFound() { UUID testId = UUID.randomUUID(); when(userRepository.findById(testId)).thenReturn(Optional.empty()); - userService.getUserById(testId.toString()); + assertThrows(IllegalArgumentException.class, ()-> { + userService.getUserById(testId.toString()); + }); } @Test @@ -164,7 +168,7 @@ public void testAddUsers_SuperAdminRole() { assertEquals(user, result.getFirst()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testAddUsers_SuperAdminRole_withoutNecessaryPrivileges() { User user = createTestUser(); Set roles = user.getRoles(); @@ -178,19 +182,24 @@ public void testAddUsers_SuperAdminRole_withoutNecessaryPrivileges() { configureUserSecurityContext(loggedInUser); when(userRepository.saveAll(List.of(user))).thenReturn(List.of(user)); - userService.addUsers(List.of(user)); + assertThrows(IllegalArgumentException.class, () -> { + userService.addUsers(List.of(user)); + }); + } - @Test(expected = RuntimeException.class) + @Test public void testAddUsers_UserRoleNotExisting() { User user = createTestUser(); configureUserSecurityContext(user); when(userRepository.saveAll(List.of(user))).thenReturn(List.of(user)); - List result = userService.addUsers(List.of(user)); - assertNotNull(result); - assertEquals(1, result.size()); - assertEquals(user, result.getFirst()); + assertThrows(RuntimeException.class, () -> { + List result = userService.addUsers(List.of(user)); + assertNotNull(result); + assertEquals(1, result.size()); + assertEquals(user, result.getFirst()); + }); } @Test @@ -255,7 +264,7 @@ public void testUpdateUser_SuperAdminRole() { assertNotNull(result); } - @Test(expected = IllegalArgumentException.class) + @Test public void testUpdateUser_SuperAdminRole_withoutNecessaryPrivileges() { User user = createTestUser(); Set roles = user.getRoles(); @@ -273,20 +282,26 @@ public void testUpdateUser_SuperAdminRole_withoutNecessaryPrivileges() { userToFindByID.setRoles(new HashSet<>()); when(userRepository.findById(user.getUuid())).thenReturn(Optional.of(userToFindByID)); - userService.updateUser(List.of(user)); + assertThrows(IllegalArgumentException.class, ()-> { + userService.updateUser(List.of(user)); + }); } - @Test(expected = NullPointerException.class) + @Test public void testGetUserProfileResponse_missingClaims() { HashMap incompleteClaims = new HashMap<>(); incompleteClaims.put("email", "test@example.com"); // Missing "sub" which is mandatory for the method logic - userService.getUserProfileResponse(incompleteClaims); + assertThrows(NullPointerException.class, ()->{ + userService.getUserProfileResponse(incompleteClaims); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testGetUserById_invalidUUID() { - userService.getUserById("not-a-real-uuid"); + assertThrows(IllegalArgumentException.class, () -> { + userService.getUserById("not-a-real-uuid"); + }); } @Test @@ -400,9 +415,11 @@ public void testGetCurrentUser_withNoPrivileges() { assertEquals(user.getToken(), currentUser.getToken()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testGetQueryTemplate_invalidApplicationId() { - userService.getQueryTemplate(null); + assertThrows(IllegalArgumentException.class, ()->{ + userService.getQueryTemplate(null); + }); } @Test @@ -459,7 +476,7 @@ public void testGetDefaultQueryTemplate() { assertNotNull(result.get("queryTemplate")); } - @Test(expected = NullPointerException.class) + @Test public void testAddUsers_withUserHavingNullRoleSet() { User user = createTestUser(); user.setRoles(null); @@ -467,8 +484,10 @@ public void testAddUsers_withUserHavingNullRoleSet() { configureUserSecurityContext(user); when(userRepository.saveAll(List.of(user))).thenReturn(List.of(user)); - List result = userService.addUsers(List.of(user)); - assertNull(result.getFirst().getRoles()); + assertThrows(NullPointerException.class, () -> { + List result = userService.addUsers(List.of(user)); + assertNull(result.getFirst().getRoles()); + }); } @Test diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authentication/AuthenticationServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authentication/AuthenticationServiceTest.java index e9aa36f7..77a1ec84 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authentication/AuthenticationServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authentication/AuthenticationServiceTest.java @@ -6,18 +6,21 @@ import edu.harvard.hms.dbmi.avillach.auth.exceptions.NotAuthorizedException; import edu.harvard.hms.dbmi.avillach.auth.repository.ConnectionRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.UserRepository; +import edu.harvard.hms.dbmi.avillach.auth.service.AuthenticationService; import edu.harvard.hms.dbmi.avillach.auth.service.impl.BasicMailService; import edu.harvard.hms.dbmi.avillach.auth.service.impl.CacheEvictionService; import edu.harvard.hms.dbmi.avillach.auth.service.impl.OauthUserMatchingService; import edu.harvard.hms.dbmi.avillach.auth.service.impl.UserService; import edu.harvard.hms.dbmi.avillach.auth.utils.RestClientUtil; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; import java.io.IOException; import java.util.HashMap; @@ -25,27 +28,30 @@ import java.util.Optional; import java.util.UUID; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; +@SpringBootTest +@ContextConfiguration(classes = {AuthenticationService.class}) public class AuthenticationServiceTest { - @Mock + @MockBean private OauthUserMatchingService matchingService; - @Mock + @MockBean private UserRepository userRepository; - @Mock + @MockBean private BasicMailService basicMailService; - @Mock + @MockBean private UserService userService; - @Mock + @MockBean private ConnectionRepository connectionRepository; - @Mock + @MockBean private RestClientUtil restClientUtil; - @Mock + @MockBean private CacheEvictionService cacheEvictionService; private Auth0AuthenticationService authenticationService; @@ -53,9 +59,9 @@ public class AuthenticationServiceTest { private final String accessToken = "dummyAccessToken"; private Map authRequest; - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); authRequest = new HashMap<>(); authRequest.put("access_token", accessToken); String redirectURI = "http://dummyRedirectUri.com"; @@ -65,25 +71,33 @@ public void setUp() { } // Tests missing parameters in the authentication request - @Test(expected = IllegalArgumentException.class) + @Test public void testGetToken_MissingParameters() throws IOException { - authenticationService.authenticate(new HashMap<>(), "localhost"); // Empty map should trigger the exception + assertThrows(IllegalArgumentException.class, () -> { + authenticationService.authenticate(new HashMap<>(), "localhost"); // Empty map should trigger the exception + }); } // Tests the failure in retrieving user information, expecting an IOException to be converted into a NotAuthorizedException - @Test(expected = NotAuthorizedException.class) + @Test public void testGetToken_UserInfoRetrievalFails() throws IOException { when(this.restClientUtil.retrieveGetResponseWithRequestConfiguration(anyString(), any(HttpHeaders.class), anyInt())) .thenThrow(new NotAuthorizedException("Failed to retrieve user info")); - authenticationService.authenticate(authRequest, "localhost"); + + assertThrows(NotAuthorizedException.class, () -> { + authenticationService.authenticate(authRequest, "localhost"); + }); } // Tests the scenario where the user ID is not found in the user info retrieved - @Test(expected = NotAuthorizedException.class) + @Test public void testGetToken_NoUserIdInUserInfo() throws IOException { when(this.restClientUtil.retrieveGetResponseWithRequestConfiguration(anyString(), any(), anyInt())) .thenReturn(new ResponseEntity<>("{}", HttpStatus.OK)); - authenticationService.authenticate(authRequest, "localhost"); + + assertThrows(NotAuthorizedException.class, () -> { + authenticationService.authenticate(authRequest, "localhost"); + }); } // Tests a successful token retrieval scenario @@ -110,10 +124,12 @@ public void testRetrieveUserInfo_WithRetries() throws Exception { } // Tests matching a token to a user when no existing user is found and an attempt to create a user fails - @Test(expected = NotAuthorizedException.class) + @Test public void testGetToken_NoUserMatchingAndCreationFails() throws Exception { setupNoUserMatchScenario(); - authenticationService.authenticate(authRequest, "localhost"); + assertThrows(NotAuthorizedException.class, () -> { + authenticationService.authenticate(authRequest, "localhost"); + }); } // Test scenario where denied access email is triggered diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authentication/RASAuthenticationServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authentication/RASAuthenticationServiceTest.java index 431a12cc..2c04b875 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authentication/RASAuthenticationServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authentication/RASAuthenticationServiceTest.java @@ -4,36 +4,37 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.Privilege; import edu.harvard.hms.dbmi.avillach.auth.entity.Role; import edu.harvard.hms.dbmi.avillach.auth.entity.User; -import edu.harvard.hms.dbmi.avillach.auth.repository.PrivilegeRepository; import edu.harvard.hms.dbmi.avillach.auth.repository.RoleRepository; import edu.harvard.hms.dbmi.avillach.auth.service.impl.*; import edu.harvard.hms.dbmi.avillach.auth.utils.FenceMappingUtility; import edu.harvard.hms.dbmi.avillach.auth.utils.RestClientUtil; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.stubbing.OngoingStubbing; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; import java.util.*; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.*; -@RunWith(MockitoJUnitRunner.class) +@SpringBootTest +@ContextConfiguration(classes = {RASPassPortService.class, RASAuthenticationService.class}) public class RASAuthenticationServiceTest { - @Mock + @MockBean private UserService userService; - @Mock + @MockBean private RestClientUtil restClientUtil; - @Mock + @MockBean private ConnectionWebService connectionService; - @Mock + @MockBean private CacheEvictionService cacheEvictionService; + @MockBean + private RoleService roleService; private RASPassPortService rasPassPortService; private RASAuthenticationService rasAuthenticationService; @@ -44,9 +45,9 @@ public class RASAuthenticationServiceTest { private Map authRequest; private final String exampleRasPassport = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImRlZmF1bHRfc3NsX2tleSJ9.ew0KInN1YiI6IjJLRWthUC1SeDJGdkJCOExRVjRucjVmZXlySG4yNXEwV3hVd1kxVDIwMnMiLA0KImp0aSI6ImNiZDFjMzkyLTk0YjYtNDc2Yi1iYjA5LTk2MWY4MTM3MmE2NCIsDQoic2NvcGUiOiJvcGVuaWQgZ2E0Z2hfcGFzc3BvcnRfdjEiLA0KInR4biI6IlRsdVJ1UVcvZlZrPS5mYWJkOTdkMTdkNGM4OGFiIiwNCiJpc3MiOiAiaHR0cHM6Ly9zdHNzdGcubmloLmdvdiIsIAoiaWF0IjogMTYyMDIxMDM2MiwKImV4cCI6IDE2MjAyNTM1NjIsCiJnYTRnaF9wYXNzcG9ydF92MSIgOiBbImV3MEtJQ0FpZEhsd0lqb2dJa3BYVkNJc0RRb2dJQ0poYkdjaU9pQWlVbE15TlRZaUxBMEtJQ0FpYTJsa0lqb2dJbVJsWm1GMWJIUmZjM05zWDJ0bGVTSU5DbjAuZXcwS0lDQWlhWE56SWpvZ0ltaDBkSEJ6T2k4dmMzUnpjM1JuTG01cGFDNW5iM1lpTEEwS0lDQWljM1ZpSWpvZ0lqSkxSV3RoVUMxU2VESkdka0pDT0V4UlZqUnVjalZtWlhseVNHNHlOWEV3VjNoVmQxa3hWREl3TW5NaUxDQU5DaUFnSW1saGRDSTZJREUyTWpBeU1UQXpOaklzRFFvZ0lDSmxlSEFpT2lBeE5qSXdNalV6TlRZeUxBMEtJQ0FpYzJOdmNHVWlPaUFpYjNCbGJtbGtJR2RoTkdkb1gzQmhjM053YjNKMFgzWXhJaXdOQ2lBZ0ltcDBhU0k2SUNJNU56UTNPV0UzTXkwMFltSmxMVFJoWVdVdE9HWTFNUzAxTldVNU9UQTBZalJqT1RnaUxBMEtJQ0FpZEhodUlqb2dJbFJzZFZKMVVWY3ZabFpyUFM1bVlXSmtPVGRrTVRka05HTTRPR0ZpSWl3TkNpQWdJbWRoTkdkb1gzWnBjMkZmZGpFaU9pQjdJQTBLSUNBZ0lDQWlkSGx3WlNJNklDSm9kSFJ3Y3pvdkwzSmhjeTV1YVdndVoyOTJMM1pwYzJGekwzWXhMakVpTENBTkNpQWdJQ0FnSW1GemMyVnlkR1ZrSWpvZ01UWXlNREl4TURNMk1pd05DaUFnSUNBZ0luWmhiSFZsSWpvZ0ltaDBkSEJ6T2k4dmMzUnpjM1JuTG01cGFDNW5iM1l2Y0dGemMzQnZjblF2WkdKbllYQXZkakV1TVNJc0RRb2dJQ0FnSUNKemIzVnlZMlVpT2lBaWFIUjBjSE02THk5dVkySnBMbTVzYlM1dWFXZ3VaMjkyTDJkaGNDSXNEUW9nSUNBZ0lDSmllU0k2SUNKa1lXTWlmU3dOQ2lBZ0lDQWdJbkpoYzE5a1ltZGhjRjl3WlhKdGFYTnphVzl1Y3lJNklGc05DaUFnSUNBZ0lDQWdJQTBLZXcwS0ltTnZibk5sYm5SZmJtRnRaU0k2SWtkbGJtVnlZV3dnVW1WelpXRnlZMmdnVlhObElpd0pEUW9pY0doelgybGtJam9pY0doek1EQXdNREEySWl3TkNpSjJaWEp6YVc5dUlqb2lkakVpTEEwS0luQmhjblJwWTJsd1lXNTBYM05sZENJNkluQXhJaXdKQ1EwS0ltTnZibk5sYm5SZlozSnZkWEFpT2lKak1TSXNEUW9pY205c1pTSTZJbkJwSWl3TkNpSmxlSEJwY21GMGFXOXVJam94TmpReE1ERXpNakF3RFFwOUxBMEtldzBLSW1OdmJuTmxiblJmYm1GdFpTSTZJa1Y0WTJoaGJtZGxJRUZ5WldFaUxBa05DaUp3YUhOZmFXUWlPaUp3YUhNd01EQXpNREFpTEEwS0luWmxjbk5wYjI0aU9pSjJNU0lzRFFvaWNHRnlkR2xqYVhCaGJuUmZjMlYwSWpvaWNERWlMQWtKRFFvaVkyOXVjMlZ1ZEY5bmNtOTFjQ0k2SW1NNU9Ua2lMQTBLSW5KdmJHVWlPaUp3YVNJc0RRb2laWGh3YVhKaGRHbHZiaUk2TVRZME1UQXhNekl3TUFrTkNuME5DaUFnSUNBZ1hTQU5DbjAuTnpSOEtzZTJOOUtFOXhvLUo4dXdUaWxzUG9pYXhNWGlGR0prY0JOYTMtOGt1ZEh3MFd6U0xDM3Z3Qk4yZ3Z0RUtMZ2ZBeVpVUDZrc0ktRzlOV0NIU3Z2RG4tbFNhbjVtV1dfWEhrRVdGWGd3RXotWlNNalBvV0Vndlk1bHhSWEhxR1lhWmQ5U2puTjdsTFpUbHNQLU9pbFUxcUNyQ205YzVfcTh1YWJyZ3o0OW5PWFRGZEpKblpPT1ZzUmtkU0NjVnlHczRlbUxNSjdDdVd2ckU2RkR2Ri1QTUpGNlhHYnN3R1pjVFRPM3h0MjR6Tk1wbm5RUEVzNXQ3Tk1LZjhucEJ3czNvd0FKcklTRkExYTNmUWtJZU83dFRUUGVSX1FRVUlxYzFJRW5JdlotMGdsNE5ETEZRSjJTTS1KdUtvSWdnQWt3NVNGWDNhSk9WNC12b2JZbXhBIl0NCn0.sJwAZeR8cYyF-BCluC9fmiQAi14L7hC3DB4MoFQNNdoakUBujPZ-NlpfP2rBgJQ3CGcxsF95Vdczm6Yk4TKa68eXkKjkswjsSSQg0qErgFhN2jis9KMxnMfmfPNUfb0lioHtD-_oghRkd9239oUwLR06KB5Ux3mD4Pc0ZPbJxJcPmyP9DZ8WEHmAFIJpcoayHwJDr1jt-GbqUtaTCs1VQ9Habh8Z8fvwrlvQNj744m5eq6141bD0G15KgvbyYf9L4_PYNgMjTyUx9EGyetrxQ4XmOpDF_ZbFEhZliy80qfO2HGQzSId-dKXCvPI_SUWcCVeJqPwmXTirTt9qJ63ypw"; - @Before + @BeforeEach public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); RoleService roleService = new RoleService(mock(RoleRepository.class), mock(PrivilegeService.class), mock(FenceMappingUtility.class)); this.rasPassPortService = spy(new RASPassPortService(restClientUtil, userService, "", cacheEvictionService)); doReturn(false).when(rasPassPortService).isExpired(any()); diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/AuthorizationServiceTestByUseCases.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/AuthorizationServiceByUseCasesTest.java similarity index 90% rename from pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/AuthorizationServiceTestByUseCases.java rename to pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/AuthorizationServiceByUseCasesTest.java index 800341ae..310523db 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/AuthorizationServiceTestByUseCases.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/AuthorizationServiceByUseCasesTest.java @@ -4,11 +4,14 @@ import edu.harvard.hms.dbmi.avillach.auth.entity.AccessRule; import edu.harvard.hms.dbmi.avillach.auth.repository.AccessRuleRepository; import edu.harvard.hms.dbmi.avillach.auth.service.impl.AccessRuleService; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.ContextConfiguration; import java.io.IOException; import java.util.HashSet; @@ -16,6 +19,9 @@ import java.util.Set; import java.util.UUID; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** *

This is a test class from the view of high level use cases (user input aspect)

*
@@ -40,9 +46,17 @@ * We also have a class testing from the aspect of design, which means each test case is just testing one feature. * @see AuthorizationServiceTest */ -public class AuthorizationServiceTestByUseCases { +@SpringBootTest +@ContextConfiguration(classes = {AccessRuleService.class}) +public class AuthorizationServiceByUseCasesTest { + + @MockBean + private AccessRuleRepository accessRuleRepository; - ObjectMapper mapper = new ObjectMapper(); + @Autowired + private AccessRuleService accessRuleService; + + private final ObjectMapper mapper = new ObjectMapper(); private static AccessRule rule_caseA; private static AccessRule rule_caseB; @@ -402,9 +416,7 @@ public class AuthorizationServiceTestByUseCases { " \"resourceCredentials\": {}\n" + "}"; - private AccessRuleService accessRuleService; - - @BeforeClass + @BeforeAll public static void init() { initialTestCaseA(); initialTestCaseB(); @@ -414,7 +426,7 @@ public static void init() { initialTestCaseF(); } - @Before + @BeforeEach public void setUp() { AccessRuleRepository accessRuleRepository = Mockito.mock(AccessRuleRepository.class); accessRuleService = new AccessRuleService(accessRuleRepository, "false", "false", "false", "false","false", "false"); @@ -422,8 +434,8 @@ public void setUp() { @Test public void testCaseA() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_pass, Map.class), rule_caseA)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_fail, Map.class), rule_caseA)); + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_pass, Map.class), rule_caseA)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_fail, Map.class), rule_caseA)); } private static void initialTestCaseA(){ @@ -438,8 +450,8 @@ private static void initialTestCaseA(){ @Test public void testCaseB() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_pass, Map.class), rule_caseB)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_fail, Map.class), rule_caseB)); + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_pass, Map.class), rule_caseB)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseAB_fail, Map.class), rule_caseB)); } private static void initialTestCaseB(){ @@ -464,9 +476,9 @@ private static void initialTestCaseB(){ @Test public void testCaseC() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_pass, Map.class), rule_caseC)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail, Map.class), rule_caseC)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail_2, Map.class), rule_caseC)); + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_pass, Map.class), rule_caseC)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail, Map.class), rule_caseC)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail_2, Map.class), rule_caseC)); } private static void initialTestCaseC(){ @@ -520,9 +532,9 @@ private static void initialTestCaseC(){ @Test public void testCaseD() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_pass, Map.class), rule_caseD)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail, Map.class), rule_caseD)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail_2, Map.class), rule_caseD)); + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_pass, Map.class), rule_caseD)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail, Map.class), rule_caseD)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseCD_fail_2, Map.class), rule_caseD)); } private static void initialTestCaseD(){ @@ -546,22 +558,22 @@ private static void initialTestCaseD(){ @Test public void testCaseE() throws IOException { - Assert.assertTrue( + assertTrue( accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_pass, Map.class), rule_caseE) || accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_pass, Map.class), rule_caseE_2) ); - Assert.assertTrue( + assertTrue( accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_2_pass, Map.class), rule_caseE) || accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_2_pass, Map.class), rule_caseE_2) ); - Assert.assertFalse( + assertFalse( accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_fail, Map.class), rule_caseE) || accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_fail, Map.class), rule_caseE_2) ); - Assert.assertFalse( + assertFalse( accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_2_fail, Map.class), rule_caseE) || accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseE_2_fail, Map.class), rule_caseE_2) ); @@ -609,12 +621,12 @@ private static void initialTestCaseE(){ @Test public void testCaseF() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_pass, Map.class), rule_caseF)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail, Map.class), rule_caseF)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_2, Map.class), rule_caseF)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_3, Map.class), rule_caseF)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_4, Map.class), rule_caseF)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_5, Map.class), rule_caseF)); + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_pass, Map.class), rule_caseF)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail, Map.class), rule_caseF)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_2, Map.class), rule_caseF)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_3, Map.class), rule_caseF)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_4, Map.class), rule_caseF)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_caseF_fail_5, Map.class), rule_caseF)); } private static void initialTestCaseF(){ diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/AuthorizationServiceTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/AuthorizationServiceTest.java index 5a81ab52..7ca7dea3 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/AuthorizationServiceTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/AuthorizationServiceTest.java @@ -2,48 +2,49 @@ import com.fasterxml.jackson.databind.ObjectMapper; import edu.harvard.hms.dbmi.avillach.auth.entity.*; -import edu.harvard.hms.dbmi.avillach.auth.enums.SecurityRoles; import edu.harvard.hms.dbmi.avillach.auth.model.CustomUserDetails; import edu.harvard.hms.dbmi.avillach.auth.repository.AccessRuleRepository; import edu.harvard.hms.dbmi.avillach.auth.service.impl.AccessRuleService; import edu.harvard.hms.dbmi.avillach.auth.service.impl.RoleService; import edu.harvard.hms.dbmi.avillach.auth.service.impl.SessionService; -import edu.harvard.hms.dbmi.avillach.auth.utils.AuthNaming; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.Mock; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.ContextConfiguration; import java.io.IOException; import java.util.*; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; +@SpringBootTest +@ContextConfiguration(classes = {AuthorizationService.class, AccessRuleService.class}) public class AuthorizationServiceTest { - @Mock + @MockBean private SecurityContext securityContext; private AuthorizationService authorizationService; private AccessRuleService accessRuleService; - @Mock + @MockBean private SessionService sessionService; - @Mock + @MockBean private AccessRuleRepository accessRuleRepository; - @Mock + @MockBean private RoleService roleService; - ObjectMapper mapper = new ObjectMapper(); + private final ObjectMapper mapper = new ObjectMapper(); private static AccessRule GATE_resouceUUID; private static AccessRule GATE_has_expectedResultType; @@ -232,7 +233,7 @@ public class AuthorizationServiceTest { "}]\n" + "}"; - @BeforeClass + @BeforeAll public static void init() { GATE_resouceUUID = new AccessRule(); GATE_resouceUUID.setUuid(UUID.randomUUID()); @@ -315,9 +316,9 @@ public static void init() { AR_Fields_IS_NOT_EMPTY.setType(AccessRule.TypeNaming.IS_NOT_EMPTY); } - @Before + @BeforeEach public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); SecurityContextHolder.setContext(securityContext); when(sessionService.isSessionExpired(any(String.class))).thenReturn(false); @@ -655,8 +656,8 @@ public void testEvaluateAccessRule_SubAccessRules() { @Test public void testGates() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_matchGate, Map.class), GATE_resouceUUID)); - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_matchGate, Map.class), GATE_has_expectedResultType)); + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_matchGate, Map.class), GATE_resouceUUID)); + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_matchGate, Map.class), GATE_has_expectedResultType)); } @@ -666,8 +667,7 @@ public void testWithGate_passGate_passCheck_all_string_contains() throws IOExcep Set gates = new HashSet<>(); gates.add(GATE_resouceUUID); AR_CategoryFilter_String_contains.setGates(gates); - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_passGate_passCheck_string_contains, Map.class), AR_CategoryFilter_String_contains)); - + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_passGate_passCheck_string_contains, Map.class), AR_CategoryFilter_String_contains)); } @Test @@ -676,7 +676,7 @@ public void testWithGate_passGate_notPassCheck_string_contains() throws IOExcept Set gates = new HashSet<>(); gates.add(GATE_resouceUUID); AR_CategoryFilter_String_contains.setGates(gates); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(getSample_passGate_passCheck_array_contains, Map.class), AR_CategoryFilter_String_contains)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(getSample_passGate_passCheck_array_contains, Map.class), AR_CategoryFilter_String_contains)); } @Test @@ -685,8 +685,7 @@ public void testWithGate_passGate_passCheck_Array_contains() throws IOException{ Set gates = new HashSet<>(); gates.add(GATE_resouceUUID); AR_CategoryFilter_Any_Contains.setGates(gates); - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(getSample_passGate_passCheck_array_contains, Map.class), AR_CategoryFilter_Any_Contains)); - + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(getSample_passGate_passCheck_array_contains, Map.class), AR_CategoryFilter_Any_Contains)); } @Test @@ -695,8 +694,7 @@ public void testWithGate_passGate_notPassCheck() throws IOException{ Set gates = new HashSet<>(); gates.add(GATE_resouceUUID); AR_CategoryFilter_String_contains.setGates(gates); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(getSample_passGate_passCheck_array_contains, Map.class), AR_CategoryFilter_String_contains)); - + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(getSample_passGate_passCheck_array_contains, Map.class), AR_CategoryFilter_String_contains)); } @Test @@ -704,7 +702,7 @@ public void testWithGate_notPassGate() throws IOException { Set gates = new HashSet<>(); gates.add(GATE_resouceUUID); AR_CategoryFilter_String_contains.setGates(gates); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_no_pass_gate, Map.class), AR_CategoryFilter_String_contains)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_no_pass_gate, Map.class), AR_CategoryFilter_String_contains)); } /** @@ -720,18 +718,18 @@ public void testMerging_emptyNodes_noSuchNode() throws IOException { Set mergedAccessRules = accessRuleService.preProcessARBySortedKeys(inputAccessRules); - Assert.assertEquals(1, mergedAccessRules.size()); + assertEquals(1, mergedAccessRules.size()); - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withFields_SEX_And_AGE, Map.class), + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withFields_SEX_And_AGE, Map.class), mergedAccessRules.stream().findFirst().get())); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withFields_and_SEE_AGE_SEX, Map.class), + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withFields_and_SEE_AGE_SEX, Map.class), mergedAccessRules.stream().findFirst().get())); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withEmptyFields, Map.class), + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withEmptyFields, Map.class), mergedAccessRules.stream().findFirst().get())); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withNoFieldsNode, Map.class), + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withNoFieldsNode, Map.class), mergedAccessRules.stream().findFirst().get())); } @@ -743,8 +741,8 @@ public void testMerging_emptyNodes_noSuchNode() throws IOException { */ @Test public void testRuleIsEmpty_IsNotEmpty() throws IOException { - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withEmptyFields, Map.class), AR_Fields_IS_EMPTY)); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withEmptyFields, Map.class), AR_Fields_IS_NOT_EMPTY)); + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withEmptyFields, Map.class), AR_Fields_IS_EMPTY)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_UUID_8694e3d4_withEmptyFields, Map.class), AR_Fields_IS_NOT_EMPTY)); } /** @@ -765,14 +763,14 @@ public void testGatesAllorAny() throws IOException{ // default is false, for testing, we explicitly set it here just for fluently reading code accessRuleGatesAllAny.setGateAnyRelation(false); // No gates applied, return false. - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_gates_all_any, Map.class), accessRuleGatesAllAny)); + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_gates_all_any, Map.class), accessRuleGatesAllAny)); // the rules will deny the access, but since we set only evaluate gates with OR relationship, // while the gates passes, it will return true. // Here we test any relationship and evaluate only by gates. accessRuleGatesAllAny.setGateAnyRelation(true); accessRuleGatesAllAny.setEvaluateOnlyByGates(true); - Assert.assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_gates_all_any, Map.class), accessRuleGatesAllAny)); + assertTrue(accessRuleService.evaluateAccessRule(mapper.readValue(sample_gates_all_any, Map.class), accessRuleGatesAllAny)); } @@ -805,8 +803,7 @@ public void testGateNestedAllorAny() throws IOException { gates2.add(GATE_has_expectedResultType); accessRuleGatesAllandAny.setGates(gates2); - Assert.assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_nestedGates, Map.class), accessRuleGatesAllandAny)); - + assertFalse(accessRuleService.evaluateAccessRule(mapper.readValue(sample_nestedGates, Map.class), accessRuleGatesAllandAny)); } private Role createTestRole() { @@ -830,21 +827,6 @@ private void configureUserSecurityContext(User user) { when(securityContext.getAuthentication()).thenReturn(authentication); } - private Role createSuperAdminRole() { - Role role = new Role(); - role.setName(SecurityRoles.SUPER_ADMIN.name()); - role.setUuid(UUID.randomUUID()); - role.setPrivileges(Collections.singleton(createSuperAdminPrivilege())); - return role; - } - - private Privilege createSuperAdminPrivilege() { - Privilege privilege = new Privilege(); - privilege.setName(AuthNaming.AuthRoleNaming.SUPER_ADMIN); - privilege.setUuid(UUID.randomUUID()); - return privilege; - } - private User createTestUser() { User user = new User(); user.setUuid(UUID.randomUUID()); diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/FenceAuthorizationService.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/FenceAuthorizationService.java deleted file mode 100644 index 42fe8b5e..00000000 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/service/impl/authorization/FenceAuthorizationService.java +++ /dev/null @@ -1,4 +0,0 @@ -package edu.harvard.hms.dbmi.avillach.auth.service.impl.authorization; - -public class FenceAuthorizationService { -} diff --git a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/utils/JsonUtilsTest.java b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/utils/JsonUtilsTest.java index 97eee285..1d8e4736 100644 --- a/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/utils/JsonUtilsTest.java +++ b/pic-sure-auth-services/src/test/java/edu/harvard/hms/dbmi/avillach/auth/utils/JsonUtilsTest.java @@ -1,20 +1,21 @@ package edu.harvard.hms.dbmi.avillach.auth.utils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.util.Collection; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; + +import static org.junit.jupiter.api.Assertions.*; +@SpringBootTest +@ContextConfiguration(classes = {JsonUtils.class}) public class JsonUtilsTest { @@ -31,10 +32,6 @@ public class JsonUtilsTest { * } */ - @Before - public void init() { - } - @Test public void testmergeTemplateMap() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); @@ -57,7 +54,7 @@ public void testmergeTemplateMap() throws IOException { assertNotNull(mergedTemplate.get("requiredFields")); //both required fields (same) should have been merged - assertTrue(mergedTemplate.get("requiredFields") instanceof Collection); + assertInstanceOf(Collection.class, mergedTemplate.get("requiredFields")); assertEquals(1, ((Collection)mergedTemplate.get("requiredFields")).size()); assertNotNull(mergedTemplate.get("variantInfoFilters")); @@ -93,7 +90,7 @@ public void testmergeTemplateMapEmptyMap() throws IOException { assertNotNull(mergedTemplate.get("requiredFields")); //both required fields (same) should have been merged - assertTrue(mergedTemplate.get("requiredFields") instanceof Collection); + assertInstanceOf(Collection.class, mergedTemplate.get("requiredFields")); assertEquals(1, ((Collection)mergedTemplate.get("requiredFields")).size()); assertNotNull(mergedTemplate.get("variantInfoFilters")); @@ -130,7 +127,7 @@ public void testmergeTemplateMapEmptyMapInverse() throws IOException { assertNotNull(mergedTemplate.get("requiredFields")); //both required fields (same) should have been merged - assertTrue(mergedTemplate.get("requiredFields") instanceof Collection); + assertInstanceOf(Collection.class, mergedTemplate.get("requiredFields")); assertEquals(1, ((Collection)mergedTemplate.get("requiredFields")).size()); assertNotNull(mergedTemplate.get("variantInfoFilters")); @@ -153,7 +150,7 @@ public void testmergeTemplateMapMergeFilters() throws IOException{ //validate that the same category filters are merged assertNotNull(mergedTemplate.get("categoryFilters")); - assertTrue(mergedTemplate.get("categoryFilters") instanceof Map); + assertInstanceOf(Map.class, mergedTemplate.get("categoryFilters")); Map categoryFilters = (Map)mergedTemplate.get("categoryFilters"); assertEquals(1, categoryFilters.size());