com.nike.backstopper.apierror.ApiError Java Examples

The following examples show how to use com.nike.backstopper.apierror.ApiError. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiExceptionTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true   |   true",
    "true   |   false",
    "false  |   true",
    "false  |   false",
}, splitBy = "\\|")
@Test(expected = IllegalArgumentException.class)
public void no_cause_constructors_fail_when_passed_null_or_empty_apiErrors_list(
    boolean useNull, boolean useConstructorWithResponseHeaders
) {
    // given
    List<Pair<String, String>> logInfoList = Collections.emptyList();
    List<Pair<String, List<String>>> responseHeaders = Collections.emptyList();
    List<ApiError> apiErrors = (useNull) ? null : Collections.<ApiError>emptyList();

    // expect
    if (useConstructorWithResponseHeaders)
        new ApiException(apiErrors, logInfoList, responseHeaders, exceptionMessage);
    else
        new ApiException(apiErrors, logInfoList, exceptionMessage);
}
 
Example #2
Source File: ApiExceptionHandlerListenerResultTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void handleResponse_one_arg_should_work_as_expected(boolean useNull) {
    // given
    SortedApiErrorSet errors = (useNull) ? null : new SortedApiErrorSet(Arrays.<ApiError>asList(
        BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR, BarebonesCoreApiErrorForTesting.MALFORMED_REQUEST
    ));

    // when
    ApiExceptionHandlerListenerResult val = ApiExceptionHandlerListenerResult.handleResponse(errors);

    // then
    verifyErrors(val, errors);
}
 
Example #3
Source File: SpringWebfluxApiExceptionHandlerUtilsTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void getErrorResponseContentType_returns_APPLICATION_JSON_UTF8_by_default() {
    // given
    DefaultErrorContractDTO errorContractDtoMock = mock(DefaultErrorContractDTO.class);
    int statusCode = 400;
    Collection<ApiError> errors = mock(Collection.class);
    Throwable ex = mock(Throwable.class);
    RequestInfoForLogging requestMock = mock(RequestInfoForLogging.class);

    // when
    MediaType result = utilsSpy.getErrorResponseContentType(
        errorContractDtoMock, statusCode, errors, ex, requestMock
    );

    // then
    assertThat(result).isEqualTo(MediaType.APPLICATION_JSON_UTF8);
    verifyZeroInteractions(errorContractDtoMock, errors, ex, requestMock);
}
 
Example #4
Source File: ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateValidationErrorsForBindException() {
    BindingResult bindingResult = mock(BindingResult.class);

    ApiError someFieldError = testProjectApiErrors.getMissingExpectedContentApiError();
    ApiError otherFieldError = testProjectApiErrors.getTypeConversionApiError();
    ApiError notAFieldError = testProjectApiErrors.getGenericBadRequestApiError();
    List<ObjectError> errorsList = Arrays.asList(
            new FieldError("someObj", "someField", someFieldError.getName()),
            new FieldError("otherObj", "otherField", otherFieldError.getName()),
            new ObjectError("notAFieldObject", notAFieldError.getName())
    );
    when(bindingResult.getAllErrors()).thenReturn(errorsList);

    BindException ex = new BindException(bindingResult);
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    validateResponse(result, true, Arrays.asList(
        new ApiErrorWithMetadata(someFieldError, Pair.of("field", "someField")),
        new ApiErrorWithMetadata(otherFieldError, Pair.of("field", "otherField")),
        notAFieldError
    ));
    verify(bindingResult).getAllErrors();
}
 
