diff --git a/build.gradle b/build.gradle index 0b34c3843ef..bf1cd7afec9 100644 --- a/build.gradle +++ b/build.gradle @@ -390,7 +390,6 @@ dependencies { implementation 'javax.validation:validation-api:2.0.1.Final' compileOnly 'javax.servlet:servlet-api:2.5' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' - implementation 'org.zalando:problem-spring-web-starter:0.29.1' implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.6.0' implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-openfeign', version: '4.1.2' diff --git a/src/functionalTest/java/uk/gov/hmcts/darts/events/CourtlogsFunctionalTest.java b/src/functionalTest/java/uk/gov/hmcts/darts/events/CourtlogsFunctionalTest.java index a5898b603df..4fbbc1deea1 100644 --- a/src/functionalTest/java/uk/gov/hmcts/darts/events/CourtlogsFunctionalTest.java +++ b/src/functionalTest/java/uk/gov/hmcts/darts/events/CourtlogsFunctionalTest.java @@ -76,7 +76,8 @@ void postFail() { "func-CASE1001" ], "text": "System : Start Recording : Record: Case Code:0008, New Case" - }""") + } + """) .when() .baseUri(getUri(ENDPOINT_URL)) .redirects().follow(false) @@ -133,9 +134,14 @@ void getFail() { .extract().response(); assertEquals(400, response.statusCode()); - assertThat(response.asPrettyString()).contains( - "Required request parameter 'start_date_time' for method parameter type OffsetDateTime is not present"); - + assertThat(response.asPrettyString()).contains(""" + { + "type": "about:blank", + "title": "Bad Request", + "status": 400, + "detail": "Required parameter 'start_date_time' is not present.", + "instance": "/courtlogs" + }"""); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerAddAudioMetadataIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerAddAudioMetadataIntTest.java index 12dbe06c259..154bc7d6d52 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerAddAudioMetadataIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerAddAudioMetadataIntTest.java @@ -1,11 +1,10 @@ package uk.gov.hmcts.darts.audio.controller; import ch.qos.logback.classic.Level; +import org.hamcrest.Matchers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -17,6 +16,7 @@ import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.unit.DataSize; @@ -376,7 +376,7 @@ void addAudioBeyondAudioFileSizeThresholdExceeded() throws Exception { Assertions.fail(); } catch (RestClientException restClientException) { String expectedJson = """ - 400 : "{"title":"Bad Request","status":400,"detail":"Maximum upload size exceeded"}" + 400 : "{"type":"about:blank","title":"Bad Request","status":400,"detail":"Maximum upload size exceeded","instance":"/audios"}" """; assertEquals(expectedJson.trim(), restClientException.getMessage()); @@ -404,18 +404,15 @@ void addAudioMetadataNonExistingCourthouse() throws Exception { objectMapper.writeValueAsString(addAudioMetadataRequest).getBytes() ); - MvcResult mvcResult = mockMvc.perform( + mockMvc.perform( multipart(ENDPOINT) .file(audioFile) .file(metadataJson)) .andExpect(status().isBadRequest()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"COMMON_100","title":"Provided courthouse does not exist","status":400,"detail":"Courthouse 'TEST' not found."}"""; - - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("COMMON_100"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(400))) + .andExpect(MockMvcResultMatchers.jsonPath("$.detail", Matchers.is("Courthouse 'TEST' not found."))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Provided courthouse does not exist"))); } @Test @@ -734,19 +731,14 @@ void addAudioReturnForbiddenError() throws Exception { objectMapper.writeValueAsString(addAudioMetadataRequest).getBytes() ); - MvcResult mvcResult = mockMvc.perform( + mockMvc.perform( multipart(ENDPOINT) .file(audioFile) .file(metadataJson)) .andExpect(status().isForbidden()) - .andReturn(); - - String actualResponse = mvcResult.getResponse().getContentAsString(); - - String expectedResponse = """ - {"type":"AUTHORISATION_109","title":"User is not authorised for this endpoint","status":403} - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); } private AddAudioMetadataRequest createAddAudioRequest(OffsetDateTime startedAt, diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerGetAdminMediasByIdIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerGetAdminMediasByIdIntTest.java index c21211b8623..33d77ed3942 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerGetAdminMediasByIdIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerGetAdminMediasByIdIntTest.java @@ -1,13 +1,11 @@ package uk.gov.hmcts.darts.audio.controller; +import org.hamcrest.Matchers; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import uk.gov.hmcts.darts.common.entity.HearingEntity; import uk.gov.hmcts.darts.common.entity.MediaEntity; import uk.gov.hmcts.darts.common.entity.ObjectAdminActionEntity; @@ -131,19 +129,11 @@ void shouldReturn404WhenMediaRecordDoesNotExist(SecurityRoleEnum role) throws Ex given.anAuthenticatedUserWithGlobalAccessAndRole(role); // When - MvcResult mvcResult = mockMvc.perform(get(ENDPOINT.resolve("123456789"))) + mockMvc.perform(get(ENDPOINT.resolve("123456789"))) .andExpect(status().isNotFound()) - .andReturn(); - - // Then - var jsonString = mvcResult.getResponse().getContentAsString(); - JSONAssert.assertEquals(""" - { - "type": "AUDIO_102", - "title": "The requested media cannot be found", - "status": 404 - } - """, jsonString, JSONCompareMode.STRICT); + .andExpect(jsonPath("$.type", Matchers.is("AUDIO_102"))) + .andExpect(jsonPath("$.status", Matchers.is(404))) + .andExpect(jsonPath("$.title", Matchers.is("The requested media cannot be found"))); } @ParameterizedTest @@ -153,19 +143,12 @@ void shouldDenyAccess(SecurityRoleEnum role) throws Exception { given.anAuthenticatedUserWithGlobalAccessAndRole(role); // When - MvcResult mvcResult = mockMvc.perform(get(ENDPOINT.resolve("123456789"))) + mockMvc.perform(get(ENDPOINT.resolve("123456789"))) .andExpect(status().isForbidden()) - .andReturn(); + .andExpect(jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(jsonPath("$.status", Matchers.is(403))) + .andExpect(jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); - // Then - var jsonString = mvcResult.getResponse().getContentAsString(); - JSONAssert.assertEquals(""" - { - "type": "AUTHORISATION_109", - "title": "User is not authorised for this endpoint", - "status": 403 - } - """, jsonString, JSONCompareMode.STRICT); } private MediaEntity createAndSaveMediaEntity(HearingEntity hearingEntity, UserAccountEntity userAccountEntity) { @@ -216,4 +199,4 @@ private ObjectAdminActionEntity createAndSaveAdminActionEntity(MediaEntity media .saveAndFlush(objectAdminActionEntity); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerGetAdminMediasIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerGetAdminMediasIntTest.java index d23aadfbb1e..edddfdf49f8 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerGetAdminMediasIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioControllerGetAdminMediasIntTest.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; +import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; @@ -10,6 +11,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import uk.gov.hmcts.darts.audio.enums.AudioRequestOutputFormat; import uk.gov.hmcts.darts.audio.exception.AudioApiError; import uk.gov.hmcts.darts.audio.model.GetAdminMediaResponseCase; @@ -324,17 +326,12 @@ void wrongPermissions() throws Exception { userAccountStub.givenUserIsAuthorisedJudge(userIdentity); // when - MvcResult mvcResult = mockMvc.perform(get(ENDPOINT_URL) + mockMvc.perform(get(ENDPOINT_URL) .queryParam("transformed_media_id", "1")) .andExpect(status().isForbidden()) - .andReturn(); - - // then - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"AUTHORISATION_109","title":"User is not authorised for this endpoint","status":403} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); } diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioRequestsControllerUpdateTransformedMediaLastAccessedTimestampIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioRequestsControllerUpdateTransformedMediaLastAccessedTimestampIntTest.java index 55f17119bcc..4f6f19e39c5 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioRequestsControllerUpdateTransformedMediaLastAccessedTimestampIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/AudioRequestsControllerUpdateTransformedMediaLastAccessedTimestampIntTest.java @@ -1,12 +1,12 @@ package uk.gov.hmcts.darts.audio.controller; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import uk.gov.hmcts.darts.audio.entity.MediaRequestEntity; import uk.gov.hmcts.darts.audiorequests.model.AudioRequestType; @@ -21,8 +21,6 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; -import static org.skyscreamer.jsonassert.JSONAssert.assertEquals; -import static org.skyscreamer.jsonassert.JSONCompareMode.NON_EXTENSIBLE; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -102,19 +100,11 @@ void updateTransformedMediaLastAccessedTimestampShouldReturnForbiddenErrorWhenRe MockHttpServletRequestBuilder requestBuilder = patch(ENDPOINT_URL, transformedMediaId); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isForbidden()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - { - "type":"AUDIO_REQUESTS_101", - "title":"The audio request is not valid for this user", - "status":403 - }"""; - - assertEquals(expectedJson, actualJson, NON_EXTENSIBLE); + .andExpect(jsonPath("$.type", Matchers.is("AUDIO_REQUESTS_101"))) + .andExpect(jsonPath("$.status", Matchers.is(403))) + .andExpect(jsonPath("$.title", Matchers.is("The audio request is not valid for this user"))); verify(mockAuthorisation).authoriseByTransformedMediaId( transformedMediaEntity.getId(), @@ -123,4 +113,4 @@ void updateTransformedMediaLastAccessedTimestampShouldReturnForbiddenErrorWhenRe verify(mockAuthorisation).authoriseTransformedMediaAgainstUser(transformedMediaId); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/MediaControllerPostAdminMediasSearchIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/MediaControllerPostAdminMediasSearchIntTest.java index 2ad66818429..e1c239a2007 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/MediaControllerPostAdminMediasSearchIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/audio/controller/MediaControllerPostAdminMediasSearchIntTest.java @@ -16,6 +16,7 @@ import org.springframework.test.web.servlet.MvcResult; import uk.gov.hmcts.darts.audio.model.PostAdminMediasSearchRequest; import uk.gov.hmcts.darts.audio.model.PostAdminMediasSearchResponseItem; +import uk.gov.hmcts.darts.audio.model.Problem; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; import uk.gov.hmcts.darts.common.entity.CourthouseEntity; import uk.gov.hmcts.darts.common.entity.MediaEntity; @@ -36,6 +37,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -386,16 +388,10 @@ void tooManyResults() throws Exception { .andExpect(status().is4xxClientError()) .andReturn(); - String actualResponse = TestUtils.removeTags(TAGS_TO_IGNORE, mvcResult.getResponse().getContentAsString()); - String expectedResponse = """ - { - "type": "AUDIO_116", - "title": "Too many results", - "status": 400 - }"""; - - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); - + Problem problem = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), Problem.class); + assertEquals("AUDIO_116", problem.getType().toString()); + assertEquals("Too many results", problem.getTitle()); + assertEquals(400, problem.getStatus()); } @Test @@ -410,16 +406,10 @@ void noPermissions() throws Exception { .andExpect(status().isForbidden()) .andReturn(); - String actualResponse = TestUtils.removeTags(TAGS_TO_IGNORE, mvcResult.getResponse().getContentAsString()); - String expectedResponse = """ - { - "type": "AUTHORISATION_109", - "title": "User is not authorised for this endpoint", - "status": 403 - }"""; - - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); - + Problem problem = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), Problem.class); + assertEquals("AUTHORISATION_109", problem.getType().toString()); + assertEquals("User is not authorised for this endpoint", problem.getTitle()); + assertEquals(403, problem.getStatus()); } } \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/authentication/controller/impl/HandleOAuthCodeIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/authentication/controller/impl/HandleOAuthCodeIntTest.java index 723fca5a3cf..20bf8161754 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/authentication/controller/impl/HandleOAuthCodeIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/authentication/controller/impl/HandleOAuthCodeIntTest.java @@ -12,14 +12,12 @@ import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import lombok.SneakyThrows; +import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import uk.gov.hmcts.darts.authorisation.api.AuthorisationApi; import uk.gov.hmcts.darts.authorisation.model.UserState; @@ -126,22 +124,12 @@ void handleOAuthCodeShouldReturnErrorResponseWhenAccessTokenMissingEmailsClaim() KeyPair keyPair = setTokenStub(Collections.emptyList()); setKeyStoreStub(keyPair); - MvcResult response = mockMvc.perform(MockMvcRequestBuilders.post( + mockMvc.perform(MockMvcRequestBuilders.post( EXTERNAL_USER_HANDLE_OAUTH_CODE_ENDPOINT_WITH_CODE)) .andExpect(status().isInternalServerError()) - .andReturn(); - - String actualResponseBody = response.getResponse().getContentAsString(); - - String expectedResponseBody = """ - { - "type":"AUTHENTICATION_101", - "title":"Failed to validate access token", - "status":500 - } - """; - - JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(jsonPath("$.type", Matchers.is("AUTHENTICATION_101"))) + .andExpect(jsonPath("$.status", Matchers.is(500))) + .andExpect(jsonPath("$.title", Matchers.is("Failed to validate access token"))); verifyNoInteractions(mockAuthorisationApi); } @@ -155,44 +143,24 @@ void handleOAuthCodeShouldReturnErrorResponseWhenDownstreamCallToAzureFails() th ) ); - MvcResult response = mockMvc.perform(MockMvcRequestBuilders.post( + mockMvc.perform(MockMvcRequestBuilders.post( EXTERNAL_USER_HANDLE_OAUTH_CODE_ENDPOINT_WITH_CODE)) .andExpect(status().isInternalServerError()) - .andReturn(); - - String actualResponseBody = response.getResponse().getContentAsString(); - - String expectedResponseBody = """ - { - "type":"AUTHENTICATION_100", - "title":"Failed to obtain access token", - "status":500 - } - """; - - JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(jsonPath("$.type", Matchers.is("AUTHENTICATION_100"))) + .andExpect(jsonPath("$.status", Matchers.is(500))) + .andExpect(jsonPath("$.title", Matchers.is("Failed to obtain access token"))); } @Test void handleOAuthCodeShouldReturnErrorResponseWhenTokenValidationFails() throws Exception { setTokenStub(List.of(VALID_EMAIL_VALUE)); - MvcResult response = mockMvc.perform(MockMvcRequestBuilders.post( + mockMvc.perform(MockMvcRequestBuilders.post( EXTERNAL_USER_HANDLE_OAUTH_CODE_ENDPOINT_WITH_CODE)) .andExpect(status().isInternalServerError()) - .andReturn(); - - String actualResponseBody = response.getResponse().getContentAsString(); - - String expectedResponseBody = """ - { - "type":"AUTHENTICATION_101", - "title":"Failed to validate access token", - "status":500 - } - """; - - JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(jsonPath("$.type", Matchers.is("AUTHENTICATION_101"))) + .andExpect(jsonPath("$.status", Matchers.is(500))) + .andExpect(jsonPath("$.title", Matchers.is("Failed to validate access token"))); } /** diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/cases/controller/CaseControllerGetCaseHearingsTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/cases/controller/CaseControllerGetCaseHearingsTest.java index 00445994211..b26a1c087ee 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/cases/controller/CaseControllerGetCaseHearingsTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/cases/controller/CaseControllerGetCaseHearingsTest.java @@ -3,13 +3,10 @@ import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; @@ -69,14 +66,10 @@ void casesSearchGetEndpointShouldReturnForbidden() throws Exception { MockHttpServletRequestBuilder requestBuilder = get(endpointUrl, hearingEntity.getCourtCase().getId()); - MvcResult response = mockMvc.perform(requestBuilder).andExpect(status().isForbidden()).andReturn(); - - String actualResponse = response.getResponse().getContentAsString(); - - String expectedResponse = """ - {"type":"AUTHORISATION_106","title":"Could not obtain user details","status":403} - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + mockMvc.perform(requestBuilder) + .andExpect(status().isForbidden()) + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_106"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Could not obtain user details"))); } @Test @@ -160,4 +153,4 @@ void casesSearchEmptyHearingListCaseIdExists() throws Exception { } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/cases/controller/CaseControllerTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/cases/controller/CaseControllerTest.java index c27a76df57c..827346608bd 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/cases/controller/CaseControllerTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/cases/controller/CaseControllerTest.java @@ -181,12 +181,23 @@ void casesPostCaseNumberMissing() throws Exception { .contentType(MediaType.APPLICATION_JSON_VALUE) .content(getContentsFromFile( "tests/cases/CaseControllerTest/casesPostEndpoint/requestBodyCaseNumberMissing.json")); - MvcResult response = mockMvc.perform(requestBuilder).andExpect(status().isBadRequest()).andReturn(); + MvcResult response = mockMvc.perform(requestBuilder).andExpect(status().isBadRequest()) + .andReturn(); String actualResponse = response.getResponse().getContentAsString(); - String expectedResponse = getContentsFromFile( - "tests/cases/CaseControllerTest/casesPostEndpoint/expectedResponseCaseNumberMissing_400.json"); + String expectedResponse = """ + { + "type":"about:blank", + "title":"Constraint Violation", + "status":400, + "detail":"", + "instance":"/cases", + "properties":{ + "caseNumber":"must not be null" + } + } + """; assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); } @@ -200,8 +211,19 @@ void casesPostCourthouseMissing() throws Exception { String actualResponse = response.getResponse().getContentAsString(); - String expectedResponse = getContentsFromFile( - "tests/cases/CaseControllerTest/casesPostEndpoint/expectedResponseCourthouseMissing_400.json"); + String expectedResponse = """ + { + "type":"about:blank", + "title":"Constraint Violation", + "status":400, + "detail":"", + "instance":"/cases", + "properties":{ + "courthouse":"must not be null" + } + } + """; + assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); } @@ -269,4 +291,4 @@ private void setupExternalDarPcUserForCourthouse(CourthouseEntity courthouse) { when(mockUserIdentity.getUserAccount()).thenReturn(testUser); when(mockUserIdentity.userHasGlobalAccess(Set.of(DAR_PC))).thenReturn(true); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/common/controller/CourthouseApiTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/common/controller/CourthouseApiTest.java index 8062dd762bb..0b20cd9c79b 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/common/controller/CourthouseApiTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/common/controller/CourthouseApiTest.java @@ -739,10 +739,8 @@ void courthousesPostShouldFailIfMissingCourthouseName() throws Exception { mockMvc.perform(requestBuilder) // Then .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.type").value("https://zalando.github.io/problem/constraint-violation")) .andExpect(jsonPath("$.title").value("Constraint Violation")) - .andExpect(jsonPath("$.violations.*.field").value("courthouseName")) - .andExpect(jsonPath("$.violations.*.message").value("must not be null")); + .andExpect(jsonPath("$.properties.courthouseName").value("must not be null")); } @Test @@ -765,10 +763,8 @@ void courthousesPostShouldFailIfMissingDisplayName() throws Exception { mockMvc.perform(requestBuilder) // Then .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.type").value("https://zalando.github.io/problem/constraint-violation")) .andExpect(jsonPath("$.title").value("Constraint Violation")) - .andExpect(jsonPath("$.violations.*.field").value("displayName")) - .andExpect(jsonPath("$.violations.*.message").value("must not be null")); + .andExpect(jsonPath("$.properties.displayName").value("must not be null")); } @Test @@ -859,5 +855,4 @@ private String getGuidFromToken() { return null; } -} - +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/common/controller/HiddenReasonApiTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/common/controller/HiddenReasonApiTest.java index 32cad3f3785..782c3dfee69 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/common/controller/HiddenReasonApiTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/common/controller/HiddenReasonApiTest.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.darts.common.controller; +import org.hamcrest.Matchers; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.skyscreamer.jsonassert.JSONAssert; @@ -8,6 +9,7 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import uk.gov.hmcts.darts.common.enums.SecurityRoleEnum; import uk.gov.hmcts.darts.testutils.GivenBuilder; import uk.gov.hmcts.darts.testutils.IntegrationBase; @@ -88,19 +90,11 @@ void shouldDenyAccess(SecurityRoleEnum role) throws Exception { given.anAuthenticatedUserWithGlobalAccessAndRole(role); // When - MvcResult mvcResult = mockMvc.perform(get(ENDPOINT)) + mockMvc.perform(get(ENDPOINT)) .andExpect(status().isForbidden()) - .andReturn(); - - // Then - var jsonString = mvcResult.getResponse().getContentAsString(); - JSONAssert.assertEquals(""" - { - "type": "AUTHORISATION_109", - "title": "User is not authorised for this endpoint", - "status": 403 - } - """, jsonString, JSONCompareMode.STRICT); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/common/exception/ExceptionHandlerTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/common/exception/ExceptionHandlerTest.java index 93f92ca7123..4bcec732ee9 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/common/exception/ExceptionHandlerTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/common/exception/ExceptionHandlerTest.java @@ -80,7 +80,8 @@ void shouldReturnRfc7807ResponseWhenADartsApiExceptionIsThrown() throws Exceptio { "type":"TEST_999", "title":"A descriptive title", - "status":418 + "status":418, + "instance": "/test" } """; @@ -104,7 +105,8 @@ void shouldReturnRfc7807ResponseWithDetailFieldPopulatedWhenADartsApiExceptionIs "type":"TEST_999", "title":"A descriptive title", "status":418, - "detail":"Some descriptive details" + "detail":"Some descriptive details", + "instance": "/test" } """; @@ -124,13 +126,15 @@ void shouldReturnAGenericRfc7807ResponseWhenARuntimeExceptionIsThrown() throws E String expectedResponseBody = """ { + "type":"about:blank", "title":"Internal Server Error", "status":500, - "detail":"A runtime exception occurred" + "detail":"A runtime exception occurred", + "instance": "/test" } """; JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, JSONCompareMode.NON_EXTENSIBLE); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/dailylist/controller/DailyListPostControllerTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/dailylist/controller/DailyListPostControllerTest.java index d6a6792887e..f5267e0a842 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/dailylist/controller/DailyListPostControllerTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/dailylist/controller/DailyListPostControllerTest.java @@ -40,7 +40,8 @@ class DailyListPostControllerTest extends IntegrationBase { private SuperAdminUserStub superAdminUserStub; private static String getExpectedResponse() { - return "{\"type\":\"DAILYLIST_101\",\"title\":\"Either xml_document or json_document or both needs to be provided.\",\"status\":400}"; + return "{\"type\":\"DAILYLIST_101\",\"title\":\"Either xml_document " + + "or json_document or both needs to be provided.\",\"status\":400,\"instance\":\"/dailylists\"}"; } @Test @@ -111,8 +112,10 @@ void shouldFailPostDailyListWhenValidXmlAndEmptySourceSystem() throws Exception String uniqueId = "func-unique-id-" + randomAlphanumeric(7); String messageId = "func-unique-id-" + randomAlphanumeric(7); - final String expectedResponse = "{\"type\":\"DAILYLIST_105\",\"title\":\"Invalid source system. Should be CPP or XHB.\",\"status\":400}"; - final String jsonPostRequest = getContentsFromFile("tests/DailyListTest/dailyListAddDailyListEndpoint/requestBody.json"); + final String expectedResponse = + "{\"type\":\"DAILYLIST_105\",\"title\":\"Invalid source system. Should be CPP or XHB.\",\"status\":400,\"instance\":\"/dailylists\"}"; + final String jsonPostRequest = + getContentsFromFile("tests/DailyListTest/dailyListAddDailyListEndpoint/requestBody.json"); PostDailyListRequest request = new PostDailyListRequest(); @@ -178,7 +181,8 @@ void shouldFailValidationForPostDailyListWhenValidXmlAndSourceSystemInvalid() th String uniqueId = "func-unique-id-" + randomAlphanumeric(7); String messageId = "func-unique-id-" + randomAlphanumeric(7); - final String expectedResponse = "{\"type\":\"DAILYLIST_105\",\"title\":\"Invalid source system. Should be CPP or XHB.\",\"status\":400}"; + final String expectedResponse = "{\"type\":\"DAILYLIST_105\",\"title\":\"Invalid " + + "source system. Should be CPP or XHB.\",\"status\":400,\"instance\":\"/dailylists\"}"; final String jsonPostRequest = getContentsFromFile("tests/DailyListTest/dailyListAddDailyListEndpoint/requestBody.json"); @@ -234,5 +238,4 @@ void shouldSuccessfullyPostDailyListWhenValidJsonAndNoSourceSystem() throws Exce .andExpect(jsonPath("$.dal_id").value(isA(Integer.class))); } -} - +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventControllerDeleteEventMappingTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventControllerDeleteEventMappingTest.java index 02d39d5f57b..644ab994227 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventControllerDeleteEventMappingTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventControllerDeleteEventMappingTest.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.darts.event.controller; +import org.hamcrest.Matchers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -11,6 +12,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import uk.gov.hmcts.darts.audit.api.AuditActivity; import uk.gov.hmcts.darts.common.entity.AuditEntity; import uk.gov.hmcts.darts.common.entity.EventEntity; @@ -64,21 +66,11 @@ void wrongPermission(SecurityRoleEnum role) throws Exception { given.anAuthenticatedUserWithGlobalAccessAndRole(role); var entity = dartsDatabase.createEventHandlerData("8888"); MockHttpServletRequestBuilder requestBuilder = delete(EVENT_MAPPINGS_ENDPOINT, entity.getId()); - MvcResult response = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isForbidden()) - .andReturn(); - - String actualResponse = response.getResponse().getContentAsString(); - - String expectedResponse = """ - { - "type": "AUTHORISATION_109", - "title": "User is not authorised for this endpoint", - "status": 403 - } - """; - - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); } @Test @@ -88,25 +80,15 @@ void mappingInactive() throws Exception { entity.setActive(false); dartsDatabase.save(entity); MockHttpServletRequestBuilder requestBuilder = delete(EVENT_MAPPINGS_ENDPOINT, entity.getId()); - MvcResult response = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isConflict()) - .andReturn(); - - String actualResponse = response.getResponse().getContentAsString(); - - String expectedResponse = """ - { - "type": "EVENT_105", - "title": "The mapping is inactive, so cannot be deleted", - "status": 409, - "detail": "Event handler mapping %s cannot be deleted because it is inactive." - } - """.formatted(entity.getId()); - - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.STRICT); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("EVENT_105"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(409))) + .andExpect(MockMvcResultMatchers.jsonPath("$.detail", Matchers.is(("Event handler " + + "mapping %s cannot be deleted because it is inactive.").formatted(entity.getId())))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The mapping is inactive, so cannot be deleted"))); } - @Test void mappingHasEvents() throws Exception { given.anAuthenticatedUserWithGlobalAccessAndRole(SUPER_ADMIN); @@ -115,25 +97,14 @@ void mappingHasEvents() throws Exception { EventEntity event = dartsDatabase.createEvent(hearing); MockHttpServletRequestBuilder requestBuilder = delete(EVENT_MAPPINGS_ENDPOINT, event.getEventType().getId()); - MvcResult response = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isConflict()) - .andReturn(); - - String actualResponse = response.getResponse().getContentAsString(); - - String expectedResponse = """ - { - "type": "EVENT_106", - "title": "The mapping has already processed events, so cannot be deleted", - "status": 409, - "detail": "Event handler mapping 10 already has processed events, so cannot be deleted." - } - """; - - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("EVENT_106"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(409))) + .andExpect(MockMvcResultMatchers.jsonPath("$.detail", Matchers.is("Event handler mapping 10 already has processed events, so cannot be deleted."))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The mapping has already processed events, so cannot be deleted"))); } - @Test void mappingDoesNotExist() throws Exception { given.anAuthenticatedUserWithGlobalAccessAndRole(SUPER_ADMIN); @@ -150,7 +121,8 @@ void mappingDoesNotExist() throws Exception { "type":"EVENT_101", "title": "No event handler mapping found in database", "status": 404, - "detail": "No event handler could be found in the database for event handler id: -1." + "detail": "No event handler could be found in the database for event handler id: -1.", + "instance":"/admin/event-mappings/-1" } """; diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventControllerGetEventMappingByIdTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventControllerGetEventMappingByIdTest.java index 7588791753e..9c4203c40b6 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventControllerGetEventMappingByIdTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventControllerGetEventMappingByIdTest.java @@ -4,12 +4,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import uk.gov.hmcts.darts.common.entity.HearingEntity; import uk.gov.hmcts.darts.common.enums.SecurityRoleEnum; @@ -108,22 +105,12 @@ void eventMappingsEndpointShouldReturn404ErrorWhenEventMappingDoesNotExist() thr MockHttpServletRequestBuilder requestBuilder = get(EVENT_MAPPINGS_ENDPOINT, 1_000_099); - MvcResult response = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isNotFound()) - .andReturn(); - - String actualResponse = response.getResponse().getContentAsString(); - - String expectedResponse = """ - { - "type":"EVENT_101", - "title": "No event handler mapping found in database", - "status": 404, - "detail": "No event handler could be found in the database for event handler id: 1000099." - } - """; - - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(jsonPath("$.type", Matchers.is("EVENT_101"))) + .andExpect(jsonPath("$.status", Matchers.is(404))) + .andExpect( + jsonPath("$.detail", Matchers.is("No event handler could be found in the database for event handler id: 1000099."))) + .andExpect(jsonPath("$.title", Matchers.is("No event handler mapping found in database"))); } - -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventsControllerCourtLogsTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventsControllerCourtLogsTest.java index ca3c837f50f..9e9dc455bf8 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventsControllerCourtLogsTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/event/controller/EventsControllerCourtLogsTest.java @@ -4,14 +4,11 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; @@ -281,17 +278,11 @@ void courtLogsEndpointShouldReturnForbiddenError() throws Exception { .queryParam(END_DATE_TIME, "2024-07-01T12:00:00+01") .contentType(MediaType.APPLICATION_JSON_VALUE); - MvcResult response = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isForbidden()) - .andReturn(); - - String actualResponse = response.getResponse().getContentAsString(); - - String expectedResponse = """ - {"type":"AUTHORISATION_109","title":"User is not authorised for this endpoint","status":403} - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); - + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); } private void setupExternalUserForCourthouse(CourthouseEntity courthouse) { @@ -305,4 +296,4 @@ private void setupExternalMidTierUserForCourthouse(CourthouseEntity courthouse) when(mockUserIdentity.getUserAccount()).thenReturn(testUser); when(mockUserIdentity.userHasGlobalAccess(Set.of(MID_TIER))).thenReturn(true); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/hearings/controller/HearingsGetControllerTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/hearings/controller/HearingsGetControllerTest.java index d26eeec027b..1ab9f7c076d 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/hearings/controller/HearingsGetControllerTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/hearings/controller/HearingsGetControllerTest.java @@ -1,6 +1,7 @@ package uk.gov.hmcts.darts.hearings.controller; import lombok.extern.slf4j.Slf4j; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; @@ -104,14 +105,16 @@ void errorGetNotFound() throws Exception { int hearingId = -1; MockHttpServletRequestBuilder requestBuilder = get(ENDPOINT_URL, hearingId); - MvcResult mvcResult = mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isNotFound()).andReturn(); + MvcResult mvcResult = mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isNotFound()) + .andReturn(); String actualJson = mvcResult.getResponse().getContentAsString(); String expectedJson = """ { "type": "HEARING_100", "title": "The requested hearing cannot be found", - "status": 404 + "status": 404, + "instance": "/hearings/-1" } """; @@ -137,16 +140,11 @@ void hearingsGetEndpointShouldReturnForbiddenError() throws Exception { MockHttpServletRequestBuilder requestBuilder = get(ENDPOINT_URL, hearing.getId()); - MvcResult response = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isForbidden()) - .andReturn(); - - String actualResponse = response.getResponse().getContentAsString(); - - String expectedResponse = """ - {"type":"AUTHORISATION_106","title":"Could not obtain user details","status":403} - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_106"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Could not obtain user details"))); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/hearings/controller/HearingsGetEventsControllerTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/hearings/controller/HearingsGetEventsControllerTest.java index 6d7fc2d908d..93cbe4f9929 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/hearings/controller/HearingsGetEventsControllerTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/hearings/controller/HearingsGetEventsControllerTest.java @@ -1,6 +1,7 @@ package uk.gov.hmcts.darts.hearings.controller; import lombok.extern.slf4j.Slf4j; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; @@ -91,17 +92,10 @@ void errorGetNotFound() throws Exception { int hearingId = -1; MockHttpServletRequestBuilder requestBuilder = get(ENDPOINT_URL, hearingId); - MvcResult mvcResult = mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isNotFound()).andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - { - "type": "HEARING_100", - "title": "The requested hearing cannot be found", - "status": 404 - } - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isNotFound()) + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("HEARING_100"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(404))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The requested hearing cannot be found"))); } @@ -111,16 +105,10 @@ void hearingEventsGetEndpointShouldReturnForbiddenError() throws Exception { when(mockUserIdentity.getUserAccount()).thenReturn(null); MockHttpServletRequestBuilder requestBuilder = get(ENDPOINT_URL, hearingEntity.getId()); - MvcResult response = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isForbidden()) - .andReturn(); - - String actualResponse = response.getResponse().getContentAsString(); - - String expectedResponse = """ - {"type":"AUTHORISATION_106","title":"Could not obtain user details","status":403} - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); - + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_106"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Could not obtain user details"))); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerCreateRetentionPolicyTypeIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerCreateRetentionPolicyTypeIntTest.java index 87aca0e0cd4..aa0783eb0cd 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerCreateRetentionPolicyTypeIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerCreateRetentionPolicyTypeIntTest.java @@ -264,10 +264,9 @@ void createRetentionPolicyTypeShouldFailWhenLongDescriptionIsProvided() throws E // Then resultActions .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.type").value("https://zalando.github.io/problem/constraint-violation")) + .andExpect(jsonPath("$.type").value("about:blank")) .andExpect(jsonPath("$.title").value("Constraint Violation")) - .andExpect(jsonPath("$.violations.*.field").value("description")) - .andExpect(jsonPath("$.violations.*.message").value("size must be between 0 and 256")); + .andExpect(jsonPath("$.properties.description").value("size must be between 0 and 256")); } @Test @@ -298,10 +297,9 @@ void createRetentionPolicyTypeShouldFailWhenDurationFormatIsIncorrect() throws E // Then resultActions .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.type").value("https://zalando.github.io/problem/constraint-violation")) + .andExpect(jsonPath("$.type").value("about:blank")) .andExpect(jsonPath("$.title").value("Constraint Violation")) - .andExpect(jsonPath("$.violations.*.field").value("duration")) - .andExpect(jsonPath("$.violations.*.message").value("must match \"^\\d{1,2}Y\\d{1,2}M\\d{1,2}D$\"")); + .andExpect(jsonPath("$.properties.duration").value("must match \"^\\d{1,2}Y\\d{1,2}M\\d{1,2}D$\"")); } @Test @@ -334,7 +332,7 @@ void createRetentionPolicyTypeShouldFailWhenDurationIsTooShort() throws Exceptio .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.type").value("RETENTION_111")) .andExpect(jsonPath("$.title").value("Duration too short")) - .andExpect(jsonPath("$.min_allowable_days").value(1)); + .andExpect(jsonPath("$.properties.min_allowable_days").value(1)); } @Test @@ -404,4 +402,4 @@ private void clearCreatedRetentionPolicyTypes() { .toList()); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerGetPolicyByIdTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerGetPolicyByIdTest.java index 99d630cc419..ba6f9022870 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerGetPolicyByIdTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerGetPolicyByIdTest.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.darts.retention.controller; +import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; @@ -8,6 +9,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; import uk.gov.hmcts.darts.testutils.IntegrationBase; import uk.gov.hmcts.darts.testutils.stubs.SuperAdminUserStub; @@ -59,28 +61,11 @@ void shouldFailToGetRetentionPoliciesForInvalidId() throws Exception { superAdminUserStub.givenUserIsAuthorised(mockUserIdentity); - var requestBuilder = get(RETENTION_POLICY_TYPE_URL,45); - - MvcResult mvcResult = mockMvc.perform(requestBuilder).andExpect(status().isNotFound()).andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - { - "type": "RETENTION_108", - "title": "The retention policy type id does not exist.", - "status": 404 - } - """; - - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); - + var requestBuilder = get(RETENTION_POLICY_TYPE_URL, 45); + mockMvc.perform(requestBuilder).andExpect(status().isNotFound()) + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("RETENTION_108"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(404))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The retention policy type id does not exist."))); } - - - - - -} - - +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerPatchRetentionPolicyTypeIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerPatchRetentionPolicyTypeIntTest.java index f8d03404ad6..d82c2c05e47 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerPatchRetentionPolicyTypeIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerPatchRetentionPolicyTypeIntTest.java @@ -742,10 +742,8 @@ void patchRetentionPolicyTypeShouldFailWhenDurationIsChangedToInvalidValue() thr // Then resultActions .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.type").value("https://zalando.github.io/problem/constraint-violation")) .andExpect(jsonPath("$.title").value("Constraint Violation")) - .andExpect(jsonPath("$.violations.*.field").value("duration")) - .andExpect(jsonPath("$.violations.*.message").value("must match \"^\\d{1,2}Y\\d{1,2}M\\d{1,2}D$\"")); + .andExpect(jsonPath("$.properties.duration").value("must match \"^\\d{1,2}Y\\d{1,2}M\\d{1,2}D$\"")); } @Test @@ -772,7 +770,7 @@ void patchRetentionPolicyTypeShouldFailWhenDurationIsTooShort() throws Exception .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.type").value("RETENTION_111")) .andExpect(jsonPath("$.title").value("Duration too short")) - .andExpect(jsonPath("$.min_allowable_days").value(1)); + .andExpect(jsonPath("$.properties.min_allowable_days").value(1)); } @Test @@ -800,10 +798,8 @@ void patchRetentionPolicyTypeShouldFailWhenLongDescriptionIsProvided() throws Ex // Then resultActions .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.type").value("https://zalando.github.io/problem/constraint-violation")) .andExpect(jsonPath("$.title").value("Constraint Violation")) - .andExpect(jsonPath("$.violations.*.field").value("description")) - .andExpect(jsonPath("$.violations.*.message").value("size must be between 0 and 256")); + .andExpect(jsonPath("$.properties.description").value("size must be between 0 and 256")); } @Test @@ -841,7 +837,7 @@ void patchRetentionPolicyTypeShouldFailWhenFixedPolicyKeyIsChangedAndTargetKeyHa .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.type").value("RETENTION_117")) .andExpect(jsonPath("$.title").value("Target policy has pending revision")) - .andExpect(jsonPath("$.pending_revision_id").value(pendingPolicy200.getId())); + .andExpect(jsonPath("$.properties.pending_revision_id").value(pendingPolicy200.getId())); } @Test @@ -903,4 +899,4 @@ private void clearCreatedRetentionPolicyTypes() { .toList()); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerPostRetentionIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerPostRetentionIntTest.java index e1d4db5db95..f3a5a62986b 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerPostRetentionIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/retention/controller/RetentionControllerPostRetentionIntTest.java @@ -213,7 +213,7 @@ void givenARetentionDateEarlierThanLastAutomatedThenThrow422() throws Exception + "' must have a retention date after the last completed automated retention date '2024-01-01'.") )) .andExpect(jsonPath( - "latest_automated_retention_date", + "properties.latest_automated_retention_date", is("2024-01-01") )); } @@ -256,9 +256,9 @@ void givenARetentionDateLaterThanMaxRetentionThenThrow422() throws Exception { + "' must have a retention date before the maximum retention date '2119-10-10'.") )) .andExpect(jsonPath( - "max_duration", + "properties.max_duration", is("99Y0M0D") )); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/testutils/IntegrationBase.java b/src/integrationTest/java/uk/gov/hmcts/darts/testutils/IntegrationBase.java index 6501835a90f..9f38db1ec71 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/testutils/IntegrationBase.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/testutils/IntegrationBase.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.darts.testutils; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -55,6 +56,8 @@ static void configureProperties(DynamicPropertyRegistry registry) { @BeforeEach void clearDb() { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + dartsDatabase.clearDatabaseInThisOrder(); } diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerAttachTranscriptIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerAttachTranscriptIntTest.java index 8f983097714..35348fb65c6 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerAttachTranscriptIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerAttachTranscriptIntTest.java @@ -2,10 +2,9 @@ import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -13,6 +12,7 @@ import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import uk.gov.hmcts.darts.audit.api.AuditApi; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; @@ -137,20 +137,15 @@ void attachTranscriptShouldReturnForbiddenError() throws Exception { "Test Document (doc)".getBytes() ); - final MvcResult mvcResult = mockMvc.perform( + mockMvc.perform( multipart( URL_TEMPLATE, transcriptionId ).file(transcript)) .andExpect(status().isForbidden()) - .andReturn(); - - String actualResponse = mvcResult.getResponse().getContentAsString(); - - String expectedResponse = """ - {"type":"AUTHORISATION_106","title":"Could not obtain user details","status":403} - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_106"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Could not obtain user details"))); verifyNoInteractions(mockAuditApi); } @@ -166,20 +161,15 @@ void attachTranscriptShouldReturnBadRequestErrorWithFileExtensionTypeBlocked() t "Test Document (txt)".getBytes() ); - final MvcResult mvcResult = mockMvc.perform( + mockMvc.perform( multipart( URL_TEMPLATE, transcriptionId ).file(transcript)) .andExpect(status().isBadRequest()) - .andReturn(); - - String actualResponse = mvcResult.getResponse().getContentAsString(); - - String expectedResponse = """ - {"type":"TRANSCRIPTION_108","title":"Failed to attach transcript","status":400} - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_108"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(400))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Failed to attach transcript"))); verifyNoInteractions(mockAuditApi); } @@ -196,20 +186,15 @@ void attachTranscriptShouldReturnBadRequestErrorWithFileSizeLimitExceeded() thro "Test Document exceeding max configured doc size(doc)".getBytes() ); - final MvcResult mvcResult = mockMvc.perform( + mockMvc.perform( multipart( URL_TEMPLATE, transcriptionId ).file(transcript)) .andExpect(status().isBadRequest()) - .andReturn(); - - String actualResponse = mvcResult.getResponse().getContentAsString(); - - String expectedResponse = """ - {"type":"TRANSCRIPTION_108","title":"Failed to attach transcript","status":400} - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_108"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(400))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Failed to attach transcript"))); verifyNoInteractions(mockAuditApi); } @@ -367,4 +352,4 @@ void attachTranscriptShouldReturnOkWithMicrosoftWordOld() throws Exception { verify(mockAuditApi).record(IMPORT_TRANSCRIPTION, authorisationStub.getSeparateIntegrationUser(), transcriptionEntity.getCourtCase()); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerDownloadTranscriptIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerDownloadTranscriptIntTest.java index a96e99d4721..37709e2d38f 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerDownloadTranscriptIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerDownloadTranscriptIntTest.java @@ -1,17 +1,16 @@ package uk.gov.hmcts.darts.transcriptions.controller; import org.apache.commons.io.IOUtils; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import uk.gov.hmcts.darts.audit.api.AuditApi; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; @@ -138,16 +137,11 @@ void downloadTranscriptShouldReturnForbiddenError() throws Exception { "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isForbidden()) - .andReturn(); - - String actualResponse = mvcResult.getResponse().getContentAsString(); - - String expectedResponse = """ - {"type":"AUTHORISATION_106","title":"Could not obtain user details","status":403} - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_106"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Could not obtain user details"))); verifyNoInteractions(mockAuditApi); } @@ -160,16 +154,12 @@ void downloadTranscriptShouldReturnNotFoundError() throws Exception { "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ); - MvcResult mvcResult = mockMvc.perform(requestBuilder) - .andExpect(status().isNotFound()) - .andReturn(); - String actualResponse = mvcResult.getResponse().getContentAsString(); - - String expectedResponse = """ - {"type":"TRANSCRIPTION_101","title":"The requested transcription cannot be found","status":404} - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + mockMvc.perform(requestBuilder) + .andExpect(status().isNotFound()) + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_101"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(404))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The requested transcription cannot be found"))); verifyNoInteractions(mockAuditApi); } @@ -284,4 +274,4 @@ void downloadTranscriptShouldReturnOkWithMicrosoftWordOld() throws Exception { verifyNoMoreInteractions(mockAuditApi, mockDataManagementFacade, mockFileBasedDownloadResponseMetaData); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriberTranscriptsIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriberTranscriptsIntTest.java index 20e52d12d57..f533ea3f2e0 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriberTranscriptsIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriberTranscriptsIntTest.java @@ -65,11 +65,8 @@ void givenAssignedQueryParamOnly_thenReturnBadRequest() throws Exception { String actualResponse = mvcResult.getResponse().getContentAsString(); String expectedResponse = """ - { - "title": "Bad Request", - "status": 400, - "detail": "Required request header 'user_id' for method parameter type Integer is not present" - } + {"type":"about:blank","title":"Bad Request","status":400,"detail": + "Required header 'user_id' is not present.","instance":"/transcriptions/transcriber-view"} """; JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); } @@ -88,11 +85,8 @@ void givenUserIdHeaderOnly_thenReturnBadRequest() throws Exception { String actualResponse = mvcResult.getResponse().getContentAsString(); String expectedResponse = """ - { - "title": "Bad Request", - "status": 400, - "detail": "Required request parameter 'assigned' for method parameter type Boolean is not present" - } + {"type":"about:blank","title":"Bad Request","status":400,"detail": + "Required parameter 'assigned' is not present.","instance":"/transcriptions/transcriber-view"} """; JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); } diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionTest.java index 17dfe176dc3..43ce7ce46fe 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionTest.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.darts.transcriptions.controller; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; @@ -10,6 +11,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; import uk.gov.hmcts.darts.common.entity.CourthouseEntity; import uk.gov.hmcts.darts.common.entity.CourtroomEntity; @@ -259,11 +261,11 @@ void getTranscriptionNoUrgency() throws Exception { @Test void getTranscriptionNotFound() throws Exception { MockHttpServletRequestBuilder requestBuilder = get(ENDPOINT_URL_TRANSCRIPTION, -999); - MvcResult response = mockMvc.perform(requestBuilder).andExpect(status().isNotFound()).andReturn(); - String actualResponse = response.getResponse().getContentAsString(); - String expectedResponse = getContentsFromFile("tests/transcriptions/transcription/expectedResponseNotFound.json"); - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); - } + mockMvc.perform(requestBuilder).andExpect(status().isNotFound()) + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_101"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(404))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The requested transcription cannot be found"))); + } private void addCommentToWorkflow(TranscriptionWorkflowEntity workflowEntity, String comment, UserAccountEntity userAccount) { TranscriptionCommentEntity commentEntity = new TranscriptionCommentEntity(); diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionTranscriberCountsIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionTranscriberCountsIntTest.java index 8cc48ff5c22..13ed3fa7a1d 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionTranscriberCountsIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionTranscriberCountsIntTest.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.darts.transcriptions.controller; +import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -11,6 +12,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import uk.gov.hmcts.darts.testutils.IntegrationBase; import java.net.URI; @@ -161,19 +163,11 @@ void getTranscriberCountsShouldReturnForbiddenWhenUserNotTranscriber() throws Ex -20 ); - final MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isForbidden()) - .andReturn(); - - String actualResponse = mvcResult.getResponse().getContentAsString(); - String expectedResponse = """ - { - "type":"USER_NOT_TRANSCRIBER_113", - "title":"User is not a transcriber user", - "status":403 - } - """; - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("USER_NOT_TRANSCRIBER_113"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("User is not a transcriber user"))); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionWorkflowsIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionWorkflowsIntTest.java index d4ad874d16b..f62116b222f 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionWorkflowsIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerGetTranscriptionWorkflowsIntTest.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.darts.transcriptions.controller; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; @@ -10,6 +11,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; import uk.gov.hmcts.darts.common.entity.CourthouseEntity; import uk.gov.hmcts.darts.common.entity.HearingEntity; @@ -135,7 +137,8 @@ void getTranscriptionMissingMandatoryFieldShouldThrow400Error() throws Exception MvcResult response = mockMvc.perform(requestBuilder).andExpect(status().isBadRequest()).andReturn(); String actualResponse = response.getResponse().getContentAsString(); String expectedResponse = """ - {"title":"Bad Request","status":400,"detail":"Required request parameter 'transcription_id' for method parameter type Integer is not present"} + {"type":"about:blank","title":"Bad Request","status":400,"detail": + "Required parameter 'transcription_id' is not present.","instance":"/admin/transcription-workflows"} """; JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); @@ -149,12 +152,9 @@ void getTranscriptionWorkflowAsNonSuperUserShouldThrow403Error() throws Exceptio .queryParam("transcription_id", "-100") .queryParam("is_current", "true"); - MvcResult response = mockMvc.perform(requestBuilder).andExpect(status().isForbidden()).andReturn(); - String actualResponse = response.getResponse().getContentAsString(); - String expectedResponse = """ - {"type":"AUTHORISATION_109","title":"User is not authorised for this endpoint","status":403} - """; - - JSONAssert.assertEquals(expectedResponse, actualResponse, JSONCompareMode.NON_EXTENSIBLE); + mockMvc.perform(requestBuilder).andExpect(status().isForbidden()) + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerRequestTranscriptionIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerRequestTranscriptionIntTest.java index 690a51b3a1c..7ebc2cb0048 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerRequestTranscriptionIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerRequestTranscriptionIntTest.java @@ -5,8 +5,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; @@ -90,17 +88,6 @@ class TranscriptionControllerRequestTranscriptionIntTest extends IntegrationBase private HearingEntity hearing; private UserAccountEntity testUser; - private static void assertTranscriptionFailed100Error(String actualJson) { - String expectedJson = """ - { - "type": "TRANSCRIPTION_100", - "title": "Failed to validate transcription request", - "status": 400 - }"""; - - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); - } - @BeforeEach void setupData() { authorisationStub.givenTestSchema(); @@ -207,7 +194,7 @@ void transcriptionRequestWithDuplicateValues() throws Exception { mockMvc.perform(requestBuilder) .andExpect(status().isConflict()) .andExpect(jsonPath("$.type", is("TRANSCRIPTION_107"))) - .andExpect(jsonPath("$.duplicate_transcription_id", is(dupeTranscription.getId()))); + .andExpect(jsonPath("$.properties.duplicate_transcription_id", is(dupeTranscription.getId()))); } @Test @@ -233,7 +220,7 @@ void transcriptionRequestWithDuplicateValuesWithNoTimes() throws Exception { mockMvc.perform(requestBuilder) .andExpect(status().isConflict()) .andExpect(jsonPath("$.type", is("TRANSCRIPTION_107"))) - .andExpect(jsonPath("$.duplicate_transcription_id", is(dupeTranscription.getId()))); + .andExpect(jsonPath("$.properties.duplicate_transcription_id", is(dupeTranscription.getId()))); } @@ -254,28 +241,16 @@ void transcriptionRequestHearingWithNoAudio() throws Exception { .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(transcriptionRequestDetails)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isNotFound()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - assertFailedTranscription110Error(actualJson); + .andExpect(jsonPath("$.type", is("TRANSCRIPTION_110"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.title", is("Transcription could not be requested, no audio"))); assertAudit(0); } - private void assertFailedTranscription110Error(String actualJson) { - String expectedJson = """ - { - "type": "TRANSCRIPTION_110", - "title": "Transcription could not be requested, no audio", - "status": 404 - } - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); - } - @Test void transcriptionRequestStartTimeOutsideHearing() throws Exception { TranscriptionUrgencyEnum transcriptionUrgencyEnum = TranscriptionUrgencyEnum.STANDARD; @@ -292,12 +267,11 @@ void transcriptionRequestStartTimeOutsideHearing() throws Exception { .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(transcriptionRequestDetails)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isNotFound()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - assertFailedTranscription111Error(actualJson); + .andExpect(jsonPath("$.type", is("TRANSCRIPTION_111"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.title", is("Transcription could not be requested, times outside of hearing times"))); assertAudit(0); } @@ -318,12 +292,11 @@ void transcriptionRequestEndTimeOutsideHearing() throws Exception { .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(transcriptionRequestDetails)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isNotFound()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - assertFailedTranscription111Error(actualJson); + .andExpect(jsonPath("$.type", is("TRANSCRIPTION_111"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.title", is("Transcription could not be requested, times outside of hearing times"))); assertAudit(0); } @@ -388,17 +361,6 @@ void transcriptionRequestInsideStartAndEnd() throws Exception { assertAudit(1); } - private void assertFailedTranscription111Error(String actualJson) { - String expectedJson = """ - { - "type": "TRANSCRIPTION_111", - "title": "Transcription could not be requested, times outside of hearing times", - "status": 404 - } - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); - } - @Test void transcriptionRequestWithNullDatesAndSentencingRemarksTypeShouldReturnSuccess() throws Exception { @@ -439,28 +401,16 @@ void transcriptionRequestWithNullHearingAndNullCaseShouldThrowException() throws .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(transcriptionRequestDetails)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(header().string("Content-Type", "application/problem+json")) .andExpect(status().isForbidden()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - assertFailedAuthentication107Error(actualJson); + .andExpect(jsonPath("$.type", is("AUTHORISATION_107"))) + .andExpect(jsonPath("$.status", is(403))) + .andExpect(jsonPath("$.title", is("Failed to check authorisation"))); assertAudit(0); } - private void assertFailedAuthentication107Error(String actualJson) { - String expectedJson = """ - { - "type": "AUTHORISATION_107", - "title": "Failed to check authorisation", - "status": 403 - } - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); - } - @ParameterizedTest @EnumSource(names = {"COURT_LOG", "SPECIFIED_TIMES"}) void transcriptionRequestWithNullStartDateAndRequiredDatesTranscriptionTypeShouldThrowException( @@ -477,13 +427,12 @@ void transcriptionRequestWithNullStartDateAndRequiredDatesTranscriptionTypeShoul .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(transcriptionRequestDetails)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(header().string("Content-Type", "application/problem+json")) .andExpect(status().isBadRequest()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - assertTranscriptionFailed100Error(actualJson); + .andExpect(jsonPath("$.type", is("TRANSCRIPTION_100"))) + .andExpect(jsonPath("$.status", is(400))) + .andExpect(jsonPath("$.title", is("Failed to validate transcription request"))); assertAudit(0); } @@ -505,13 +454,12 @@ void transcriptionRequestWithNullEndDateAndRequiredDatesTranscriptionTypeShouldT .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(transcriptionRequestDetails)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(header().string("Content-Type", "application/problem+json")) .andExpect(status().isBadRequest()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - assertTranscriptionFailed100Error(actualJson); + .andExpect(jsonPath("$.type", is("TRANSCRIPTION_100"))) + .andExpect(jsonPath("$.status", is(400))) + .andExpect(jsonPath("$.title", is("Failed to validate transcription request"))); assertAudit(0); } @@ -593,40 +541,17 @@ void transcriptionRequestWithInvalidHearingIdShouldThrowException() throws Excep .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(transcriptionRequestDetails)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(header().string("Content-Type", "application/problem+json")) .andExpect(status().isNotFound()) - .andReturn(); + .andExpect(jsonPath("$.type", is("HEARING_100"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.title", is("The requested hearing cannot be found"))); - String actualJson = mvcResult.getResponse().getContentAsString(); - assertHearingNotFound404Error(actualJson); assertAudit(0); } - private void assertHearingNotFound404Error(String actualJson) { - String expectedJson = """ - { - "type": "HEARING_100", - "title": "The requested hearing cannot be found", - "status": 404 - } - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); - - } - - private void assertCaseNotFound404Error(String actualJson) { - String expectedJson = """ - { - "type": "CASE_104", - "title": "The requested case cannot be found", - "status": 404 - } - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); - } - @Test void transcriptionRequestWithInvalidCaseIdShouldThrowException() throws Exception { TranscriptionUrgencyEnum transcriptionUrgencyEnum = TranscriptionUrgencyEnum.STANDARD; @@ -641,14 +566,13 @@ void transcriptionRequestWithInvalidCaseIdShouldThrowException() throws Exceptio .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(transcriptionRequestDetails)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(header().string("Content-Type", "application/problem+json")) .andExpect(status().isNotFound()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); + .andExpect(jsonPath("$.type", is("CASE_104"))) + .andExpect(jsonPath("$.status", is(404))) + .andExpect(jsonPath("$.title", is("The requested case cannot be found"))); - assertCaseNotFound404Error(actualJson); assertAudit(0); } @@ -691,4 +615,4 @@ private TranscriptionRequestDetails createTranscriptionRequestDetails(Integer he } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionAdminApprovedIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionAdminApprovedIntTest.java index 1ad007f3d2d..dbe05e3e946 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionAdminApprovedIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionAdminApprovedIntTest.java @@ -1,16 +1,16 @@ package uk.gov.hmcts.darts.transcriptions.controller; import com.jayway.jsonpath.JsonPath; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import uk.gov.hmcts.darts.audit.api.AuditApi; import uk.gov.hmcts.darts.authorisation.component.Authorisation; @@ -157,15 +157,11 @@ void updateTranscriptionShouldReturnTranscriptionNotFoundError() throws Exceptio String.format(ENDPOINT_URL, -1))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isNotFound()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"TRANSCRIPTION_101","title":"The requested transcription cannot be found","status":404} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_101"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(404))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The requested transcription cannot be found"))); } @Test @@ -178,16 +174,12 @@ void updateTranscriptionShouldReturnTranscriptionWorkflowActionInvalidError() th String.format(ENDPOINT_URL, transcriptionId))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isConflict()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"TRANSCRIPTION_105","title":"Transcription workflow action is not permitted","status":409} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_105"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(409))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Transcription workflow action is not permitted"))); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionApprovedIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionApprovedIntTest.java index d3b44b3e3ca..df603fc3f14 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionApprovedIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionApprovedIntTest.java @@ -1,16 +1,16 @@ package uk.gov.hmcts.darts.transcriptions.controller; import com.jayway.jsonpath.JsonPath; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import uk.gov.hmcts.darts.audit.api.AuditApi; import uk.gov.hmcts.darts.authorisation.component.Authorisation; @@ -194,15 +194,12 @@ void updateTranscriptionShouldReturnTranscriptionNotFoundError() throws Exceptio String.format("/transcriptions/%d", -1))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isNotFound()) - .andReturn(); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_101"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(404))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The requested transcription cannot be found"))); - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"TRANSCRIPTION_101","title":"The requested transcription cannot be found","status":404} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); verify(authorisation).authoriseByTranscriptionId( -1, Set.of(APPROVER, TRANSCRIBER) @@ -220,15 +217,11 @@ void updateTranscriptionShouldReturnTranscriptionWorkflowActionInvalidError() th String.format("/transcriptions/%d", transcriptionId))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isConflict()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"TRANSCRIPTION_105","title":"Transcription workflow action is not permitted","status":409} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_105"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(409))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Transcription workflow action is not permitted"))); verify(authorisation).authoriseByTranscriptionId( transcriptionId, Set.of(APPROVER, TRANSCRIBER) @@ -252,17 +245,12 @@ void givenAUpdateTranscriptionRequest_WhenRequestorIsSameAsApprover_ThenErrorIsR String.format("/transcriptions/%d", transcriptionId))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isBadRequest()) - .andReturn(); - - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"TRANSCRIPTION_114","title":"Transcription requestor cannot approve or reject their own transcription requests.","status":400} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); - + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_114"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(400))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", + Matchers.is("Transcription requestor cannot approve or reject their own transcription requests."))); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionRejectedIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionRejectedIntTest.java index 45fcc8dde5f..f02f4a68cb6 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionRejectedIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionRejectedIntTest.java @@ -1,16 +1,16 @@ package uk.gov.hmcts.darts.transcriptions.controller; import com.jayway.jsonpath.JsonPath; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import uk.gov.hmcts.darts.audit.api.AuditApi; import uk.gov.hmcts.darts.authorisation.component.Authorisation; @@ -97,15 +97,11 @@ void updateTranscriptionRejectedWithoutCommentShouldReturnTranscriptionBadReques String.format("/transcriptions/%d", transcriptionId))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isBadRequest()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"TRANSCRIPTION_103","title":"The workflow comment is required for this transcription update","status":400} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_103"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(400))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The workflow comment is required for this transcription update"))); verify(authorisation).authoriseByTranscriptionId( transcriptionId, Set.of(APPROVER, TRANSCRIBER) @@ -166,15 +162,11 @@ void updateTranscriptionShouldReturnTranscriptionNotFoundError() throws Exceptio String.format("/transcriptions/%d", -1))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isNotFound()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"TRANSCRIPTION_101","title":"The requested transcription cannot be found","status":404} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_101"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(404))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The requested transcription cannot be found"))); verify(authorisation).authoriseByTranscriptionId( -1, Set.of(APPROVER, TRANSCRIBER) @@ -192,19 +184,15 @@ void updateTranscriptionShouldReturnTranscriptionWorkflowActionInvalidError() th String.format("/transcriptions/%d", transcriptionId))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isConflict()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"TRANSCRIPTION_105","title":"Transcription workflow action is not permitted","status":409} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_105"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(409))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Transcription workflow action is not permitted"))); verify(authorisation).authoriseByTranscriptionId( transcriptionId, Set.of(APPROVER, TRANSCRIBER) ); verifyNoInteractions(mockAuditApi); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionWithTranscriberIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionWithTranscriberIntTest.java index dc76d55ac63..bfc78162d4c 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionWithTranscriberIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionWithTranscriberIntTest.java @@ -1,16 +1,16 @@ package uk.gov.hmcts.darts.transcriptions.controller; import com.jayway.jsonpath.JsonPath; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import uk.gov.hmcts.darts.audit.api.AuditApi; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; @@ -142,15 +142,11 @@ void updateTranscriptionShouldReturnTranscriptionNotFoundError() throws Exceptio String.format("/transcriptions/%d", -1))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isNotFound()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"TRANSCRIPTION_101","title":"The requested transcription cannot be found","status":404} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_101"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(404))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The requested transcription cannot be found"))); verifyNoInteractions(mockAuditApi); } @@ -164,15 +160,11 @@ void updateTranscriptionShouldReturnTranscriptionWorkflowActionInvalidError() th String.format("/transcriptions/%d", transcriptionId))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isConflict()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"TRANSCRIPTION_105","title":"Transcription workflow action is not permitted","status":409} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("TRANSCRIPTION_105"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(409))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("Transcription workflow action is not permitted"))); verifyNoInteractions(mockAuditApi); } @@ -192,15 +184,11 @@ void updateTranscriptionShouldReturnForbiddenError() throws Exception { String.format("/transcriptions/%d", transcriptionId))) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(updateTranscription)); - MvcResult mvcResult = mockMvc.perform(requestBuilder) + mockMvc.perform(requestBuilder) .andExpect(status().isForbidden()) - .andReturn(); - - String actualJson = mvcResult.getResponse().getContentAsString(); - String expectedJson = """ - {"type":"AUTHORISATION_100","title":"User is not authorised for the associated courthouse","status":403} - """; - JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.NON_EXTENSIBLE); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_100"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("User is not authorised for the associated courthouse"))); verifyNoInteractions(mockAuditApi); } @@ -251,4 +239,4 @@ void updateTranscriptionShouldReturnOkWhenTranscriberOnlyUser() throws Exception verify(mockAuditApi).record(ACCEPT_TRANSCRIPTION, testUser, transcriptionEntity.getCourtCase()); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionsTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionsTest.java index 26d7654ddf5..17cebd6cecb 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionsTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/transcriptions/controller/TranscriptionControllerUpdateTranscriptionsTest.java @@ -280,7 +280,7 @@ void testTransactionsUpdateHidePartialFailureWhereSomeTransactionIdsAreUpdatedAn // assert the failure response Assertions.assertNotNull(failureResponse); String partialFailure = JsonPath.parse(mvcResult.getResponse().getContentAsString()) - .read("$.partial_failure"); + .read("$.properties.partial_failure"); List partialFailureResponse = objectMapper.readValue( partialFailure, new TypeReference<>() { @@ -336,7 +336,7 @@ void testTransactionsUpdateHidePartialFailureWhereSomeTransactionIdsAreUpdatedAn // assert the failure response Assertions.assertNotNull(failureResponse); String partialFailure = JsonPath.parse(mvcResult.getResponse().getContentAsString()) - .read("$.partial_failure"); + .read("$.properties.partial_failure"); List partialFailureResponse = objectMapper.readValue( partialFailure, new TypeReference<>() { @@ -501,4 +501,4 @@ void testTransactionsUpdateHideSuccessButUnchangedInDbWhenHideIsNull() throws Ex Assertions.assertFalse(existingTranscription1.getHideRequestFromRequestor()); Assertions.assertFalse(existingTranscription.getHideRequestFromRequestor()); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/GetSecurityGroupsIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/GetSecurityGroupsIntTest.java index 150fb6517ee..4a6208396da 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/GetSecurityGroupsIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/GetSecurityGroupsIntTest.java @@ -1,11 +1,12 @@ package uk.gov.hmcts.darts.usermanagement.controller; +import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; import uk.gov.hmcts.darts.common.entity.CourthouseEntity; import uk.gov.hmcts.darts.common.entity.SecurityGroupEntity; @@ -16,7 +17,6 @@ import uk.gov.hmcts.darts.testutils.stubs.CourthouseStub; import uk.gov.hmcts.darts.testutils.stubs.SuperAdminUserStub; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -47,15 +47,13 @@ void givenAUserNotAuthorisedThenReturnA403() throws Exception { SecurityGroupEntity securityGroupEntity = SecurityGroupTestData.buildGroupForRoleAndCourthouse(SecurityRoleEnum.APPROVER, courthouseEntity); securityGroupRepository.saveAndFlush(securityGroupEntity); - MvcResult mvcResult = mockMvc.perform(get(ENDPOINT_URL)) + mockMvc.perform(get(ENDPOINT_URL)) .andExpect(status().isForbidden()) - .andReturn(); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); - String expectedResponse = """ - {"type":"AUTHORISATION_109","title":"User is not authorised for this endpoint","status":403}"""; - - assertEquals(expectedResponse, mvcResult.getResponse().getContentAsString()); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/PatchUserIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/PatchUserIntTest.java index 8f1c336c61f..d717ebaa650 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/PatchUserIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/PatchUserIntTest.java @@ -12,7 +12,6 @@ import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; -import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; import uk.gov.hmcts.darts.common.entity.SecurityGroupEntity; import uk.gov.hmcts.darts.common.entity.UserAccountEntity; @@ -236,7 +235,7 @@ void patchUserShouldFailIfChangeWithInvalidDataIsAttempted() throws Exception { mockMvc.perform(request) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.title").value("Constraint Violation")) - .andExpect(jsonPath("$.violations[*].field", hasItems("fullName"))); + .andExpect(jsonPath("$.properties.fullName", Matchers.is("size must be between 1 and 256"))); } @Test @@ -460,7 +459,7 @@ void patchUserShouldFailIfProvidedUserIsASystemUser() throws Exception { MvcResult mvcResult = mockMvc.perform(request).andReturn(); - Problem problem = new ObjectMapper().readValue(mvcResult.getResponse().getContentAsString(), Problem.class); + Problem problem = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), Problem.class); assertEquals(UserManagementError.USER_NOT_FOUND.getHttpStatus().value(), mvcResult.getResponse().getStatus()); assertEquals(UserManagementError.USER_NOT_FOUND.getErrorTypeNumeric(), problem.getType().toString()); } diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/PostSecurityGroupIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/PostSecurityGroupIntTest.java index 4597c66961b..325132e92d2 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/PostSecurityGroupIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/PostSecurityGroupIntTest.java @@ -235,7 +235,7 @@ void createSecurityGroupShouldFailWhenAttemptingToCreateGroupThatAlreadyExists() mockMvc.perform(requestForDuplicateGroup) .andExpect(status().isConflict()) .andExpect(jsonPath("$.type").value("USER_MANAGEMENT_105")) - .andExpect(jsonPath("$.existing_group_id").value(initialSecurityGroup.get("id"))); + .andExpect(jsonPath("$.properties.existing_group_id").value(initialSecurityGroup.get("id"))); } @Test @@ -267,7 +267,7 @@ void createSecurityGroupShouldFailWhenAttemptingToCreateGroupThatDisplayNameAlre mockMvc.perform(requestForDuplicateGroup) .andExpect(status().isConflict()) .andExpect(jsonPath("$.type").value("USER_MANAGEMENT_107")) - .andExpect(jsonPath("$.existing_group_id").value(initialSecurityGroup.get("id"))) + .andExpect(jsonPath("$.properties.existing_group_id").value(initialSecurityGroup.get("id"))) .andExpect(jsonPath("$.detail").value("Attempt to create group with a display name that already exists")); } @@ -326,4 +326,4 @@ private MockHttpServletRequestBuilder buildRequest() { .header("Content-Type", "application/json"); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerGetUsersByIdIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerGetUsersByIdIntTest.java index def29ad75bb..3b33d50092e 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerGetUsersByIdIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerGetUsersByIdIntTest.java @@ -2,15 +2,15 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.hamcrest.Matchers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import uk.gov.hmcts.darts.authorisation.component.UserIdentity; import uk.gov.hmcts.darts.common.entity.UserAccountEntity; import uk.gov.hmcts.darts.testutils.IntegrationBase; @@ -79,7 +79,7 @@ void usersGetShouldReturnSystemUserFailure() throws Exception { MvcResult mvcResult = mockMvc.perform(get(ENDPOINT_URL + userAccountEntity.getId())) .andReturn(); - Problem problem = new ObjectMapper().readValue(mvcResult.getResponse().getContentAsString(), Problem.class); + Problem problem = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), Problem.class); Assertions.assertEquals(UserManagementError.USER_NOT_FOUND.getHttpStatus().value(), mvcResult.getResponse().getStatus()); Assertions.assertEquals(UserManagementError.USER_NOT_FOUND.getErrorTypeNumeric(), problem.getType().toString()); @@ -92,20 +92,11 @@ void usersGetShouldReturnSystemUserFailure() throws Exception { void usersGetShouldReturnForbiddenError() throws Exception { superAdminUserStub.givenUserIsNotAuthorised(mockUserIdentity); - MvcResult mvcResult = mockMvc.perform(get(ENDPOINT_URL + "1")) + mockMvc.perform(get(ENDPOINT_URL + "1")) .andExpect(status().isForbidden()) - .andReturn(); - - String expectedResponse = """ - {"type":"AUTHORISATION_109", - "title":"User is not authorised for this endpoint", - "status":403} - """; - JSONAssert.assertEquals( - expectedResponse, - mvcResult.getResponse().getContentAsString(), - JSONCompareMode.NON_EXTENSIBLE - ); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(403))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); verify(mockUserIdentity).userHasGlobalAccess(Set.of(SUPER_ADMIN, SUPER_USER)); verifyNoMoreInteractions(mockUserIdentity); @@ -115,21 +106,12 @@ void usersGetShouldReturnForbiddenError() throws Exception { void usersGetShouldReturnNotFoundError() throws Exception { superAdminUserStub.givenUserIsAuthorised(mockUserIdentity); - MvcResult mvcResult = mockMvc.perform(get(ENDPOINT_URL + "123456")) + mockMvc.perform(get(ENDPOINT_URL + "123456")) .andExpect(status().isNotFound()) - .andReturn(); - - String expectedResponse = """ - {"type":"USER_MANAGEMENT_100", - "title":"The provided user does not exist", - "status":404, - "detail":"User id 123456 not found"} - """; - JSONAssert.assertEquals( - expectedResponse, - mvcResult.getResponse().getContentAsString(), - JSONCompareMode.NON_EXTENSIBLE - ); + .andExpect(MockMvcResultMatchers.jsonPath("$.type", Matchers.is("USER_MANAGEMENT_100"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.status", Matchers.is(404))) + .andExpect(MockMvcResultMatchers.jsonPath("$.detail", Matchers.is("User id 123456 not found"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.is("The provided user does not exist"))); verify(mockUserIdentity).userHasGlobalAccess(Set.of(SUPER_ADMIN, SUPER_USER)); verifyNoMoreInteractions(mockUserIdentity); diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerGetUsersIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerGetUsersIntTest.java index b0c3f92ff57..1ba1d3b2e6c 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerGetUsersIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerGetUsersIntTest.java @@ -1,8 +1,7 @@ package uk.gov.hmcts.darts.usermanagement.controller; +import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; -import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.mock.mockito.MockBean; @@ -56,18 +55,11 @@ class UserControllerGetUsersIntTest extends IntegrationBase { void usersGetShouldReturnForbiddenError() throws Exception { superAdminUserStub.givenUserIsNotAuthorised(mockUserIdentity); - MvcResult mvcResult = mockMvc.perform(get(ENDPOINT_URL)) + mockMvc.perform(get(ENDPOINT_URL)) .andExpect(status().isForbidden()) - .andReturn(); - - String expectedResponse = """ - {"type":"AUTHORISATION_109","title":"User is not authorised for this endpoint","status":403} - """; - JSONAssert.assertEquals( - expectedResponse, - mvcResult.getResponse().getContentAsString(), - JSONCompareMode.NON_EXTENSIBLE - ); + .andExpect(jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(jsonPath("$.status", Matchers.is(403))) + .andExpect(jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); verify(mockUserIdentity).userHasGlobalAccess(Set.of(SUPER_ADMIN, SUPER_USER)); verifyNoMoreInteractions(mockUserIdentity); @@ -144,4 +136,4 @@ private UserAccountEntity createEnabledUserAccountEntity(UserAccountEntity user) .save(userAccountEntity); } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerSearchIntTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerSearchIntTest.java index cf47359d140..2c898f6d463 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerSearchIntTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerSearchIntTest.java @@ -1,6 +1,7 @@ package uk.gov.hmcts.darts.usermanagement.controller; import com.fasterxml.jackson.databind.ObjectMapper; +import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; @@ -60,20 +61,13 @@ void searchShouldReturnForbiddenError() throws Exception { UserSearch userSearch = new UserSearch(); userSearch.setEmailAddress("@example"); - MvcResult mvcResult = mockMvc.perform(post(ENDPOINT_URL) + mockMvc.perform(post(ENDPOINT_URL) .header("Content-Type", "application/json") .content(objectMapper.writeValueAsString(userSearch))) .andExpect(status().isForbidden()) - .andReturn(); - - String expectedResponse = """ - {"type":"AUTHORISATION_109","title":"User is not authorised for this endpoint","status":403} - """; - JSONAssert.assertEquals( - expectedResponse, - mvcResult.getResponse().getContentAsString(), - JSONCompareMode.NON_EXTENSIBLE - ); + .andExpect(jsonPath("$.type", Matchers.is("AUTHORISATION_109"))) + .andExpect(jsonPath("$.status", Matchers.is(403))) + .andExpect(jsonPath("$.title", Matchers.is("User is not authorised for this endpoint"))); verify(userIdentity).userHasGlobalAccess(Set.of(SUPER_ADMIN, SUPER_USER)); verifyNoMoreInteractions(userIdentity); @@ -94,15 +88,14 @@ void searchShouldReturnBadRequestError() throws Exception { String expectedResponse = """ { - "violations": [ - { - "field": "emailAddress", - "message": "size must be between 1 and 256" - } - ], - "type": "https://zalando.github.io/problem/constraint-violation", - "status": 400, - "title": "Constraint Violation" + "type":"about:blank", + "title":"Constraint Violation", + "status":400, + "detail":"", + "instance":"/admin/users/search", + "properties":{ + "emailAddress":"size must be between 1 and 256" + } } """; JSONAssert.assertEquals( @@ -319,4 +312,4 @@ private UserAccountEntity userWithName(String name) { user.setIsSystemUser(false); return user; } -} +} \ No newline at end of file diff --git a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerTest.java b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerTest.java index 95abe704e06..6630702eff9 100644 --- a/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/darts/usermanagement/controller/UserControllerTest.java @@ -121,10 +121,9 @@ void testDeactivateModifyWithSuperAdmin() throws Exception { Assertions.assertFalse(securityGroupStub.isPartOfAnySecurityGroup(fndUserIdentity.get().getId())); - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new JavaTimeModule()); + objectMapper.registerModule(new JavaTimeModule()); - UserWithIdAndTimestamps userWithIdAndTimestamps = mapper.readValue(mvcResult.getResponse().getContentAsString(), + UserWithIdAndTimestamps userWithIdAndTimestamps = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), UserWithIdAndTimestamps.class); List rolledBackTranscription = userWithIdAndTimestamps.getRolledBackTranscriptRequests(); @@ -183,10 +182,9 @@ void testDeactivateUserWithSuperUser() throws Exception { Assertions.assertFalse(securityGroupStub.isPartOfAnySecurityGroup(fndUserIdentity.get().getId())); - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new JavaTimeModule()); + objectMapper.registerModule(new JavaTimeModule()); - UserWithIdAndTimestamps userWithIdAndTimestamps = mapper.readValue(mvcResult.getResponse().getContentAsString(), + UserWithIdAndTimestamps userWithIdAndTimestamps = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), UserWithIdAndTimestamps.class); List rolledBackTranscription = userWithIdAndTimestamps.getRolledBackTranscriptRequests(); @@ -247,10 +245,9 @@ void testActivateModifyUserWithSuperAdmin() throws Exception { = dartsDatabase.getUserAccountRepository().findById(userAccountEntity.getId()); Assertions.assertTrue(fndUserIdentity.isPresent()); - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new JavaTimeModule()); + objectMapper.registerModule(new JavaTimeModule()); - UserWithIdAndTimestamps userWithIdAndTimestamps = mapper.readValue(mvcResult.getResponse().getContentAsString(), + UserWithIdAndTimestamps userWithIdAndTimestamps = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), UserWithIdAndTimestamps.class); List rolledBackTranscription = userWithIdAndTimestamps.getRolledBackTranscriptRequests(); @@ -446,10 +443,9 @@ void testDeactivateFailureWhereUserIsLastInSuperAdminGroup() throws Exception { .andExpect(status().is(AuthorisationError.UNABLE_TO_DEACTIVATE_USER.getHttpStatus().value())) .andReturn(); - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new JavaTimeModule()); + objectMapper.registerModule(new JavaTimeModule()); - Problem problem = mapper.readValue(mvcResult.getResponse().getContentAsString(), + Problem problem = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), Problem.class); Assertions.assertEquals(AuthorisationError.UNABLE_TO_DEACTIVATE_USER.getErrorTypeNumeric(), problem.getType().toString()); } @@ -474,10 +470,9 @@ void testDeactivateFailureFromSuperUserModifyChange() throws Exception { .andExpect(status().is(AuthorisationError.USER_NOT_AUTHORISED_TO_USE_PAYLOAD_CONTENT.getHttpStatus().value())) .andReturn(); - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new JavaTimeModule()); + objectMapper.registerModule(new JavaTimeModule()); - Problem problem = mapper.readValue(mvcResult.getResponse().getContentAsString(), + Problem problem = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), Problem.class); Assertions.assertEquals(AuthorisationError.USER_NOT_AUTHORISED_TO_USE_PAYLOAD_CONTENT.getErrorTypeNumeric(), problem.getType().toString()); } @@ -502,10 +497,9 @@ void testActivateFailureFromSuperUser() throws Exception { .andExpect(status().is(AuthorisationError.USER_NOT_AUTHORISED_TO_ACTIVATE_USER.getHttpStatus().value())) .andReturn(); - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new JavaTimeModule()); + objectMapper.registerModule(new JavaTimeModule()); - Problem problem = mapper.readValue(mvcResult.getResponse().getContentAsString(), + Problem problem = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), Problem.class); Assertions.assertEquals(AuthorisationError.USER_NOT_AUTHORISED_TO_ACTIVATE_USER.getErrorTypeNumeric(), problem.getType().toString()); } diff --git a/src/main/java/uk/gov/hmcts/darts/common/config/ObjectMapperConfig.java b/src/main/java/uk/gov/hmcts/darts/common/config/ObjectMapperConfig.java index 6c679e42817..d23a291e1bc 100644 --- a/src/main/java/uk/gov/hmcts/darts/common/config/ObjectMapperConfig.java +++ b/src/main/java/uk/gov/hmcts/darts/common/config/ObjectMapperConfig.java @@ -9,7 +9,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.web.client.RestTemplate; -import org.zalando.problem.jackson.ProblemModule; @Configuration @Slf4j @@ -20,7 +19,6 @@ public class ObjectMapperConfig { public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); - objectMapper.registerModule(new ProblemModule()); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); @@ -33,7 +31,7 @@ public ObjectMapper objectMapper() { public ObjectMapper caseDocumentObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); - objectMapper.registerModule(new ProblemModule()); + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); diff --git a/src/main/java/uk/gov/hmcts/darts/common/exception/DartsApiTrait.java b/src/main/java/uk/gov/hmcts/darts/common/exception/DartsApiTrait.java index 97222239b14..df0a4b61881 100644 --- a/src/main/java/uk/gov/hmcts/darts/common/exception/DartsApiTrait.java +++ b/src/main/java/uk/gov/hmcts/darts/common/exception/DartsApiTrait.java @@ -2,39 +2,50 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ProblemDetail; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.NativeWebRequest; -import org.zalando.problem.Problem; -import org.zalando.problem.ProblemBuilder; -import org.zalando.problem.spring.common.HttpStatusAdapter; -import org.zalando.problem.spring.web.advice.AdviceTrait; +import java.util.HashMap; import java.util.Map.Entry; -public interface DartsApiTrait extends AdviceTrait { +public interface DartsApiTrait { Logger DARTS_API_EXCEPTION_LOGGER = LoggerFactory.getLogger(DartsApiTrait.class); @ExceptionHandler - default ResponseEntity handleDartsApiException(DartsApiException exception, NativeWebRequest request) { + @SuppressWarnings({ "java:S2259" }) + default ResponseEntity handleDartsApiException(DartsApiException exception, NativeWebRequest request) { var error = exception.getError(); DARTS_API_EXCEPTION_LOGGER.error("A darts exception occurred", exception); - HttpStatusAdapter problemHttpStatus = new HttpStatusAdapter(error.getHttpStatus()); - - ProblemBuilder problemBuilder = Problem.builder() - .withType(error.getType()) - .withStatus(problemHttpStatus) - .withTitle(error.getTitle()) - .withDetail(exception.getDetail()); + ProblemDetail problemDetail = ProblemDetail + .forStatusAndDetail(error.getHttpStatus(), exception.getDetail()); + problemDetail.setType(error.getType()); + problemDetail.setTitle(error.getTitle()); for (Entry stringStringEntry : exception.getCustomProperties().entrySet()) { - problemBuilder.with(stringStringEntry.getKey(), stringStringEntry.getValue()); + if (problemDetail.getProperties() == null) { + problemDetail.setProperties(new HashMap<>()); + } + problemDetail.getProperties().put(stringStringEntry.getKey(), stringStringEntry.getValue()); } - return create(exception, problemBuilder.build(), request); + return new ResponseEntity<>(problemDetail, error.getHttpStatus()); + } + + + @ExceptionHandler + default ResponseEntity exception(Exception exception, NativeWebRequest request) { + DARTS_API_EXCEPTION_LOGGER.error("A exception occurred", exception); + + ProblemDetail problemDetail = ProblemDetail + .forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "A runtime exception occurred"); + + return new ResponseEntity<>(problemDetail, HttpStatus.INTERNAL_SERVER_ERROR); } } \ No newline at end of file diff --git a/src/main/java/uk/gov/hmcts/darts/common/exception/DartsApiTraitImpl.java b/src/main/java/uk/gov/hmcts/darts/common/exception/DartsApiTraitImpl.java new file mode 100644 index 00000000000..d8d9cea9445 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/darts/common/exception/DartsApiTraitImpl.java @@ -0,0 +1,92 @@ +package uk.gov.hmcts.darts.common.exception; + +import jakarta.validation.ConstraintViolation; +import jakarta.validation.ConstraintViolationException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ProblemDetail; +import org.springframework.http.ResponseEntity; +import org.springframework.util.MultiValueMap; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.method.annotation.HandlerMethodValidationException; +import org.springframework.web.multipart.MaxUploadSizeExceededException; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +@ControllerAdvice +public class DartsApiTraitImpl extends ResponseEntityExceptionHandler implements DartsApiTrait { + + + /** + * We can influence JSR 303 errors here in a standardised RFC 7808 manner. We could convert field based + * exceptions to unique error codes making our whole API consistent + */ + @Override + @SuppressWarnings({ "java:S2259" }) + protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, + WebRequest request) { + + ProblemDetail problemDetail = ex.getBody(); + problemDetail.setTitle("Constraint Violation"); + problemDetail.setDetail(""); + + // add the failure specifics to the problem detail properties + for (FieldError fieldError : ex.getFieldErrors()) { + if (problemDetail.getProperties() == null) { + problemDetail.setProperties(new HashMap<>()); + } + problemDetail.getProperties().put(fieldError.getField(), fieldError.getDefaultMessage()); + } + + return new ResponseEntity<>(problemDetail, HttpStatus.BAD_REQUEST); + } + + @Override + @SuppressWarnings("java:S2259") + protected ResponseEntity handleHandlerMethodValidationException(HandlerMethodValidationException ex, HttpHeaders headers, HttpStatusCode status, + WebRequest request) { + return super.handleHandlerMethodValidationException(ex, headers, status, request); + } + + @ExceptionHandler + @SuppressWarnings({ "java:S2259", "java:S1185" }) + protected ResponseEntity handleConstraintViolationException(ConstraintViolationException ex, NativeWebRequest request) { + ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST); + problemDetail.setTitle("Constraint Violation"); + problemDetail.setDetail(ex.getMessage()); + + Set> constraintViolationExceptionSet = ex.getConstraintViolations(); + + for (ConstraintViolation fieldError : constraintViolationExceptionSet) { + + if (problemDetail.getProperties() == null) { + problemDetail.setProperties(new HashMap<>()); + } + + problemDetail.getProperties().put(fieldError.getPropertyPath().toString(), fieldError.getMessage()); + } + + return new ResponseEntity<>(problemDetail, HttpStatus.BAD_REQUEST); + } + + @Override + protected ResponseEntity handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex, HttpHeaders headers, HttpStatusCode status, + WebRequest request) { + ProblemDetail problemDetail = ex.getBody(); + problemDetail.setStatus(HttpStatus.BAD_REQUEST); + + MultiValueMap myheaders = new HttpHeaders(); + myheaders.put("Content-Type", List.of("application/json")); + + return new ResponseEntity<>(problemDetail, myheaders, HttpStatus.BAD_REQUEST); + } +} \ No newline at end of file diff --git a/src/main/java/uk/gov/hmcts/darts/common/exception/ErrorResponseAdviceTrait.java b/src/main/java/uk/gov/hmcts/darts/common/exception/ErrorResponseAdviceTrait.java index 4b9c3b18bea..34c5b109b3e 100644 --- a/src/main/java/uk/gov/hmcts/darts/common/exception/ErrorResponseAdviceTrait.java +++ b/src/main/java/uk/gov/hmcts/darts/common/exception/ErrorResponseAdviceTrait.java @@ -6,36 +6,20 @@ import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.servlet.resource.NoResourceFoundException; -import org.zalando.problem.Problem; -import org.zalando.problem.spring.common.HttpStatusAdapter; -import org.zalando.problem.spring.web.advice.AdviceTrait; /** * AdviceTrait for handling Spring 6 {@link org.springframework.web.ErrorResponseException}. * Temporary workaround until problem-spring-web is extended with support for {@link org.springframework.web.ErrorResponse}. * For now scope is restricted to {@link org.springframework.web.servlet.resource.NoResourceFoundException}, but additional exceptions can be added as needed. */ -public interface ErrorResponseAdviceTrait extends AdviceTrait { +public interface ErrorResponseAdviceTrait { @ExceptionHandler({ NoResourceFoundException.class, }) - default ResponseEntity handleErrorResponseException(ErrorResponse errorResponse, Exception errorResponseAsException, NativeWebRequest request) { - - var problem = toProblem(errorResponse); - - return create(errorResponseAsException, problem, request); - } - - private Problem toProblem(ErrorResponse errorResponse) { - - var problemHttpStatus = new HttpStatusAdapter(errorResponse.getStatusCode()); + default ResponseEntity handleErrorResponseException(ErrorResponse errorResponse, + Exception errorResponseAsException, NativeWebRequest request) { ProblemDetail body = errorResponse.getBody(); - return Problem.builder() - .withType(body.getType()) - .withStatus(problemHttpStatus) - .withTitle(body.getTitle()) - .withDetail(body.getDetail()) - .build(); + return new ResponseEntity<>(body, errorResponse.getStatusCode()); } -} +} \ No newline at end of file diff --git a/src/main/java/uk/gov/hmcts/darts/common/exception/ExceptionHandler.java b/src/main/java/uk/gov/hmcts/darts/common/exception/ExceptionHandler.java index c3e9b652163..632b6a310cf 100644 --- a/src/main/java/uk/gov/hmcts/darts/common/exception/ExceptionHandler.java +++ b/src/main/java/uk/gov/hmcts/darts/common/exception/ExceptionHandler.java @@ -3,10 +3,9 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; import org.springframework.web.bind.annotation.ControllerAdvice; -import org.zalando.problem.spring.web.advice.ProblemHandling; @ControllerAdvice @EnableAutoConfiguration(exclude = ErrorMvcAutoConfiguration.class) -public class ExceptionHandler implements ProblemHandling, DartsApiTrait, ErrorResponseAdviceTrait { +public class ExceptionHandler implements DartsApiTrait, ErrorResponseAdviceTrait { -} +} \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 4601ac6495b..a4baf9130de 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -17,6 +17,9 @@ springdoc: packagesToScan: uk.gov.hmcts.darts spring: + mvc: + problemdetails: + enabled: true lifecycle: timeout-per-shutdown-phase: ${GRACEFUL_SHUTDOWN_TIMEOUT:30s} config: diff --git a/src/testCommon/java/uk/gov/hmcts/darts/test/common/TestUtils.java b/src/testCommon/java/uk/gov/hmcts/darts/test/common/TestUtils.java index d5f72b25447..f466d1a2892 100644 --- a/src/testCommon/java/uk/gov/hmcts/darts/test/common/TestUtils.java +++ b/src/testCommon/java/uk/gov/hmcts/darts/test/common/TestUtils.java @@ -12,7 +12,6 @@ import org.apache.commons.io.FileUtils; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; -import org.zalando.problem.jackson.ProblemModule; import java.io.BufferedReader; import java.io.File; @@ -57,7 +56,6 @@ public static File getFile(String filelocation) { public static ObjectMapper getObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); - objectMapper.registerModule(new ProblemModule()); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);