diff --git a/build.gradle b/build.gradle index b9076244c..61dc616c5 100644 --- a/build.gradle +++ b/build.gradle @@ -137,6 +137,20 @@ sourceSets { } } +idea { + module { + // config to allow Intelij to mark test source and resource files correctly to help linting tools + testSources.from(java.sourceSets.functionalTest.java.srcDirs) + testSources.from(java.sourceSets.integrationTest.java.srcDirs) + testSources.from(java.sourceSets.smokeTest.java.srcDirs) + testSources.from(java.sourceSets.contractTest.java.srcDirs) + testResources.from(java.sourceSets.functionalTest.resources.srcDirs) + testResources.from(java.sourceSets.integrationTest.resources.srcDirs) + testResources.from(java.sourceSets.smokeTest.resources.srcDirs) + testResources.from(java.sourceSets.contractTest.resources.srcDirs) + } +} + tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:unchecked" << "-Werror" } @@ -298,6 +312,13 @@ repositories { } } +tasks.named('integration') { + useJUnitPlatform() + + testLogging { + exceptionFormat = 'full' + } +} dependencies { implementation(group: 'org.springframework.boot', name:'spring-boot-starter-web', version: versions.springBoot) { diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/config/SwaggerPublisher.java b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/config/SwaggerPublisher.java index b97930f33..d9305a3d0 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/config/SwaggerPublisher.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/config/SwaggerPublisher.java @@ -1,7 +1,7 @@ package uk.gov.hmcts.reform.orgrolemapping.config; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -33,7 +33,7 @@ public class SwaggerPublisher extends BaseTest { @Inject private WebApplicationContext wac; - @Before + @BeforeEach public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/BaseTest.java b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/BaseTest.java index 3688ce65b..c2174553a 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/BaseTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/BaseTest.java @@ -2,20 +2,34 @@ import com.azure.messaging.servicebus.ServiceBusSenderClient; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.github.tomakehurst.wiremock.WireMockServer; import com.microsoft.azure.servicebus.SubscriptionClient; import com.opentable.db.postgres.embedded.EmbeddedPostgres; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ApplicationListener; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; +import org.springframework.context.event.ContextClosedEvent; import org.springframework.jdbc.datasource.SingleConnectionDataSource; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.lang.NonNull; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.support.TestPropertySourceUtils; +import uk.gov.hmcts.reform.orgrolemapping.controller.utils.WiremockFixtures; import javax.annotation.PreDestroy; @@ -26,9 +40,17 @@ import java.sql.SQLException; import java.util.Properties; -@RunWith(SpringRunner.class) +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; + +@ContextConfiguration(initializers = {BaseTest.WireMockServerInitializer.class}) +@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("itest") +@EnableConfigurationProperties public abstract class BaseTest { + + public static final WireMockServer WIRE_MOCK_SERVER = new WireMockServer(options().dynamicPort()); + protected static final ObjectMapper mapper = new ObjectMapper(); @MockBean @@ -51,10 +73,20 @@ public abstract class BaseTest { @MockBean(name = "getSubscriptionClient1") private SubscriptionClient getSubscriptionClient1; - @BeforeClass - public static void init() { + @MockBean(name = "clientRegistrationRepository") + private ClientRegistrationRepository getClientRegistrationRepository; + + @MockBean(name = "reactiveClientRegistrationRepository") + private ReactiveClientRegistrationRepository getReactiveClientRegistrationRepository; + + static { + if (!WIRE_MOCK_SERVER.isRunning()) { + WIRE_MOCK_SERVER.start(); + } + mapper.registerModule(new JavaTimeModule()); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); // Force re-initialisation of base types for each test suite } @@ -88,4 +120,31 @@ public void contextDestroyed() throws SQLException { } } } + + public static class WireMockServerInitializer + implements ApplicationContextInitializer { + + private final WiremockFixtures wiremockFixtures = new WiremockFixtures(); + + @Override + public void initialize(@NonNull ConfigurableApplicationContext applicationContext) { + + TestPropertySourceUtils.addInlinedPropertiesToEnvironment( + applicationContext, + "wiremock.server.port=" + WIRE_MOCK_SERVER.port() + ); + + try { + wiremockFixtures.stubIdamConfig(); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + + applicationContext.addApplicationListener((ApplicationListener) event -> { + if (WIRE_MOCK_SERVER.isRunning()) { + WIRE_MOCK_SERVER.shutdown(); + } + }); + } + } } diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/RefreshControllerIntegrationTest.java b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/RefreshControllerIntegrationTest.java index c70ca7f2e..86edfe3e2 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/RefreshControllerIntegrationTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/RefreshControllerIntegrationTest.java @@ -1,11 +1,11 @@ package uk.gov.hmcts.reform.orgrolemapping.controller; import org.jetbrains.annotations.NotNull; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -30,6 +30,7 @@ import uk.gov.hmcts.reform.orgrolemapping.apihelper.Constants; import uk.gov.hmcts.reform.orgrolemapping.controller.advice.exception.UnauthorizedServiceException; import uk.gov.hmcts.reform.orgrolemapping.controller.utils.MockUtils; +import uk.gov.hmcts.reform.orgrolemapping.controller.utils.WiremockFixtures; import uk.gov.hmcts.reform.orgrolemapping.data.RefreshJobEntity; import uk.gov.hmcts.reform.orgrolemapping.domain.model.Appointment; import uk.gov.hmcts.reform.orgrolemapping.domain.model.CaseWorkerProfilesResponse; @@ -63,10 +64,10 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; @@ -90,6 +91,8 @@ public class RefreshControllerIntegrationTest extends BaseTest { private static final Logger logger = LoggerFactory.getLogger(RefreshControllerIntegrationTest.class); + private final WiremockFixtures wiremockFixtures = new WiremockFixtures(); + private static final String REFRESH_JOB_RECORDS_QUERY = "SELECT job_id, status, user_ids, linked_job_id," + " comments, log FROM refresh_jobs where job_id=?"; private static final String AUTHORISED_SERVICE = "am_role_assignment_refresh_batch"; @@ -140,18 +143,18 @@ public class RefreshControllerIntegrationTest extends BaseTest { StandardCharsets.UTF_8 ); - @Before + @BeforeEach public void setUp() throws Exception { template = new JdbcTemplate(ds); mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); - MockitoAnnotations.openMocks(this); doReturn(authentication).when(securityContext).getAuthentication(); SecurityContextHolder.setContext(securityContext); doReturn(true).when(featureConditionEvaluation).preHandle(any(),any(),any()); MockUtils.setSecurityAuthorities(authentication, MockUtils.ROLE_CASEWORKER); + wiremockFixtures.resetRequests(); } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:sql/insert_refresh_jobs.sql"}) public void shouldProcessRefreshRoleAssignmentsWithJobIdToComplete() throws Exception { @@ -180,7 +183,7 @@ public void shouldProcessRefreshRoleAssignmentsWithJobIdToComplete() throws Exce assertNotNull(refreshJob.getLog()); } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:sql/insert_refresh_jobs.sql"}) public void shouldProcessRefreshRoleAssignmentsWithJobIdToAborted() throws Exception { @@ -207,7 +210,7 @@ public void shouldProcessRefreshRoleAssignmentsWithJobIdToAborted() throws Excep assertThat(refreshJob.getLog(),containsString(String.join(",", refreshJob.getUserIds()))); } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:sql/insert_refresh_jobs.sql"}) public void shouldProcessRefreshRoleAssignmentsWithJobIdToAborted_status422() throws Exception { @@ -234,7 +237,7 @@ public void shouldProcessRefreshRoleAssignmentsWithJobIdToAborted_status422() th assertThat(refreshJob.getLog(),containsString(String.join(",", refreshJob.getUserIds()))); } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:sql/insert_refresh_jobs.sql"}) public void shouldProcessRefreshRoleAssignmentsWithJobIdToPartialComplete() throws Exception { @@ -261,7 +264,7 @@ public void shouldProcessRefreshRoleAssignmentsWithJobIdToPartialComplete() thro assertThat(refreshJob.getLog(), containsString(String.join(",", refreshJob.getUserIds()))); } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:sql/insert_refresh_jobs.sql"}) public void shouldProcessRefreshRoleAssignmentsWithJobIdToPartialComplete_status422() throws Exception { @@ -288,7 +291,7 @@ public void shouldProcessRefreshRoleAssignmentsWithJobIdToPartialComplete_status assertThat(refreshJob.getLog(), containsString(String.join(",", refreshJob.getUserIds()))); } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:sql/insert_refresh_jobs.sql"}) public void shouldProcessRefreshRoleAssignmentsWithFailedUsersToComplete() throws Exception { @@ -373,7 +376,7 @@ public void shouldFailProcessRefreshRoleAssignmentsWithOutJobID() throws Excepti .andReturn(); } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test public void shouldFailProcessRefreshRoleAssignmentsWithInvalidServiceToken() throws Exception { logger.info("Refresh request rejected with invalid service token"); @@ -391,7 +394,7 @@ public void shouldFailProcessRefreshRoleAssignmentsWithInvalidServiceToken() thr assertThat(result.getResolvedException().getMessage(), equalTo(UNAUTHORIZED_SERVICE)); } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:sql/insert_refresh_jobs.sql"}) public void shouldProcessRefreshRoleAssignmentsWithJobIdToComplete_retryFail() throws Exception { @@ -416,7 +419,7 @@ public void shouldProcessRefreshRoleAssignmentsWithJobIdToComplete_retryFail() t assertEquals("NEW", refreshJob.getStatus());// failed process should change the status to IN-PROGRESS } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:sql/insert_refresh_jobs.sql"}) public void shouldProcessRefreshRoleAssignmentsWithJobIdToComplete_CRDRetry() throws Exception { diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/RefreshControllerIntegrationV2Test.java b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/RefreshControllerIntegrationV2Test.java index da2e2be3f..b3a63512c 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/RefreshControllerIntegrationV2Test.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/RefreshControllerIntegrationV2Test.java @@ -1,11 +1,10 @@ package uk.gov.hmcts.reform.orgrolemapping.controller; import org.jetbrains.annotations.NotNull; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -30,6 +29,7 @@ import uk.gov.hmcts.reform.orgrolemapping.apihelper.Constants; import uk.gov.hmcts.reform.orgrolemapping.controller.advice.exception.UnauthorizedServiceException; import uk.gov.hmcts.reform.orgrolemapping.controller.utils.MockUtils; +import uk.gov.hmcts.reform.orgrolemapping.controller.utils.WiremockFixtures; import uk.gov.hmcts.reform.orgrolemapping.data.RefreshJobEntity; import uk.gov.hmcts.reform.orgrolemapping.domain.model.AppointmentV2; import uk.gov.hmcts.reform.orgrolemapping.domain.model.CaseWorkerProfilesResponse; @@ -62,9 +62,9 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; @@ -86,6 +86,8 @@ public class RefreshControllerIntegrationV2Test extends BaseTest { private static final Logger logger = LoggerFactory.getLogger(RefreshControllerIntegrationV2Test.class); + private final WiremockFixtures wiremockFixtures = new WiremockFixtures(); + private static final String REFRESH_JOB_RECORDS_QUERY = "SELECT job_id, status, user_ids, linked_job_id," + " comments, log FROM refresh_jobs where job_id=?"; private static final String AUTHORISED_SERVICE = "am_role_assignment_refresh_batch"; @@ -97,6 +99,9 @@ public class RefreshControllerIntegrationV2Test extends BaseTest { private MockMvc mockMvc; private JdbcTemplate template; + @Autowired + private RefreshController controller; + @Inject private WebApplicationContext wac; @@ -136,15 +141,15 @@ public class RefreshControllerIntegrationV2Test extends BaseTest { StandardCharsets.UTF_8 ); - @Before + @BeforeEach public void setUp() throws Exception { template = new JdbcTemplate(ds); mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); - MockitoAnnotations.openMocks(this); doReturn(authentication).when(securityContext).getAuthentication(); SecurityContextHolder.setContext(securityContext); doReturn(true).when(featureConditionEvaluation).preHandle(any(),any(),any()); MockUtils.setSecurityAuthorities(authentication, MockUtils.ROLE_CASEWORKER); + wiremockFixtures.resetRequests(); } @Test @@ -191,7 +196,7 @@ public void shouldFailProcessRefreshRoleAssignmentsWithOutJobID() throws Excepti .andReturn(); } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test public void shouldFailProcessRefreshRoleAssignmentsWithInvalidServiceToken() throws Exception { logger.info("Refresh request rejected with invalid service token"); @@ -209,7 +214,7 @@ public void shouldFailProcessRefreshRoleAssignmentsWithInvalidServiceToken() thr assertThat(result.getResolvedException().getMessage(), equalTo(UNAUTHORIZED_SERVICE)); } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:sql/insert_refresh_jobs.sql"}) public void shouldProcessRefreshRoleAssignmentsWithJobIdToComplete_retryFail() throws Exception { @@ -234,7 +239,7 @@ public void shouldProcessRefreshRoleAssignmentsWithJobIdToComplete_retryFail() t assertEquals("NEW", refreshJob.getStatus());// failed process should change the status to IN-PROGRESS } - @Ignore("Intermittent AM-2919") + @Disabled("Intermittent AM-2919") @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:sql/insert_refresh_jobs.sql"}) public void shouldProcessRefreshRoleAssignmentsWithJobIdToComplete_CRDRetry() throws Exception { diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/WelcomeControllerIntegrationTest.java b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/WelcomeControllerIntegrationTest.java index b1cff43f7..0b06a90cd 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/WelcomeControllerIntegrationTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/WelcomeControllerIntegrationTest.java @@ -3,12 +3,11 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.codehaus.plexus.util.StringUtils; -import org.junit.Before; import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.DisplayName; import org.mockito.Mock; import org.slf4j.Logger; @@ -30,6 +29,7 @@ import org.springframework.web.context.WebApplicationContext; import uk.gov.hmcts.reform.idam.client.models.UserInfo; import uk.gov.hmcts.reform.orgrolemapping.controller.utils.MockUtils; +import uk.gov.hmcts.reform.orgrolemapping.controller.utils.WiremockFixtures; import uk.gov.hmcts.reform.orgrolemapping.domain.model.JRDUserRequest; import uk.gov.hmcts.reform.orgrolemapping.domain.model.JudicialProfile; import uk.gov.hmcts.reform.orgrolemapping.domain.model.UserRequest; @@ -55,8 +55,6 @@ import java.util.Objects; import java.util.Set; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -77,6 +75,8 @@ public class WelcomeControllerIntegrationTest extends BaseTest { private static final Logger logger = LoggerFactory.getLogger(WelcomeControllerIntegrationTest.class); + private final WiremockFixtures wiremockFixtures = new WiremockFixtures(); + private transient MockMvc mockMvc; @Mock @@ -143,7 +143,7 @@ public class WelcomeControllerIntegrationTest extends BaseTest { UserRequest userRequest; List judicialProfiles; - @Before + @BeforeEach public void setUp() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //this.mockMvc = standaloneSetup(this.welcomeController).build() @@ -166,6 +166,7 @@ public void setUp() throws Exception { judicialProfiles = new ArrayList<>(buildJudicialProfile(JRDUserRequest.builder() .sidamIds(Set.copyOf(userRequest.getUserIds())).build(),"judicialProfileSample.json")); + wiremockFixtures.resetRequests(); } @Test @@ -699,14 +700,7 @@ public void setRoleAssignmentWireMock(HttpStatus status, String fileName) throws returnHttpStatus = 201; } - roleAssignmentService.stubFor(WireMock.post(urlEqualTo("/am/role-assignments")) - .willReturn(aResponse() - .withHeader("Content-Type", "application/json") - .withBody(body) - .withStatus(returnHttpStatus) - )); - - + wiremockFixtures.stubRoleAssignments(body, returnHttpStatus); } private String readJsonFromFile(String fileName) throws IOException { diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/utils/WiremockFixtures.java b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/utils/WiremockFixtures.java new file mode 100644 index 000000000..2ff8da867 --- /dev/null +++ b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/controller/utils/WiremockFixtures.java @@ -0,0 +1,84 @@ +package uk.gov.hmcts.reform.orgrolemapping.controller.utils; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.github.tomakehurst.wiremock.client.WireMock; +import com.nimbusds.jose.JOSEException; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static com.azure.core.http.ContentType.APPLICATION_JSON; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.resetAllRequests; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; +import static uk.gov.hmcts.reform.orgrolemapping.controller.BaseTest.WIRE_MOCK_SERVER; +import static uk.gov.hmcts.reform.orgrolemapping.util.KeyGenerator.getRsaJwk; + +public class WiremockFixtures { + + public static final ObjectMapper OBJECT_MAPPER = new Jackson2ObjectMapperBuilder() + .modules(new Jdk8Module(), new JavaTimeModule()) + .build(); + + public WiremockFixtures() { + configureFor(WIRE_MOCK_SERVER.port()); + } + + public void resetRequests() { + resetAllRequests(); + } + + public void stubIdamConfig() throws JsonProcessingException { + + WIRE_MOCK_SERVER.stubFor(get(urlPathMatching("/o/.well-known/openid-configuration")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", APPLICATION_JSON) + .withBody(OBJECT_MAPPER.writeValueAsString(getOpenIdResponse())) + )); + + WIRE_MOCK_SERVER.stubFor(get(urlPathMatching("/o/jwks")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", APPLICATION_JSON) + .withBody(getJwksResponse()) + )); + + } + + private Map getOpenIdResponse() { + LinkedHashMap data1 = new LinkedHashMap<>(); + data1.put("issuer", "http://localhost:" + WIRE_MOCK_SERVER.port() + "/o"); + data1.put("jwks_uri", "http://localhost:" + WIRE_MOCK_SERVER.port() + "/o/jwks"); + + return data1; + } + + private String getJwksResponse() { + try { + return "{" + + "\"keys\": [" + getRsaJwk().toPublicJWK().toJSONString() + "]" + + "}"; + + } catch (JOSEException ex) { + throw new RuntimeException(ex); + } + + } + + public void stubRoleAssignments(String body, int returnHttpStatus) { + WIRE_MOCK_SERVER.stubFor(WireMock.post(urlEqualTo("/am/role-assignments")) + .willReturn(aResponse() + .withHeader("Content-Type", "application/json") + .withBody(body) + .withStatus(returnHttpStatus) + )); + } +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/util/KeyGenerator.java b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/util/KeyGenerator.java new file mode 100644 index 000000000..978f61ce9 --- /dev/null +++ b/src/integrationTest/java/uk/gov/hmcts/reform/orgrolemapping/util/KeyGenerator.java @@ -0,0 +1,24 @@ +package uk.gov.hmcts.reform.orgrolemapping.util; + +import com.nimbusds.jose.JOSEException; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jose.jwk.gen.RSAKeyGenerator; + +public final class KeyGenerator { + + private static RSAKey rsaJwk; + private static final String KEY_ID = "23456789"; + + private KeyGenerator() { + } + + public static RSAKey getRsaJwk() throws JOSEException { + if (rsaJwk == null) { + rsaJwk = new RSAKeyGenerator(2048) + .keyID(KEY_ID) + .generate(); + } + return rsaJwk; + } + +} diff --git a/src/integrationTest/resources/application-itest.yaml b/src/integrationTest/resources/application-itest.yaml new file mode 100644 index 000000000..6d37ad11b --- /dev/null +++ b/src/integrationTest/resources/application-itest.yaml @@ -0,0 +1,18 @@ +spring: + security: + oauth2: + client: + provider: + oidc: + issuer-uri: http://localhost:${wiremock.server.port:5000}/o + +idam: + s2s-auth: + url: http://localhost:${wiremock.server.port:4502} + api.url: http://localhost:${wiremock.server.port:5000} + +feign: + client: + config: + roleAssignmentApp: + url: http://localhost:${wiremock.server.port:4096} \ No newline at end of file