com.nike.internal.util.MapBuilder Java Examples

The following examples show how to use com.nike.internal.util.MapBuilder. 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: BackstopperSpringboot2WebMvcComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #2
Source File: HttpRequestWrapperWithModifiableHeadersTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Test
public void constructor_sets_modifiableHeaders_to_a_mutable_copy_of_given_request_headers() {
    // given
    HttpHeaders immutableHeaders = generateImmutableHeaders(
        MapBuilder.builder("foo", singletonList(UUID.randomUUID().toString()))
                  .put("bar", Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
                  .build()
    );
    doReturn(immutableHeaders).when(requestMock).getHeaders();

    verifyImmutableHeaders(immutableHeaders);

    // when
    HttpRequestWrapperWithModifiableHeaders wrapper = new HttpRequestWrapperWithModifiableHeaders(requestMock);
    verify(requestMock).getHeaders(); // The constructor should have called requestMock.getHeaders()

    // then
    HttpHeaders wrapperHeaders = wrapper.getHeaders();
    assertThat(wrapperHeaders).isSameAs(wrapper.modifiableHeaders);
    // The call to wrapper.getHeaders() should not have called requestMock.getHeaders()
    verifyNoMoreInteractions(requestMock);
    // Instead we should get back some headers that are equal to requestMock's headers, but mutable.
    assertThat(wrapperHeaders).isEqualTo(immutableHeaders);
    verifyMutableHeaders(wrapperHeaders);
}
 
Example #3
Source File: ServerHttpStatusCodeExceptionTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void constructor_sets_values_as_expected() {
    // given
    Throwable cause = new RuntimeException("cause");
    String connectionType = "foo_conn";
    Throwable details = new RuntimeException("details");
    int responseStatusCode = 500;
    Map<String, List<String>> responseHeaders = MapBuilder
        .builder("foo", singletonList(UUID.randomUUID().toString()))
        .put("bar", Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
        .build();
    String rawResponseBody = UUID.randomUUID().toString();

    // when
    ServerHttpStatusCodeException ex = new ServerHttpStatusCodeException(
        cause, connectionType, details, responseStatusCode, responseHeaders, rawResponseBody
    );

    // then
    assertThat(ex).hasCause(cause);
    assertThat(ex.getConnectionType()).isEqualTo(connectionType);
    assertThat(ex.getDetails()).isEqualTo(details);
    assertThat(ex.getResponseStatusCode()).isEqualTo(responseStatusCode);
    assertThat(ex.getResponseHeaders()).isEqualTo(responseHeaders);
    assertThat(ex.getRawResponseBody()).isEqualTo(rawResponseBody);
}
 
Example #4
Source File: ApiErrorComparatorTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void should_return_0_if_names_and_metadata_are_equal() {
    // given
    ApiError mockApiError1 = mock(ApiError.class);
    ApiError mockApiError2 = mock(ApiError.class);

    String name = UUID.randomUUID().toString();
    doReturn(name).when(mockApiError1).getName();
    doReturn(name).when(mockApiError2).getName();

    Map<String, Object> metadata1 = MapBuilder.builder("key1", (Object)"value1")
                                              .put("key2", "value2")
                                              .build();
    Map<String, Object> metadata2 = new HashMap<>(metadata1);

    doReturn(metadata1).when(mockApiError1).getMetadata();
    doReturn(metadata2).when(mockApiError2).getMetadata();

    // when
    int result = comparator.compare(mockApiError1, mockApiError2);

    // then
    assertThat(result).isEqualTo(0);
}
 
Example #5
Source File: VerifySampleEndpointsComponentTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
private Pair<Span, Map<String, String>> generateUpstreamSpanHeaders(boolean includeUserId) {
    Span.Builder spanBuilder = Span.newBuilder("upstreamSpan", Span.SpanPurpose.CLIENT);
    if (includeUserId) {
        spanBuilder.withUserId("user-" + UUID.randomUUID().toString());
    }

    Span span = spanBuilder.build();

    MapBuilder<String, String> headersBuilder = MapBuilder
        .builder(TraceHeaders.TRACE_ID, span.getTraceId())
        .put(TraceHeaders.SPAN_ID, span.getSpanId())
        .put(TraceHeaders.SPAN_NAME, span.getSpanName())
        .put(TraceHeaders.TRACE_SAMPLED, String.valueOf(span.isSampleable()));

    if (span.getUserId() != null) {
        headersBuilder.put(USER_ID_HEADER_KEY, span.getUserId());
    }

    return Pair.of(span, headersBuilder.build());
}
 
Example #6
Source File: ApiExceptionHandlerBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void doHandleApiException_should_add_headers_from_extraHeadersForResponse_to_ErrorResponseInfo() {
    // given
    final Map<String, List<String>> baseExtraHeaders = MapBuilder
        .builder("foo", singletonList(UUID.randomUUID().toString()))
        .put("bar", Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
        .build();
    ApiExceptionHandlerBase<TestDTO> handler = new TestApiExceptionHandler() {
        @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.doHandleApiException(singletonSortedSetOf(CUSTOM_API_ERROR), new ArrayList<Pair<String, String>>(),
                                                                     null, new Exception(), reqMock);

    // then
    Map<String, List<String>> expectedExtraHeaders = new HashMap<>(baseExtraHeaders);
    expectedExtraHeaders.put("error_uid", singletonList(result.frameworkRepresentationObj.erv.error_id));
    Assertions.assertThat(result.headersToAddToResponse).isEqualTo(expectedExtraHeaders);
}
 
Example #7
Source File: VerifySampleEndpointsComponentTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
private Pair<Span, Map<String, String>> generateUpstreamSpanHeaders(boolean includeUserId) {
    Span.Builder spanBuilder = Span.newBuilder("upstreamSpan", Span.SpanPurpose.CLIENT);
    if (includeUserId) {
        spanBuilder.withUserId("user-" + UUID.randomUUID().toString());
    }

    Span span = spanBuilder.build();

    MapBuilder<String, String> headersBuilder = MapBuilder
        .builder(TraceHeaders.TRACE_ID, span.getTraceId())
        .put(TraceHeaders.SPAN_ID, span.getSpanId())
        .put(TraceHeaders.SPAN_NAME, span.getSpanName())
        .put(TraceHeaders.TRACE_SAMPLED, String.valueOf(span.isSampleable()));

    if (span.getUserId() != null) {
        headersBuilder.put(USER_ID_HEADER_KEY, span.getUserId());
    }

    return Pair.of(span, headersBuilder.build());
}
 
Example #8
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 #9
Source File: UnhandledExceptionHandlerBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void handleException_should_add_headers_from_extraHeadersForResponse_to_ErrorResponseInfo() {
    // given
    final Map<String, List<String>> baseExtraHeaders = MapBuilder
        .builder("foo", singletonList(UUID.randomUUID().toString()))
        .put("bar", Arrays.asList(UUID.randomUUID().toString(), 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
    Map<String, List<String>> expectedExtraHeaders = new HashMap<>(baseExtraHeaders);
    expectedExtraHeaders.put("error_uid", singletonList(result.frameworkRepresentationObj.erv.error_id));
    assertThat(result.headersToAddToResponse).isEqualTo(expectedExtraHeaders);
}
 
Example #10
Source File: ApiExceptionHandlerBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void doHandleApiException_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();
    ApiExceptionHandlerBase<TestDTO> handler = new TestApiExceptionHandler() {
        @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.doHandleApiException(singletonSortedSetOf(CUSTOM_API_ERROR), new ArrayList<Pair<String, String>>(),
                                                                     null, new Exception(), reqMock);

    // then
    Assertions.assertThat(result.headersToAddToResponse.get("error_uid"))
              .isNotEqualTo(baseExtraHeaders.get("error_uid"))
              .isEqualTo(singletonList(result.frameworkRepresentationObj.erv.error_id));
}
 
Example #11
Source File: ServerUnknownHttpStatusCodeExceptionTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void constructor_sets_values_as_expected() {
    // given
    Throwable cause = new RuntimeException("cause");
    String connectionType = "foo_conn";
    Throwable details = new RuntimeException("details");
    int responseStatusCode = 500;
    Map<String, List<String>> responseHeaders = MapBuilder
        .builder("foo", singletonList(UUID.randomUUID().toString()))
        .put("bar", Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
        .build();
    String rawResponseBody = UUID.randomUUID().toString();

    // when
    ServerUnknownHttpStatusCodeException ex = new ServerUnknownHttpStatusCodeException(
        cause, connectionType, details, responseStatusCode, responseHeaders, rawResponseBody
    );

    // then
    assertThat(ex).hasCause(cause);
    assertThat(ex.getConnectionType()).isEqualTo(connectionType);
    assertThat(ex.getDetails()).isEqualTo(details);
    assertThat(ex.getResponseStatusCode()).isEqualTo(responseStatusCode);
    assertThat(ex.getResponseHeaders()).isEqualTo(responseHeaders);
    assertThat(ex.getRawResponseBody()).isEqualTo(rawResponseBody);
}
 
Example #12
Source File: JaxRsUnhandledExceptionHandlerTest.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 #13
Source File: BackstopperSpringboot1ComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #14
Source File: WingtipsSpringWebfluxUtilsTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Test
public void subscriberContextWithTracingInfo_works_as_expected() {
    // given
    Map<String, String> origContextPairs = MapBuilder
        .builder("foo", UUID.randomUUID().toString())
        .put("bar", UUID.randomUUID().toString())
        .build();
    Context origContext = Context.of(origContextPairs);
    TracingState tracingStateMock = mock(TracingState.class);

    // when
    Context result = WingtipsSpringWebfluxUtils.subscriberContextWithTracingInfo(origContext, tracingStateMock);

    // then
    assertThat(result.size()).isEqualTo(origContextPairs.size() + 1);
    origContextPairs.forEach(
        (k, v) -> assertThat(result.<String>get(k)).isEqualTo(v)
    );
    assertThat(result.get(TracingState.class)).isSameAs(tracingStateMock);
}
 
Example #15
Source File: BackstopperSpring5WebMvcComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #16
Source File: VerifySampleEndpointsComponentTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
private Pair<Span, Map<String, String>> generateUpstreamSpanHeaders(boolean includeUserId) {
    Span.Builder spanBuilder = Span.newBuilder("upstreamSpan", Span.SpanPurpose.CLIENT);
    if (includeUserId) {
        spanBuilder.withUserId("user-" + UUID.randomUUID().toString());
    }

    Span span = spanBuilder.build();

    MapBuilder<String, String> headersBuilder = MapBuilder
        .builder(TraceHeaders.TRACE_ID, span.getTraceId())
        .put(TraceHeaders.SPAN_ID, span.getSpanId())
        .put(TraceHeaders.SPAN_NAME, span.getSpanName())
        .put(TraceHeaders.TRACE_SAMPLED, String.valueOf(span.isSampleable()));

    if (span.getUserId() != null) {
        headersBuilder.put(USER_ID_HEADER_KEY, span.getUserId());
    }

    return Pair.of(span, headersBuilder.build());
}
 
Example #17
Source File: BackstopperSpring4WebMvcComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #18
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 #19
Source File: PropertiesRegistrationGuiceModuleTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_registration_works() {
    String stringKey = "stringkey";
    String stringVal = UUID.randomUUID().toString();
    String intKey = "intkey";
    int intVal = 42;

    Injector injector = Guice.createInjector(new PropertiesRegistrationGuiceModule() {
        @Override
        protected Map<String, String> getPropertiesMap() {
            return MapBuilder.builder(stringKey, stringVal)
                             .put(intKey, String.valueOf(intVal))
                             .build();
        }
    });

    injector.injectMembers(this);

    assertThat(injectedString).isEqualTo(stringVal);
    assertThat(injectedInt).isEqualTo(intVal);
}
 
Example #20
Source File: ApiExceptionHandlerServletApiBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void maybeHandleExceptionSetsHeadersAndStatusCodeOnServletResponse() throws UnexpectedMajorExceptionHandlingError {
    ErrorResponseInfo<?> expectedResponseInfo = new ErrorResponseInfo(42, null, MapBuilder.<String, List<String>>builder().put("header1", Arrays.asList("h1val1")).put("header2", Arrays.asList("h2val1", "h2val2")).build());
    doReturn(expectedResponseInfo).when(instanceSpy).maybeHandleException(any(Throwable.class), any(RequestInfoForLogging.class));
    instanceSpy.maybeHandleException(new Exception(), servletRequestMock, servletResponseMock);

    verify(servletResponseMock).setStatus(expectedResponseInfo.httpStatusCode);
    int numHeadersChecked = 0;
    for (Map.Entry<String, List<String>> entry : expectedResponseInfo.headersToAddToResponse.entrySet()) {
        for (String headerValue : entry.getValue()) {
            verify(servletResponseMock).addHeader(entry.getKey(), headerValue);
            numHeadersChecked++;
        }
    }
    assertThat(numHeadersChecked > 0, is(true));
    assertThat(numHeadersChecked >= expectedResponseInfo.headersToAddToResponse.size(), is(true));
}
 
Example #21
Source File: UnhandledExceptionHandlerServletApiBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void handleExceptionSetsHeadersAndStatusCodeOnServletResponse() throws UnexpectedMajorExceptionHandlingError {
    ErrorResponseInfo<?> expectedResponseInfo = new ErrorResponseInfo(42, null, MapBuilder.<String, List<String>>builder().put("header1", Arrays.asList("h1val1")).put("header2", Arrays.asList("h2val1", "h2val2")).build());
    doReturn(expectedResponseInfo).when(instanceSpy).handleException(any(Throwable.class), any(RequestInfoForLogging.class));
    instanceSpy.handleException(new Exception(), servletRequestMock, servletResponseMock);

    verify(servletResponseMock).setStatus(expectedResponseInfo.httpStatusCode);
    int numHeadersChecked = 0;
    for (Map.Entry<String, List<String>> entry : expectedResponseInfo.headersToAddToResponse.entrySet()) {
        for (String headerValue : entry.getValue()) {
            verify(servletResponseMock).addHeader(entry.getKey(), headerValue);
            numHeadersChecked++;
        }
    }
    assertThat(numHeadersChecked > 0, is(true));
    assertThat(numHeadersChecked >= expectedResponseInfo.headersToAddToResponse.size(), is(true));
}
 
Example #22
Source File: MediaRangeTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void hashCode_is_equal_to_Objects_dot_hash_of_all_fields() {
    // given
    MediaRange instance = new MediaRange(
        MediaRangeFixture.nikeRunningCoach.expectedMediaRange.type,
        MediaRangeFixture.nikeRunningCoach.expectedMediaRange.subType,
        1.0f,
        MapBuilder.<String, String>builder().put("foo", UUID.randomUUID().toString()).build(),
        MapBuilder.<String, String>builder().put("bar", UUID.randomUUID().toString()).build()
    );

    // expect
    assertThat(instance.hashCode())
        .isEqualTo(Objects.hash(instance.type, instance.subType, instance.qualityFactor,
                                instance.mediaRangeParameters, instance.acceptParameters)
        );
}
 
Example #23
Source File: RequestInfoForLoggingRiposteAdapterTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void getHeadersDelegatesToRequestInfo() {
    Pair<String, List<String>> header1 = Pair.of("header1", Arrays.asList("h1val1"));
    Pair<String, List<String>> header2 = Pair.of("header2", Arrays.asList("h2val1", "h2val2"));
    Map<String, List<String>> expectedHeaderMap = new TreeMap<>(MapBuilder.<String, List<String>>builder()
                                                                          .put(header1.getKey(), header1.getValue())
                                                                          .put(header2.getKey(), header2.getValue())
                                                                          .build());
    HttpHeaders headersMock = mock(HttpHeaders.class);
    doReturn(expectedHeaderMap.keySet()).when(headersMock).names();
    for (Map.Entry<String, List<String>> entry : expectedHeaderMap.entrySet()) {
        doReturn(entry.getValue()).when(headersMock).getAll(entry.getKey());
    }
    setFieldOnRequestInfo("headers", headersMock);
    assertThat(adapter.getHeaders(header1.getKey()), is(header1.getValue()));
    assertThat(adapter.getHeaders(header2.getKey()), is(header2.getValue()));
}
 
Example #24
Source File: SpringWebfluxApiExceptionHandlerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void processWebFluxResponse_works_as_expected() {
    // given
    Map<String, List<String>> headersToAddToResponse = MapBuilder
        .builder("foo", Arrays.asList("bar1", "bar2"))
        .put("blah", Collections.singletonList(UUID.randomUUID().toString()))
        .build();
    ErrorResponseInfo<Mono<ServerResponse>> errorResponseInfo = new ErrorResponseInfo<>(
        400, mock(Mono.class), headersToAddToResponse
    );

    // when
    handlerSpy.processWebFluxResponse(errorResponseInfo, serverHttpResponseMock);

    // then
    headersToAddToResponse.forEach((key, value) -> verify(serverHttpResponseHeadersMock).put(key, value));
}
 
Example #25
Source File: RequestInfoForLoggingRiposteAdapterTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void getHeaderMapDelegatesToRequestInfoAndCachesResult() {
    Map<String, List<String>> expectedHeaderMap = new TreeMap<>(MapBuilder.<String, List<String>>builder()
                                                                          .put("header1", Arrays.asList("h1val1"))
                                                                          .put("header2", Arrays.asList("h2val1", "h2val2"))
                                                                          .build());

    HttpHeaders nettyHeaders = new DefaultHttpHeaders();
    for (Map.Entry<String, List<String>> headerEntry : expectedHeaderMap.entrySet()) {
        nettyHeaders.add(headerEntry.getKey(), headerEntry.getValue());
    }
    setFieldOnRequestInfo("headers", nettyHeaders);
    Map<String, List<String>> actualHeaderMap = adapter.getHeadersMap();
    assertThat(actualHeaderMap, is(expectedHeaderMap));
    assertThat(adapter.getHeadersMap(), sameInstance(actualHeaderMap));
}
 
Example #26
Source File: SpringWebfluxUnhandledExceptionHandlerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void processWebFluxResponse_works_as_expected() {
    // given
    Map<String, List<String>> headersToAddToResponse = MapBuilder
        .builder("foo", Arrays.asList("bar1", "bar2"))
        .put("blah", Collections.singletonList(UUID.randomUUID().toString()))
        .build();
    ErrorResponseInfo<Mono<ServerResponse>> errorResponseInfo = new ErrorResponseInfo<>(
        400, mock(Mono.class), headersToAddToResponse
    );

    // when
    handlerSpy.processWebFluxResponse(errorResponseInfo, serverHttpResponseMock);

    // then
    headersToAddToResponse.forEach((key, value) -> verify(serverHttpResponseHeadersMock).put(key, value));
}
 
Example #27
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #28
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
        .when()
            .get()
        .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #29
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #30
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        // We can't expect the bad_property_name=requiredQueryParamValue metadata like we do in Spring Web MVC,
        //      because Spring WebFlux doesn't add it to the TypeMismatchException cause.
        MapBuilder.builder("bad_property_value", (Object) "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}