Example #5
Source File: SanityCheckComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
private void verifyErrorReceived(ExtractableResponse response, Collection<ApiError> expectedErrors, int expectedHttpStatusCode) {
    assertThat(response.statusCode()).isEqualTo(expectedHttpStatusCode);
    try {
        DefaultErrorContractDTO errorContract = objectMapper.readValue(response.asString(), DefaultErrorContractDTO.class);
        assertThat(errorContract.error_id).isNotEmpty();
        assertThat(UUID.fromString(errorContract.error_id)).isNotNull();
        assertThat(errorContract.errors).hasSameSizeAs(expectedErrors);
        for (ApiError apiError : expectedErrors) {
            DefaultErrorDTO matchingError = findErrorMatching(errorContract, apiError);
            assertThat(matchingError).isNotNull();
            assertThat(matchingError.code).isEqualTo(apiError.getErrorCode());
            assertThat(matchingError.message).isEqualTo(apiError.getMessage());
            assertThat(matchingError.metadata).isEqualTo(apiError.getMetadata());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: ServerConfig.java    From riposte with Apache License 2.0 6 votes vote down vote up
/**
 * @return The error handler that should be used for this application for handling known errors. For things that
 * fall through the cracks they will be handled by {@link #riposteUnhandledErrorHandler()}.
 *
 * <p>NOTE: The default implementation returned if you don't override this method is a very basic Backstopper impl -
 * it will not know about your application's {@link ProjectApiErrors} and will instead create a dummy {@link
 * ProjectApiErrors} that only supports the {@link com.nike.backstopper.apierror.sample.SampleCoreApiError} values.
 * This method should be overridden for most real applications to return a real implementation tailored for your
 * app. In practice this usually means copy/pasting this method and simply supplying the correct {@link
 * ProjectApiErrors} for the app. The rest is usually fine for defaults.
 */
default @NotNull RiposteErrorHandler riposteErrorHandler() {
    ProjectApiErrors projectApiErrors = new SampleProjectApiErrorsBase() {
        @Override
        protected List<ApiError> getProjectSpecificApiErrors() {
            return null;
        }

        @Override
        protected ProjectSpecificErrorCodeRange getProjectSpecificErrorCodeRange() {
            return null;
        }
    };
    return BackstopperRiposteConfigHelper
        .defaultErrorHandler(projectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL);
}
 
Example #7
Source File: SpringWebfluxApiExceptionHandlerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void prepareFrameworkRepresentation_delegates_to_SpringWebfluxApiExceptionHandlerUtils() {
    // given
    Mono<ServerResponse> expectedResult = mock(Mono.class);

    DefaultErrorContractDTO errorContractDTOMock = mock(DefaultErrorContractDTO.class);
    int httpStatusCode = 400;
    Collection<ApiError> rawFilteredApiErrors = mock(Collection.class);
    Throwable originalException = mock(Throwable.class);
    RequestInfoForLogging request = mock(RequestInfoForLogging.class);

    doReturn(expectedResult).when(springUtilsMock).generateServerResponseForError(
        errorContractDTOMock, httpStatusCode, rawFilteredApiErrors, originalException, request
    );

    // when
    Mono<ServerResponse> result = handlerSpy.prepareFrameworkRepresentation(
        errorContractDTOMock, httpStatusCode, rawFilteredApiErrors, originalException, request
    );

    // then
    assertThat(result).isSameAs(expectedResult);
    verify(springUtilsMock).generateServerResponseForError(
        errorContractDTOMock, httpStatusCode, rawFilteredApiErrors, originalException, request
    );
}
 
Example #8
Source File: Jersey1UnhandledExceptionHandlerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void generateLastDitchFallbackErrorResponseInfo_returns_expected_value() {
    // given
    Exception ex = new Exception("kaboom");
    RequestInfoForLogging reqMock = mock(RequestInfoForLogging.class);
    String errorId = UUID.randomUUID().toString();
    Map<String, List<String>> headersMap = MapBuilder.builder("error_uid", singletonList(errorId)).build();

    ApiError expectedGenericError = testProjectApiErrors.getGenericServiceError();
    int expectedHttpStatusCode = expectedGenericError.getHttpStatusCode();
    Map<String, List<String>> expectedHeadersMap = new HashMap<>(headersMap);
    String expectedBodyPayload = JsonUtilWithDefaultErrorContractDTOSupport.writeValueAsString(
        new DefaultErrorContractDTO(errorId, singletonList(expectedGenericError))
    );

    // when
    ErrorResponseInfo<Response.ResponseBuilder> response = handler.generateLastDitchFallbackErrorResponseInfo(ex, reqMock, errorId, headersMap);

    // then
    assertThat(response.httpStatusCode).isEqualTo(expectedHttpStatusCode);
    assertThat(response.headersToAddToResponse).isEqualTo(expectedHeadersMap);
    Response builtFrameworkResponse = response.frameworkRepresentationObj.build();
    assertThat(builtFrameworkResponse.getStatus()).isEqualTo(expectedHttpStatusCode);
    assertThat(builtFrameworkResponse.getEntity()).isEqualTo(expectedBodyPayload);
}
 
Example #9
Source File: ApiExceptionHandlerListenerResultTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
private void verifyErrors(ApiExceptionHandlerListenerResult val, SortedApiErrorSet expectedErrors) {
    if (expectedErrors == null) {
        assertThat(val.errors)
            .isNotNull()
            .isEmpty();
    }
    else {
        assertThat(val.errors).isEqualTo(expectedErrors);
    }

    // verify mutability
    ApiError newError = new ApiErrorBase(UUID.randomUUID().toString(), "foo", "bar", 400);
    // and when
    val.errors.add(newError);
    // then
    assertThat(val.errors).contains(newError);
}
 
Example #10
Source File: SpringWebfluxApiExceptionHandlerUtils.java    From backstopper with Apache License 2.0 6 votes vote down vote up
/**
 * Method for generating a {@link Mono} of {@link ServerResponse} that contains a serialized representation of the
 * given {@link DefaultErrorContractDTO} as its body (JSON serialization by default).
 *
 * <p>NOTE: make sure the {@link DefaultErrorContractDTO} is FULLY populated before calling this method! Changes to
 * the {@link DefaultErrorContractDTO} after calling this method may not be reflected in the
 * returned {@code Mono<ServerResponse>}.
 *
 * <p>The following two methods control the serialized representation of the error contract that will be used
 * as the {@link ServerResponse}'s body: {@link #serializeErrorContractToString(DefaultErrorContractDTO)} and
 * {@link #getErrorResponseContentType(DefaultErrorContractDTO, int, Collection, Throwable, RequestInfoForLogging)}.
 *
 * @return A {@link Mono} of {@link ServerResponse} that contains a serialized representation of the given
 * {@link DefaultErrorContractDTO}.
 */
public Mono<ServerResponse> generateServerResponseForError(
    DefaultErrorContractDTO errorContractDTO,
    int httpStatusCode,
    Collection<ApiError> rawFilteredApiErrors,
    Throwable originalException,
    RequestInfoForLogging request
) {
    return ServerResponse
        .status(httpStatusCode)
        .contentType(
            getErrorResponseContentType(
                errorContractDTO, httpStatusCode, rawFilteredApiErrors, originalException, request
            )
        )
        .syncBody(serializeErrorContractToString(errorContractDTO));
}
 
Example #11
Source File: ApiExceptionHandlerUtils.java    From backstopper with Apache License 2.0 6 votes vote down vote up
/**
 * @return Helper method for turning the given collection into a comma-delimited string of
 *          {@link ApiError#getName()}. Will return blank string (not null) if you pass in null or an empty
 *          collection.
 */
public String concatenateErrorCollection(Collection<ApiError> errors) {
    if (errors == null || errors.isEmpty())
        return "";

    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (ApiError error : errors) {
        if (!first)
            sb.append(',');
        sb.append(error.getName());
        first = false;
    }

    return sb.toString();
}
 
Example #12
Source File: ProjectApiErrorsTestBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyGetStatusCodePriorityOrderMethodContainsAllRelevantCodes_throws_AssertionError_if_it_finds_bad_state() {
    // given
    final ProjectApiErrorsTestBase base = new ProjectApiErrorsTestBase() {
        @Override
        protected ProjectApiErrors getProjectApiErrors() {
            return ProjectApiErrorsForTesting.withProjectSpecificData(Arrays.<ApiError>asList(
                new ApiErrorBase("FOOBAR", 42, "foo", 123456)
            ), ProjectSpecificErrorCodeRange.ALLOW_ALL_ERROR_CODES);
        }
    };

    // when
    Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            base.verifyGetStatusCodePriorityOrderMethodContainsAllRelevantCodes();
        }
    });

    // then
    assertThat(ex)
        .isInstanceOf(AssertionError.class)
        .hasMessageContaining("getStatusCodePriorityOrder() did not contain HTTP Status Code: 123456");
}
 
