com.nike.internal.util.Pair Java Examples

The following examples show how to use com.nike.internal.util.Pair. 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: AsyncWingtipsHelperTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void functionWithTracing_separate_args_works_as_expected(boolean useStaticMethod) {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingInfo();

    // when
    Function result = (useStaticMethod)
                      ? functionWithTracing(functionMock, setupInfo.getLeft(), setupInfo.getRight())
                      : DEFAULT_IMPL.functionWithTracing(functionMock,
                                                               setupInfo.getLeft(), setupInfo.getRight());

    // then
    verifyFunctionWithTracing(result, functionMock, setupInfo.getLeft(), setupInfo.getRight());
}
 
Example #2
Source File: ReflectionBasedJsr303AnnotationTrollerBase.java    From backstopper with Apache License 2.0 6 votes vote down vote up
/**
 * @return Helper method that returns the given listToFilter after any pairs have been removed where the pair's
 * AnnotatedElement's owning class is in annotatedElementOwnerClassesToExclude OR where the pair matches any matcher
 * in specificAnnotationDeclarationExclusionMatchers.
 */
public static List<Pair<Annotation, AnnotatedElement>> getSubAnnotationListUsingExclusionFilters(
    List<Pair<Annotation, AnnotatedElement>> listToFilter,
    final List<Class<?>> annotatedElementOwnerClassesToExclude,
    final List<Predicate<Pair<Annotation, AnnotatedElement>>> specificAnnotationDeclarationExclusionMatchers) {
    return getSubAnnotationList(listToFilter, new Predicate<Pair<Annotation, AnnotatedElement>>() {
        public boolean apply(Pair<Annotation, AnnotatedElement> input) {
            AnnotatedElement annotatedElement = input.getRight();

            if (annotatedElementOwnerClassesToExclude != null && annotatedElementOwnerClassesToExclude
                .contains(getOwnerClass(annotatedElement)))
                return false;

            if (specificAnnotationDeclarationExclusionMatchers != null) {
                for (Predicate<Pair<Annotation, AnnotatedElement>> exclusionMatcher : specificAnnotationDeclarationExclusionMatchers) {
                    if (exclusionMatcher.apply(input))
                        return false;
                }
            }

            return true;
        }
    });
}
 
Example #3
Source File: SignalFxAwareCodahaleMetricsCollectorTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
private <M extends Metric> void verifyMetricCreation(
    MetricBuilder<M> metricBuilder, BuilderTagger<M> builderTaggerMock, String metricName,
    List<Pair<String, String>> dimensions, M expectedMetricResult, M actualMetricResult
) {
    int numDimensions = (dimensions == null) ? 0 : dimensions.size();

    verify(metricMetadataMock).forBuilder(metricBuilder);
    verify(builderTaggerMock).withMetricName(metricName);
    if (numDimensions == 0) {
        verify(builderTaggerMock, never()).withDimension(anyString(), anyString());
    }
    else {
        for (Pair<String, String> dimension : dimensions) {
            verify(builderTaggerMock).withDimension(dimension.getKey(), dimension.getValue());
        }
    }
    verify(builderTaggerMock).createOrGet(metricRegistryMock);
    verifyNoMoreInteractions(metricMetadataMock, builderTaggerMock);
    assertThat(actualMetricResult).isSameAs(expectedMetricResult);
}
 