Example #13
Source File: ProjectApiErrorsTestBase.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void should_not_contain_same_error_codes_for_different_instances_that_are_not_wrappers() {
    Set<String> allowedDuplicateErrorCodes = allowedDuplicateErrorCodes();
    Map<String, ApiError> codeToErrorMap = new HashMap<>();
    for (ApiError apiError : getProjectApiErrors().getProjectApiErrors()) {
        ApiError errorWithSameCode = codeToErrorMap.get(apiError.getErrorCode());

        if (errorWithSameCode != null && !areWrappersOfEachOther(apiError, errorWithSameCode)
            && !allowedDuplicateErrorCodes.contains(apiError.getErrorCode()))
        {
            throw new AssertionError(
                "There are ApiError instances in the ProjectApiErrors that share duplicate error codes and are not "
                + "wrappers of each other. error_code=" + apiError.getErrorCode() + ", conflicting_api_errors=["
                + apiError.getName() + ", " + errorWithSameCode.getName() + "]"
            );
        }

        codeToErrorMap.put(apiError.getErrorCode(), apiError);
    }
}
 
Example #14
Source File: ServerConfig.java    From riposte with Apache License 2.0 6 votes vote down vote up
/**
 * @return The error handler that should be used for this application for handling unknown/unexpected/unhandled
 * errors. Known/handled errors will be processed by {@link #riposteErrorHandler()}.
 *
 * <p>NOTE: The default implementation returned if you don't override this method is a very basic Backstopper impl -
 * it will not know about your application's {@link ProjectApiErrors} and will instead create a dummy {@link
 * ProjectApiErrors} that only supports the {@link com.nike.backstopper.apierror.sample.SampleCoreApiError} values.
 * This method should be overridden for most real applications to return a real implementation tailored for your
 * app. In practice this usually means copy/pasting this method and simply supplying the correct {@link
 * ProjectApiErrors} for the app. The rest is usually fine for defaults.
 */
default @NotNull RiposteUnhandledErrorHandler riposteUnhandledErrorHandler() {
    ProjectApiErrors projectApiErrors = new SampleProjectApiErrorsBase() {
        @Override
        protected List<ApiError> getProjectSpecificApiErrors() {
            return null;
        }

        @Override
        protected ProjectSpecificErrorCodeRange getProjectSpecificErrorCodeRange() {
            return null;
        }
    };
    return BackstopperRiposteConfigHelper
        .defaultUnhandledErrorHandler(projectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL);
}
 
Example #15
Source File: ApiExceptionTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true   |   true",
    "true   |   false",
    "false  |   true",
    "false  |   false",
}, splitBy = "\\|")
@Test(expected = IllegalArgumentException.class)
public void with_cause_constructors_fail_when_passed_null_or_empty_apiErrors_list(
    boolean useNull, boolean useConstructorWithResponseHeaders
) {
    // given
    List<Pair<String, String>> logInfoList = Collections.emptyList();
    List<Pair<String, List<String>>> responseHeaders = Collections.emptyList();
    List<ApiError> apiErrors = (useNull) ? null : Collections.<ApiError>emptyList();

    // expect
    if (useConstructorWithResponseHeaders)
        new ApiException(apiErrors, logInfoList, responseHeaders, exceptionMessage, cause);
    else
        new ApiException(apiErrors, logInfoList, exceptionMessage, cause);
}
 
Example #16
Source File: UnhandledExceptionHandlerBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void handleException_should_not_allow_error_uid_from_extraHeadersForResponse_to_override_true_error_uid() {
    // given
    final Map<String, List<String>> baseExtraHeaders = MapBuilder
        .builder("error_uid", singletonList(UUID.randomUUID().toString()))
        .build();
    UnhandledExceptionHandlerBase<TestDTO> handler = new TestUnhandledExceptionHandler(testProjectApiErrors, utilsSpy) {
        @Override
        protected Map<String, List<String>> extraHeadersForResponse(TestDTO frameworkRepresentation, DefaultErrorContractDTO errorContractDTO,
                                                                    int httpStatusCode, Collection<ApiError> rawFilteredApiErrors,
                                                                    Throwable originalException,
                                                                    RequestInfoForLogging request) {
            return baseExtraHeaders;
        }
    };

    // when
    ErrorResponseInfo<TestDTO> result = handler.handleException(new Exception(), reqMock);

    // then
    assertThat(result.headersToAddToResponse.get("error_uid"))
              .isNotEqualTo(baseExtraHeaders.get("error_uid"))
              .isEqualTo(singletonList(result.frameworkRepresentationObj.erv.error_id));
}
 
Example #17
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
private DefaultErrorDTO findErrorMatching(DefaultErrorContractDTO errorContract, ApiError desiredError) {
    for (DefaultErrorDTO error : errorContract.errors) {
        if (error.code.equals(desiredError.getErrorCode()) && error.message.equals(desiredError.getMessage()))
            return error;
    }

    return null;
}
 