Example #4
Source File: WingtipsSpringWebfluxExchangeFilterFunctionTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Test
public void completeSubspanAttachedToCurrentThread_completes_span_even_if_highly_improbable_exception_occurs() {
    // given
    Span rootSpan = Tracer.getInstance().startRequestWithRootSpan("fooRootSpan");
    Span currentSpan = Tracer.getInstance().startSubSpan("fooSubspan", SpanPurpose.LOCAL_ONLY);
    RuntimeException improbableException = new RuntimeException("Intentional test exception");

    @SuppressWarnings("unchecked")
    Pair<String, String> explodingTag = mock(Pair.class);
    //noinspection ResultOfMethodCallIgnored
    doThrow(improbableException).when(explodingTag).getKey();

    // when
    Throwable ex = catchThrowable(
        () -> WingtipsSpringWebfluxExchangeFilterFunction.completeSubspanAttachedToCurrentThread(
            request, responseMock, mock(Throwable.class), tagAndNamingStrategy, tagAndNamingAdapterMock, explodingTag
        )
    );

    // then
    assertThat(ex).isSameAs(improbableException);

    assertThat(currentSpan.isCompleted()).isTrue();
    assertThat(spanRecorder.completedSpans).isEqualTo(singletonList(currentSpan));
    assertThat(Tracer.getInstance().getCurrentSpan()).isEqualTo(rootSpan);
}
 
Example #5
Source File: AsyncCompletionHandlerWithTracingAndMdcSupportTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
private Pair<Deque<Span>, Map<String, String>> generateTraceInfo(Boolean setupForSubspan) {
    if (setupForSubspan == null)
        return Pair.of(null, null);

    try {
        resetTracingAndMdc();
        Tracer.getInstance().startRequestWithRootSpan("overallReqSpan");

        if (setupForSubspan)
            Tracer.getInstance().startSubSpan("subSpan", Span.SpanPurpose.LOCAL_ONLY);

        return Pair.of(Tracer.getInstance().getCurrentSpanStackCopy(), MDC.getCopyOfContextMap());
    }
    finally {
        resetTracingAndMdc();
    }
}
 
Example #6
Source File: AsyncWingtipsHelperTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void consumerWithTracing_separate_args_works_as_expected(boolean useStaticMethod) {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingInfo();

    // when
    Consumer result = (useStaticMethod)
                      ? consumerWithTracing(consumerMock, setupInfo.getLeft(), setupInfo.getRight())
                      : DEFAULT_IMPL.consumerWithTracing(consumerMock,
                                                               setupInfo.getLeft(), setupInfo.getRight());

    // then
    verifyConsumerWithTracing(result, consumerMock, setupInfo.getLeft(), setupInfo.getRight());
}
 
Example #7
Source File: ApiException.java    From backstopper with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance on top of {@link Exception#Exception(String)} super constructor. You can safely pass in null
 * for message if you have no message. If another exception caused this to be thrown then you'll want
 * {@link #ApiException(List, List, List, String, Throwable)} instead so that the proper super constructor is used.
 *
 * <p>NOTE: Most of the time you wouldn't want to use this constructor directly - use the
 * {@link ApiException.Builder} instead.
 *
 * @deprecated Use the {@link Builder} (or the {@link ApiException#ApiException(Builder) constructor} that takes a
 * builder) instead.
 */
@Deprecated
public ApiException(List<ApiError> apiErrors, List<Pair<String, String>> extraDetailsForLogging,
                    List<Pair<String, List<String>>> extraResponseHeaders, String message) {
    super(extractMessage(apiErrors, message));

    if (apiErrors == null || apiErrors.isEmpty())
        throw new IllegalArgumentException("apiErrors cannot be null or empty");

    if (extraDetailsForLogging == null)
        extraDetailsForLogging = Collections.emptyList();

    if (extraResponseHeaders == null)
        extraResponseHeaders = Collections.emptyList();

    this.apiErrors = new ArrayList<>(apiErrors);
    this.extraDetailsForLogging = new ArrayList<>(extraDetailsForLogging);
    this.extraResponseHeaders = new ArrayList<>(extraResponseHeaders);
    this.stackTraceLoggingBehavior = StackTraceLoggingBehavior.DEFER_TO_DEFAULT_BEHAVIOR;
}
 
Example #8
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 #9
Source File: ReflectionBasedJsr303AnnotationTrollerBase.java    From backstopper with Apache License 2.0 6 votes vote down vote up
/**
 * @return The list of annotation->owningElement pairs from the given 2-dimensional array that match the given
 * desiredAnnotationClass - note that if desiredAnnotationClassIsMultiValueConstraint is true then each matching
 * annotation will be exploded via {@link #explodeAnnotationToManyConstraintsIfMultiValue(java.lang.annotation.Annotation,
 * boolean)} before being added to the return list.
 */
private static List<Pair<Annotation, AnnotatedElement>> extractAnnotationsFrom2dArray(
    Annotation[][] annotations2dArray, Class<? extends Annotation> desiredAnnotationClass,
    boolean desiredAnnotationClassIsMultiValueConstraint, AnnotatedElement owningElement) {
    List<Pair<Annotation, AnnotatedElement>> returnList = new ArrayList<>();
    for (Annotation[] innerArray : annotations2dArray) {
        for (Annotation annotation : innerArray) {
            if (annotation.annotationType().equals(desiredAnnotationClass)) {
                List<Annotation> annotationsToRegister = explodeAnnotationToManyConstraintsIfMultiValue(
                    annotation, desiredAnnotationClassIsMultiValueConstraint
                );
                for (Annotation annotationToRegister : annotationsToRegister) {
                    returnList.add(Pair.of(annotationToRegister, owningElement));
                }
            }
        }
    }

    return returnList;
}
 
Example #10
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_GENERIC_SERVICE_ERROR_returned_if_ServerErrorException_is_thrown() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .log().all()
            .when()
            .get(SERVER_ERROR_EXCEPTION_ENDPOINT_PATH, "doesNotMatter")
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, SampleCoreApiError.GENERIC_SERVICE_ERROR);
    ServerErrorException ex = verifyResponseStatusExceptionSeenByBackstopper(ServerErrorException.class, 500);
    verifyHandlingResult(
        SampleCoreApiError.GENERIC_SERVICE_ERROR,
        Pair.of("exception_message", quotesToApostrophes(ex.getMessage())),
        Pair.of("method_parameter", ex.getMethodParameter().toString()),
        Pair.of("handler_method", ex.getHandlerMethod().toString())
    );
}
 
Example #11
Source File: AsyncWingtipsHelperTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void biConsumerWithTracing_pair_works_as_expected(boolean useStaticMethod) {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingInfo();

    // when
    BiConsumer result = (useStaticMethod)
                        ? biConsumerWithTracing(biConsumerMock, setupInfo)
                        : DEFAULT_IMPL.biConsumerWithTracing(biConsumerMock, setupInfo);

    // then
    verifyBiConsumerWithTracing(result, biConsumerMock, setupInfo.getLeft(), setupInfo.getRight());
}
 
Example #12
Source File: AsyncWingtipsHelperTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void supplierWithTracing_separate_args_works_as_expected(boolean useStaticMethod) {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingInfo();

    // when
    Supplier result = (useStaticMethod)
                      ? supplierWithTracing(supplierMock, setupInfo.getLeft(), setupInfo.getRight())
                      : DEFAULT_IMPL.supplierWithTracing(supplierMock,
                                                               setupInfo.getLeft(), setupInfo.getRight());

    // then
    verifySupplierWithTracing(result, supplierMock, setupInfo.getLeft(), setupInfo.getRight());
}
 
Example #13
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
private Pair<Pair<SignalFxReporter, MetricMetadata>, Pair<Long, TimeUnit>> wireUpReporterFactoryMockForConstructor(
    SignalFxReporterFactory factoryMock, MetricRegistry expectedMetricRegistry
) {
    SignalFxReporter reporterMock = mock(SignalFxReporter.class);
    doReturn(reporterMock).when(factoryMock).getReporter(expectedMetricRegistry);

    MetricMetadata metricMetadataMock = wireUpReporterForConstructor(reporterMock);

    long reportingInterval = 42;
    TimeUnit reportingTimeUnit = TimeUnit.DAYS;

    doReturn(reportingInterval).when(factoryMock).getInterval();
    doReturn(reportingTimeUnit).when(factoryMock).getTimeUnit();

    return Pair.of(Pair.of(reporterMock, metricMetadataMock), Pair.of(reportingInterval, reportingTimeUnit));
}
 
Example #14
Source File: BackstopperRiposteFrameworkErrorHandlerListenerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void should_handle_RequestTooBigException() {
    // given
    String exMsg = UUID.randomUUID().toString();
    RequestTooBigException ex = new RequestTooBigException(exMsg);

    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    // then
    assertThat(result.shouldHandleResponse).isTrue();
    assertThat(result.errors).isEqualTo(singletonError(
        new ApiErrorWithMetadata(testProjectApiErrors.getMalformedRequestApiError(),
                                 Pair.of("cause", "The request exceeded the maximum payload size allowed"))
    ));

    assertThat(result.extraDetailsForLogging.get(0).getLeft()).isEqualTo("exception_message");
    assertThat(result.extraDetailsForLogging.get(0).getRight()).isEqualTo(exMsg);

    assertThat(result.extraDetailsForLogging.get(1).getLeft()).isEqualTo("decoder_exception");
    assertThat(result.extraDetailsForLogging.get(1).getRight()).isEqualTo("true");
}
 
Example #15
Source File: FunctionWithTracingAndMdcSupportTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void constructors_throw_exception_if_passed_null_function() {
    // given
    Deque<Span> spanStackMock = mock(Deque.class);
    Map<String, String> mdcInfoMock = mock(Map.class);

    // expect
    assertThat(catchThrowable(() -> new FunctionWithTracingAndMdcSupport(null, ctxMock)))
        .isInstanceOf(IllegalArgumentException.class);

    // and expect
    assertThat(catchThrowable(() -> new FunctionWithTracingAndMdcSupport(null, Pair.of(spanStackMock, mdcInfoMock))))
        .isInstanceOf(IllegalArgumentException.class);

    // and expect
    assertThat(catchThrowable(() -> new FunctionWithTracingAndMdcSupport(null, spanStackMock, mdcInfoMock)))
        .isInstanceOf(IllegalArgumentException.class);
}
 
Example #16
Source File: DTraceEndHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void endDtrace_completes_the_trace_immediately_if_state_is_not_null_but_isResponseSendingLastChunkSent_returns_false() {
    // given
    assertThat(state.isTraceCompletedOrScheduled(), is(false));
    state.setResponseWriterFinalChunkChannelFuture(null);
    assertThat(state.isResponseSendingLastChunkSent(), is(false));
    assertThat(state.getDistributedTraceStack(), nullValue());
    Pair<Deque<Span>, Map<String, String>> expectedDtraceInfo = setupStateWithNewSpan("blahTrace");
    assertThat(state.getDistributedTraceStack(), notNullValue());
    assertThat(state.getDistributedTraceStack(), is(expectedDtraceInfo.getLeft()));
    assertThat(state.getDistributedTraceStack().size(), is(1));
    assertThat(state.isTracingResponseTaggingAndFinalSpanNameCompleted(), is(false));
    Span expectedSpan = expectedDtraceInfo.getLeft().peek();

    // when
    handlerSpy.endDtrace(ctxMock);

    // then
    verify(handlerSpy).completeCurrentSpan();
    assertThat(currentSpanWhenCompleteCurrentSpanWasCalled, is(expectedSpan));
    assertThat(currentSpanAfterCompleteCurrentSpanWasCalled, nullValue());
    assertThat(state.isTraceCompletedOrScheduled(), is(true));
    assertThat(state.isTracingResponseTaggingAndFinalSpanNameCompleted(), is(true));
}
 
Example #17
Source File: GenericApiExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddExceptionMessageIfExceptionMessageIsNonEmpty() {
    ApiError error = BarebonesCoreApiErrorForTesting.NOT_FOUND;
    ApiException ex = ApiException.newBuilder().withApiErrors(error).withExceptionMessage("Nice message").build();
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);
    assertThat(result.extraDetailsForLogging.size(), is(1));
    assertThat(result.extraDetailsForLogging.get(0), is(Pair.of("api_exception_message", "Nice message")));
}
 