Example #18
Source File: ClientfacingErrorITest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConvertValidationExceptionsAppropriatelyWithSameErrorTypes() throws Exception {
    // Errors with the same error codes should all show up in the response.
    List<ApiError> errors = Arrays.asList(projectApiErrors.getMalformedRequestApiError(), projectApiErrors.getMissingExpectedContentApiError());
    MvcResult result = this.mockMvc.perform(
            get("/clientFacingErrorTestDummy/throwSpecificValidationExceptions")
                    .content(objectMapper.writeValueAsString(errors))
                    .contentType(MediaType.APPLICATION_JSON)
    ).andReturn();
    verifyErrorResponse(result, projectApiErrors, errors, ApiException.class);
    Assertions.assertThat(result.getResponse().getHeaders("foo1")).isEqualTo(singletonList("bar"));
    Assertions.assertThat(result.getResponse().getHeaders("foo2")).isEqualTo(Arrays.asList("bar2.1", "bar2.2"));
}
 
Example #19
Source File: ProjectApiErrorsTestBase.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void convertToApiErrorShouldReturnExpectedResultIfPassedValidNames() {
    for (ApiError apiError : getProjectApiErrors().getProjectApiErrors()) {
        assertThat("Did not get back the same instance for ApiError with name: " + apiError.getName() + ". This is usually because you have duplicate ApiError names - see the " +
                   "output of the shouldNotContainDuplicateNamedApiErrors() test to be sure. If that's not the case then you'll probably need to do some breakpoint debugging.",
                   getProjectApiErrors().convertToApiError(apiError.getName()), is(apiError));
    }
}
 
Example #20
Source File: ProjectApiErrorsTestBase.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void determineHighestPriorityHttpStatusCodeShouldReturnNullIfNoApiErrorsYouPassItHasHttpStatusCodeInPriorityOrderList() {
    ApiError mockApiError1 = mock(ApiError.class);
    ApiError mockApiError2 = mock(ApiError.class);
    doReturn(414141).when(mockApiError1).getHttpStatusCode();
    doReturn(424242).when(mockApiError2).getHttpStatusCode();
    List<ApiError> list = Arrays.asList(mockApiError1, mockApiError2);

    assertThat(getProjectApiErrors().determineHighestPriorityHttpStatusCode(list), nullValue());
}
 
Example #21
Source File: ProjectApiErrorsTestBase.java    From backstopper with Apache License 2.0 5 votes vote down vote up
protected ApiError findRandomApiErrorWithHttpStatusCode(int httpStatusCode) {
    for (ApiError error : getProjectApiErrors().getProjectApiErrors()) {
        if (error.getHttpStatusCode() == httpStatusCode)
            return error;
    }
    throw new IllegalStateException("Couldn't find ApiError with HTTP status code: " + httpStatusCode);
}
 
Example #22
Source File: ProjectApiErrorsForTesting.java    From backstopper with Apache License 2.0 5 votes vote down vote up
public static ProjectApiErrorsForTesting withProjectSpecificData(final List<ApiError> projectSpecificErrors,
                                                                 final ProjectSpecificErrorCodeRange projectSpecificErrorCodeRange) {
    return new ProjectApiErrorsForTesting() {
        @Override
        protected List<ApiError> getProjectSpecificApiErrors() {
            return projectSpecificErrors;
        }

        @Override
        protected ProjectSpecificErrorCodeRange getProjectSpecificErrorCodeRange() {
            return projectSpecificErrorCodeRange;
        }
    };
}
 