Example #18
Source File: RoutingHandler.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public PipelineContinuationBehavior doChannelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest nettyRequest = (HttpRequest)msg;

        HttpProcessingState state = ChannelAttributes.getHttpProcessingStateForChannel(ctx).get();
        RequestInfo request = handlerUtils.createRequestInfoFromNettyHttpRequestAndHandleStateSetupIfNecessary(
            nettyRequest,
            state
        );

        // If the Netty HttpRequest is invalid, we shouldn't do any endpoint routing.
        handlerUtils.throwExceptionIfNotSuccessfullyDecoded(nettyRequest);

        // The HttpRequest is valid, so continue with the endpoint routing.
        Pair<Endpoint<?>, String> endpointForExecution = findSingleEndpointForExecution(request);

        request.setPathParamsBasedOnPathTemplate(endpointForExecution.getRight());
        state.setEndpointForExecution(endpointForExecution.getLeft(), endpointForExecution.getRight());

        handleSpanNameUpdateForRequestWithPathTemplate(nettyRequest, request, state);

        throwExceptionIfContentLengthHeaderIsLargerThanConfiguredMaxRequestSize(
            nettyRequest, endpointForExecution.getLeft()
        );
    }

    return PipelineContinuationBehavior.CONTINUE;
}
 
Example #19
Source File: ReflectionBasedJsr303AnnotationTrollerBase.java    From backstopper with Apache License 2.0 5 votes vote down vote up
/**
 * @return Helper method that returns the given listToFilter after it has been filtered down based on the given
 * keepTheseItemsFilter predicate.
 */
public static List<Pair<Annotation, AnnotatedElement>> getSubAnnotationList(
    List<Pair<Annotation, AnnotatedElement>> listToFilter,
    Predicate<Pair<Annotation, AnnotatedElement>> keepTheseItemsFilter) {
    List<Pair<Annotation, AnnotatedElement>> returnList = new ArrayList<>();
    for (Pair<Annotation, AnnotatedElement> pair : listToFilter) {
        if (keepTheseItemsFilter.apply(pair))
            returnList.add(pair);
    }

    return returnList;
}
 
Example #20
Source File: ApiExceptionTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void with_cause_constructor_should_translate_null_response_headers_to_empty_list() {
    // given
    List<Pair<String, String>> loggingDetails = Collections.emptyList();
    List<ApiError> apiErrors = Arrays.asList(apiError1, apiError2);

    // when
    ApiException apiException = new ApiException(apiErrors, loggingDetails, null, exceptionMessage, cause);

    // then
    assertThat(apiException.getExtraResponseHeaders())
        .isNotNull()
        .isEmpty();
}
 
Example #21
Source File: BiConsumerWithTracingTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Test
public void constructors_throw_exception_if_passed_null_operator() {
    // given
    final Deque<Span> spanStackMock = mock(Deque.class);
    final Map<String, String> mdcInfoMock = mock(Map.class);

    // expect
    assertThat(catchThrowable(() -> new BiConsumerWithTracing(null)))
        .isInstanceOf(IllegalArgumentException.class);

    assertThat(catchThrowable(() -> withTracing(null)))
        .isInstanceOf(IllegalArgumentException.class);

    // and expect
    assertThat(catchThrowable(() -> new BiConsumerWithTracing(null, Pair.of(spanStackMock, mdcInfoMock))))
        .isInstanceOf(IllegalArgumentException.class);

    assertThat(catchThrowable(() -> withTracing(null, Pair.of(spanStackMock, mdcInfoMock))))
        .isInstanceOf(IllegalArgumentException.class);

    // and expect
    assertThat(catchThrowable(() -> new BiConsumerWithTracing(null, spanStackMock, mdcInfoMock)))
        .isInstanceOf(IllegalArgumentException.class);

    assertThat(catchThrowable(() -> withTracing(null, spanStackMock, mdcInfoMock)))
        .isInstanceOf(IllegalArgumentException.class);
}
 