Example #23
Source File: ApiExceptionHandlerListenerResultTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true   |   true    |   true",
    "true   |   true    |   false",
    "true   |   false   |   true",
    "true   |   false   |   false",
    "false  |   true    |   true",
    "false  |   true    |   false",
    "false  |   false   |   true",
    "false  |   false   |   false",
}, splitBy = "\\|")
@Test
public void handleResponse_three_args_should_work_as_expected(
    boolean useNullErrors, boolean useNullExtraLogging, boolean useNullResponseHeaders
) {
    // given
    SortedApiErrorSet errors = (useNullErrors) ? null : new SortedApiErrorSet(Arrays.<ApiError>asList(
        BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR, BarebonesCoreApiErrorForTesting.MALFORMED_REQUEST
    ));
    List<Pair<String, String>> extraDetailsForLogging = (useNullExtraLogging) ? null : Arrays.asList(
        Pair.of("extraKey1", UUID.randomUUID().toString()), Pair.of("extraKey2", UUID.randomUUID().toString())
    );
    List<Pair<String, List<String>>> extraResponseHeaders = (useNullResponseHeaders) ? null : Arrays.asList(
        Pair.of("header1", singletonList(UUID.randomUUID().toString())),
        Pair.of("header2", Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
    );

    // when
    ApiExceptionHandlerListenerResult val = ApiExceptionHandlerListenerResult.handleResponse(
        errors, extraDetailsForLogging, extraResponseHeaders
    );

    // then
    verifyErrors(val, errors);
    verifyExtraLogging(val, extraDetailsForLogging);
    verifyExtraResponseHeaders(val, extraResponseHeaders);
}
 
Example #24
Source File: ProjectApiErrorsTestBase.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void getSublistContainingOnlyHttpStatusCodeShouldFilterOutExpectedValues() {
    List<ApiError> mixedList = Arrays.asList(
        findRandomApiErrorWithHttpStatusCode(getProjectApiErrors().getStatusCodePriorityOrder()
                                                                  .get(0)),
        findRandomApiErrorWithHttpStatusCode(getProjectApiErrors().getStatusCodePriorityOrder()
                                                                  .get(1)));

    List<ApiError> filteredList = getProjectApiErrors().getSublistContainingOnlyHttpStatusCode(mixedList, getProjectApiErrors().getStatusCodePriorityOrder()
                                                                                                                               .get(1));
    for(ApiError error : filteredList) {
        assertThat(error.getHttpStatusCode(), is(getProjectApiErrors().getStatusCodePriorityOrder().get(1)));
    }
}
 
Example #25
Source File: BaseSpringEnabledValidationTestCase.java    From backstopper with Apache License 2.0 5 votes vote down vote up
private List<Pair<String, String>> convertToCodeAndMessagePairs(Collection<ApiError> errors) {
    List<Pair<String, String>> pairs = new ArrayList<>();
    for (ApiError error : errors) {
        pairs.add(Pair.of(error.getErrorCode(), error.getMessage()));
    }

    return pairs;
}
 
Example #26
Source File: ApiExceptionHandlerBaseTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
private List<ApiError> findAllApiErrorsWithHttpStatusCode(int httpStatusCode) {
    List<ApiError> returnList = new ArrayList<>();
    for (ApiError error : testProjectApiErrors.getProjectApiErrors()) {
        if (error.getHttpStatusCode() == httpStatusCode)
            returnList.add(error);
    }
    return returnList;
}
 
Example #27
Source File: ProjectApiErrorsTestBase.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyGetStatusCodePriorityOrderMethodContainsAllRelevantCodes() {
    for (ApiError error : getProjectApiErrors().getProjectApiErrors()) {
        int relevantCode = error.getHttpStatusCode();
        boolean containsRelevantCode = getProjectApiErrors().getStatusCodePriorityOrder().contains(relevantCode);
        if (!containsRelevantCode)
            throw new AssertionError("getStatusCodePriorityOrder() did not contain HTTP Status Code: " + relevantCode + " for " + getProjectApiErrors().getClass().getName() + "'s ApiError: " + error);
    }
}
 
Example #28
Source File: ComponentTestUtils.java    From riposte with Apache License 2.0 5 votes vote down vote up
public static void verifyErrorReceived(String response, int responseStatusCode, ApiError expectedApiError) throws IOException {
    assertThat(responseStatusCode).isEqualTo(expectedApiError.getHttpStatusCode());
    DefaultErrorContractDTO responseAsError = objectMapper.readValue(response, DefaultErrorContractDTO.class);
    assertThat(responseAsError.errors).hasSize(1);
    assertThat(responseAsError.errors.get(0).code).isEqualTo(expectedApiError.getErrorCode());
    assertThat(responseAsError.errors.get(0).message).isEqualTo(expectedApiError.getMessage());
    assertThat(responseAsError.errors.get(0).metadata).isEqualTo(expectedApiError.getMetadata());
}
 
Example #29
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
private DefaultErrorDTO findErrorMatching(DefaultErrorContractDTO errorContract, ApiError desiredError) {
    for (DefaultErrorDTO error : errorContract.errors) {
        if (error.code.equals(desiredError.getErrorCode()) && error.message.equals(desiredError.getMessage()))
            return error;
    }

    return null;
}
 
Example #30
Source File: JaxRsWebApplicationExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@UseDataProvider("dataProviderForShouldHandleException")
@Test
public void shouldHandleException_handles_exceptions_it_knows_about(Exception ex, ApiError expectedResultError) {
    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    // then
    assertThat(result.shouldHandleResponse).isTrue();
    assertThat(result.errors).isEqualTo(SortedApiErrorSet.singletonSortedSetOf(expectedResultError));
}