Example #22
Source File: BaseInboundHandlerWithTracingAndMdcSupport.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    PipelineContinuationBehavior methodExecutionResponse;

    boolean shouldLinkAndUnlinkDTraceInfo = shouldLinkAndUnlinkDistributedTraceInfoForMethod(
        DO_CHANNEL_READ, isDefaultDoChannelReadImpl, forceEnableDTraceOnAllMethods, debugHandlerMethodCalls,
        ctx, msg, null
    );

    Pair<Deque<Span>, Map<String, String>> origThreadInfo = null;
    try {
        if (shouldLinkAndUnlinkDTraceInfo)
            origThreadInfo = linkTracingAndMdcToCurrentThread(ctx);

        if (debugHandlerMethodCalls)
            logger.debug("############### channelRead for {}", this.getClass().getName());

        methodExecutionResponse = doChannelRead(ctx, msg);
    }
    finally {
        if (shouldLinkAndUnlinkDTraceInfo)
            unlinkTracingAndMdcFromCurrentThread(ctx, origThreadInfo);
    }

    if (methodExecutionResponse == null || CONTINUE.equals(methodExecutionResponse))
        super.channelRead(ctx, msg);
}
 
Example #23
Source File: VerifySampleEndpointsComponentTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void verify_mono_endpoint_traced_correctly(boolean upstreamSendsSpan) {
    Pair<Span, Map<String, String>> upstreamSpanInfo = (upstreamSendsSpan)
                                                       ? generateUpstreamSpanHeaders()
                                                       : Pair.of((Span)null, Collections.emptyMap());

    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .headers(upstreamSpanInfo.getRight())
            .queryParam("foo", "bar")
            .log().all()
        .when()
            .get(MONO_PATH)
        .then()
            .log().all()
            .extract();

    assertThat(response.statusCode()).isEqualTo(200);
    assertThat(response.asString()).isEqualTo(MONO_RESULT);
    Span completedSpan =
        verifySingleSpanCompletedAndReturnedInResponse(response, SLEEP_TIME_MILLIS, upstreamSpanInfo.getLeft());
    verifySpanNameAndTags(
        completedSpan,
        "GET " + MONO_PATH,
        "GET",
        MONO_PATH,
        "http://localhost:" + SERVER_PORT + MONO_PATH + "?foo=bar",
        MONO_PATH,
        response.statusCode(),
        null,
        "spring.webflux.server"
    );
}
 
Example #24
Source File: VerifySampleEndpointsComponentTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void verify_flux_endpoint_traced_correctly(boolean upstreamSendsSpan) {
    Pair<Span, Map<String, String>> upstreamSpanInfo = (upstreamSendsSpan)
                                                       ? generateUpstreamSpanHeaders()
                                                       : Pair.of((Span)null, Collections.emptyMap());

    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .headers(upstreamSpanInfo.getRight())
            .queryParam("foo", "bar")
            .log().all()
            .when()
            .get(FLUX_PATH)
            .then()
            .log().all()
            .extract();

    assertThat(response.statusCode()).isEqualTo(200);
    assertThat(response.asString()).isEqualTo(String.join("", FLUX_RESULT));
    Span completedSpan =
        verifySingleSpanCompletedAndReturnedInResponse(response, SLEEP_TIME_MILLIS, upstreamSpanInfo.getLeft());
    verifySpanNameAndTags(
        completedSpan,
        "GET " + FLUX_PATH,
        "GET",
        FLUX_PATH,
        "http://localhost:" + SERVER_PORT + FLUX_PATH + "?foo=bar",
        FLUX_PATH,
        response.statusCode(),
        null,
        "spring.webflux.server"
    );
}
 
Example #25
Source File: AsyncNettyHelperTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void runnableWithTracingAndMdc_separate_args_works_as_expected() {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingAndMdcInfo();

    // when
    Runnable result = AsyncNettyHelper.runnableWithTracingAndMdc(runnableMock,
                                                                 setupInfo.getLeft(), setupInfo.getRight());

    // then
    verifyRunnableWithTracingAndMdcSupport(result, runnableMock, setupInfo.getLeft(), setupInfo.getRight());
}
 
Example #26
Source File: ClientDataValidationErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotAddExtraLoggingDetailsForValidationGroupsWhenGroupsArrayIsEmpty() {
    ClientDataValidationError ex = new ClientDataValidationError(null, null, new Class<?>[0]);

    List<Pair<String, String>> extraLoggingDetails = new ArrayList<>();
    listener.processClientDataValidationError(ex, extraLoggingDetails);
    assertThat(extraLoggingDetails.isEmpty(), is(true));
}
 
Example #27
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@SafeVarargs
private final void verifyHandlingResult(
    ApiError expectedApiError, Pair<String, String> ... expectedExtraLoggingPairs
) {
    ApiExceptionHandlerListenerResult result = normalBackstopperHandlingResult;
    assertThat(result.shouldHandleResponse).isTrue();
    assertThat(result.errors).containsExactly(expectedApiError);
    assertThat(result.extraDetailsForLogging).containsExactlyInAnyOrder(expectedExtraLoggingPairs);
}
 
Example #28
Source File: AsyncWingtipsHelperJava7Test.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Test
public void callableWithTracing_separate_args_works_as_expected() {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingInfo();

    // when
    Callable result = callableWithTracing(callableMock, setupInfo.getLeft(), setupInfo.getRight());

    // then
    verifyCallableWithTracing(result, callableMock, setupInfo.getLeft(), setupInfo.getRight());
}
 
Example #29
Source File: Parser.java    From riposte with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a predicate that takes a nested-left pair, five deep, and applies it to the given five-arity
 * function. Chains of thenParse() calls will produce nested-left pairs, use test() in conjunction with
 * parser.filter() to pass/fail a parser's result. e.g. string("A").string("B").string("C").string("D").filter(test(
 * (a,b,c,d) -> a+b != c+d)).map(match( (a,b,c,d) -> ...))
 */
public static <A, B, C, D, E> Predicate<Pair<Pair<Pair<Pair<A, B>, C>, D>, E>> test(
    final Function5<A, B, C, D, E, Boolean> function) {
    return pair -> function.apply(
        pair.getLeft().getLeft().getLeft().getLeft(),
        pair.getLeft().getLeft().getLeft().getRight(),
        pair.getLeft().getLeft().getRight(),
        pair.getLeft().getRight(),
        pair.getRight()
    );
}
 
Example #30
Source File: VerifySampleEndpointsComponentTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void verify_async_DeferredResult_endpoint_traced_correctly(boolean upstreamSendsSpan) {
    Pair<Span, Map<String, String>> upstreamSpanInfo = (upstreamSendsSpan)
                                                       ? generateUpstreamSpanHeaders()
                                                       : Pair.of((Span)null, Collections.<String, String>emptyMap());

    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .headers(upstreamSpanInfo.getRight())
            .queryParam("foo", "bar")
            .log().all()
        .when()
            .get(ASYNC_DEFERRED_RESULT_PATH)
        .then()
            .log().all()
            .extract();

    assertThat(response.statusCode()).isEqualTo(200);
    assertThat(response.asString()).isEqualTo(ASYNC_DEFERRED_RESULT_PAYLOAD);
    Span completedSpan =
        verifySingleSpanCompletedAndReturnedInResponse(response, SLEEP_TIME_MILLIS, upstreamSpanInfo.getLeft());
    verifySpanNameAndTags(
        completedSpan,
        "GET " + ASYNC_DEFERRED_RESULT_PATH,
        "GET",
        ASYNC_DEFERRED_RESULT_PATH,
        "http://localhost:" + SERVER_PORT + ASYNC_DEFERRED_RESULT_PATH + "?foo=bar",
        ASYNC_DEFERRED_RESULT_PATH,
        response.statusCode(),
        null,
        "servlet"
    );
}