com.nike.wingtips.Span Java Examples

The following examples show how to use com.nike.wingtips.Span. 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: TestUtils.java    From wingtips with Apache License 2.0 6 votes vote down vote up
public static void verifyExpectedTracingHeaders(HttpRequest executedRequest, Span expectedSpanForHeaders) {
    HttpHeaders headers = executedRequest.getHeaders();

    List<String> actualTraceIdHeaderVal = headers.get(TRACE_ID);
    List<String> actualSpanIdHeaderVal = headers.get(SPAN_ID);
    List<String> actualSampledHeaderVal = headers.get(TRACE_SAMPLED);
    List<String> actualParentSpanIdHeaderVal = headers.get(PARENT_SPAN_ID);

    if (expectedSpanForHeaders == null) {
        verifyExpectedTracingHeaderValue(actualTraceIdHeaderVal, null);
        verifyExpectedTracingHeaderValue(actualSpanIdHeaderVal, null);
        verifyExpectedTracingHeaderValue(actualSampledHeaderVal, null);
        verifyExpectedTracingHeaderValue(actualParentSpanIdHeaderVal, null);

    }
    else {
        verifyExpectedTracingHeaderValue(actualTraceIdHeaderVal, expectedSpanForHeaders.getTraceId());
        verifyExpectedTracingHeaderValue(actualSpanIdHeaderVal, expectedSpanForHeaders.getSpanId());
        verifyExpectedTracingHeaderValue(
            actualSampledHeaderVal,
            convertSampleableBooleanToExpectedB3Value(expectedSpanForHeaders.isSampleable())
        );
        verifyExpectedTracingHeaderValue(actualParentSpanIdHeaderVal, expectedSpanForHeaders.getParentSpanId());
    }
}
 
Example #2
Source File: HttpSpanFactoryTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Test
public void fromHttpServletRequest_generates_new_spanId_if_missing_from_headers() {
    // given: a request with a trace ID but no span ID in the headers
    String traceId = UUID.randomUUID().toString();
    given(request.getHeader(TraceHeaders.TRACE_ID)).willReturn(traceId);

    // when: we use it to create span objects
    Span firstSpan = HttpSpanFactory.fromHttpServletRequest(request, USER_ID_HEADER_KEYS);
    Span secondSpan = HttpSpanFactory.fromHttpServletRequest(request, USER_ID_HEADER_KEYS);

    // then: ensure each call generates a span with the same trace ID but new span ID
    assertThat(firstSpan.getTraceId()).isEqualTo(traceId);
    assertThat(secondSpan.getTraceId()).isEqualTo(traceId);

    assertThat(firstSpan.getSpanId()).isNotEmpty();
    assertThat(secondSpan.getSpanId()).isNotEmpty();

    assertThat(firstSpan.getSpanId()).isNotEqualTo(secondSpan.getSpanId());
}
 
Example #3
Source File: RunnableWithTracingTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void kitchen_sink_constructor_sets_fields_as_expected(boolean useStaticFactory) {
    // given
    Deque<Span> spanStackMock = mock(Deque.class);
    Map<String, String> mdcInfoMock = mock(Map.class);

    // when
    RunnableWithTracing instance = (useStaticFactory)
                                   ? withTracing(runnableMock, spanStackMock, mdcInfoMock)
                                   : new RunnableWithTracing(runnableMock, spanStackMock, mdcInfoMock);

    // then
    assertThat(instance.origRunnable).isSameAs(runnableMock);
    assertThat(instance.spanStackForExecution).isEqualTo(spanStackMock);
    assertThat(instance.mdcContextMapForExecution).isEqualTo(mdcInfoMock);
}
 
Example #4
Source File: AsyncNettyHelperTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void linkTracingAndMdcToCurrentThread_pair_works_as_expected_with_non_null_pair_and_null_innards() {
    // given
    Pair<Deque<Span>, Map<String, String>> infoForLinking = Pair.of(null, null);
    resetTracingAndMdc();
    Tracer.getInstance().startRequestWithRootSpan("foo-" + UUID.randomUUID().toString());
    Pair<Deque<Span>, Map<String, String>> expectedPreCallInfo = Pair.of(
        Tracer.getInstance().getCurrentSpanStackCopy(),
        MDC.getCopyOfContextMap()
    );

    // when
    Pair<Deque<Span>, Map<String, String>> preCallInfo =
        AsyncNettyHelper.linkTracingAndMdcToCurrentThread(infoForLinking);
    Pair<Deque<Span>, Map<String, String>> postCallInfo = Pair.of(
        Tracer.getInstance().getCurrentSpanStackCopy(),
        MDC.getCopyOfContextMap()
    );

    // then
    assertThat(preCallInfo).isEqualTo(expectedPreCallInfo);
    assertThat(postCallInfo).isEqualTo(Pair.of(null, Collections.emptyMap()));
}
 
Example #5
Source File: DefaultAsyncHttpClientHelperSpanNamingAndTaggingStrategyTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
        "null           |   false",
        "               |   false",
        "[whitespace]   |   false",
        "fooNewName     |   true"
}, splitBy = "\\|")
@Test
public void doChangeSpanName_changes_span_name_as_expected(String newName, boolean expectNameToBeChanged) {
    // given
    if ("[whitespace]".equals(newName)) {
        newName = "  \r\n\t  ";
    }

    String initialSpanName = UUID.randomUUID().toString();
    Span span = Span.newBuilder(initialSpanName, Span.SpanPurpose.CLIENT).build();

    String expectedSpanName = (expectNameToBeChanged) ? newName : initialSpanName;

    // when
    impl.doChangeSpanName(span, newName);

    // then
    assertThat(span.getSpanName()).isEqualTo(expectedSpanName);
}
 
Example #6
Source File: ExceptionHandlingHandler.java    From riposte with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ConstantConditions")
public ExceptionHandlingHandler(
    @NotNull RiposteErrorHandler riposteErrorHandler,
    @NotNull RiposteUnhandledErrorHandler riposteUnhandledErrorHandler,
    @NotNull DistributedTracingConfig<Span> distributedTracingConfig
) {
    if (riposteErrorHandler == null) {
        throw new IllegalArgumentException("riposteErrorHandler cannot be null");
    }

    if (riposteUnhandledErrorHandler == null) {
        throw new IllegalArgumentException("riposteUnhandledErrorHandler cannot be null");
    }

    if (distributedTracingConfig == null) {
        throw new IllegalArgumentException("distributedTracingConfig cannot be null");
    }

    this.riposteErrorHandler = riposteErrorHandler;
    this.riposteUnhandledErrorHandler = riposteUnhandledErrorHandler;
    this.spanNamingAndTaggingStrategy = distributedTracingConfig.getServerSpanNamingAndTaggingStrategy();
}
 
Example #7
Source File: WingtipsToZipkinSpanConverterDefaultImplTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("idSanitizationScenarios")
@Test
public void convertWingtipsSpanToZipkinSpan_sanitizes_spanId_as_expected_when_sanitization_is_enabled(
    IdSanitizationScenario scenario
) {
    // given
    impl = new WingtipsToZipkinSpanConverterDefaultImpl(true);
    final Endpoint zipkinEndpoint = Endpoint.newBuilder().serviceName(UUID.randomUUID().toString()).build();
    final Span wingtipsSpan = Span.newBuilder("foo", SpanPurpose.CLIENT)
                                  .withSpanId(scenario.originalId)
                                  .withSpanStartTimeEpochMicros(Math.abs(random.nextLong()))
                                  .withDurationNanos(Math.abs(random.nextLong()))
                                  .build();

    // when
    zipkin2.Span zipkinSpan = impl.convertWingtipsSpanToZipkinSpan(wingtipsSpan, zipkinEndpoint);

    // then
    assertThat(zipkinSpan.id()).isEqualTo(scenario.expectedSanitizedResultForSpanIdOrParentSpanId);
    assertThat(zipkinSpan.tags().get("invalid.span_id")).isEqualTo(scenario.originalId);
    assertThat(wingtipsSpan.getTags().get("sanitized_span_id")).isEqualTo(scenario.expectedSanitizedResultForSpanIdOrParentSpanId);
}
 
Example #8
Source File: NonblockingEndpointExecutionHandler.java    From riposte with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ConstantConditions")
public NonblockingEndpointExecutionHandler(
    @NotNull Executor longRunningTaskExecutor,
    long defaultCompletableFutureTimeoutMillis,
    @NotNull DistributedTracingConfig<Span> distributedTracingConfig
) {
    if (longRunningTaskExecutor == null) {
        throw new IllegalArgumentException("longRunningTaskExecutor cannot be null");
    }

    if (distributedTracingConfig == null) {
        throw new IllegalArgumentException("distributedTracingConfig cannot be null");
    }

    this.longRunningTaskExecutor = longRunningTaskExecutor;
    this.defaultCompletableFutureTimeoutMillis = defaultCompletableFutureTimeoutMillis;
    this.spanTaggingStrategy = distributedTracingConfig.getServerSpanNamingAndTaggingStrategy();
}
 
Example #9
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 #10
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 #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 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 #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 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 #13
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 #14
Source File: DefaultAsyncHttpClientHelperSpanNamingAndTaggingStrategyTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Before
public void beforeMethod() {
    initialSpanNameFromStrategy = new AtomicReference<>("span-name-from-strategy-" + UUID.randomUUID().toString());
    strategyInitialSpanNameMethodCalled = new AtomicBoolean(false);
    strategyRequestTaggingMethodCalled = new AtomicBoolean(false);
    strategyResponseTaggingAndFinalSpanNameMethodCalled = new AtomicBoolean(false);
    strategyInitialSpanNameArgs = new AtomicReference<>(null);
    strategyRequestTaggingArgs = new AtomicReference<>(null);
    strategyResponseTaggingArgs = new AtomicReference<>(null);
    wingtipsStrategy = new ArgCapturingHttpTagAndSpanNamingStrategy<>(
        initialSpanNameFromStrategy, strategyInitialSpanNameMethodCalled, strategyRequestTaggingMethodCalled,
        strategyResponseTaggingAndFinalSpanNameMethodCalled, strategyInitialSpanNameArgs,
        strategyRequestTaggingArgs, strategyResponseTaggingArgs
    );
    wingtipsAdapterMock = mock(HttpTagAndSpanNamingAdapter.class);

    impl = new DefaultAsyncHttpClientHelperSpanNamingAndTaggingStrategy(wingtipsStrategy, wingtipsAdapterMock);

    requestMock = mock(RequestBuilderWrapper.class);
    responseMock = mock(Response.class);
    errorMock = mock(Throwable.class);
    spanMock = mock(Span.class);
}
 
Example #15
Source File: CallableWithTracingTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void current_thread_info_constructor_sets_fields_as_expected(boolean useStaticFactory) {
    // given
    Tracer.getInstance().startRequestWithRootSpan("request-" + UUID.randomUUID().toString());
    Deque<Span> spanStackMock = Tracer.getInstance().getCurrentSpanStackCopy();
    Map<String, String> mdcInfoMock = MDC.getCopyOfContextMap();

    // when
    CallableWithTracing instance = (useStaticFactory)
                                   ? withTracing(callableMock)
                                   : new CallableWithTracing(callableMock);

    // then
    assertThat(instance.origCallable).isSameAs(callableMock);
    assertThat(instance.spanStackForExecution).isEqualTo(spanStackMock);
    assertThat(instance.mdcContextMapForExecution).isEqualTo(mdcInfoMock);
}
 
Example #16
Source File: ArgCapturingHttpTagAndSpanNamingStrategy.java    From riposte with Apache License 2.0 5 votes vote down vote up
private ResponseTaggingArgs(
    Span span, REQ request, RES response, Throwable error,
    HttpTagAndSpanNamingAdapter adapter
) {
    this.span = span;
    this.request = request;
    this.response = response;
    this.error = error;
    this.adapter = adapter;
}
 
Example #17
Source File: HttpTagAndSpanNamingStrategyTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Override
protected void doHandleResponseAndErrorTagging(
    @NotNull Span span, @Nullable Object request, @Nullable Object response, @Nullable Throwable error,
    @NotNull HttpTagAndSpanNamingAdapter<Object, Object> adapter
) {

}
 
Example #18
Source File: CallableWithTracingAndMdcSupportTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void call_handles_tracing_and_mdc_info_as_expected(boolean throwException) throws Exception {
    // given
    throwExceptionDuringCall = throwException;
    Tracer.getInstance().startRequestWithRootSpan("foo");
    Deque<Span> spanStack = Tracer.getInstance().getCurrentSpanStackCopy();
    Map<String, String> mdcInfo = MDC.getCopyOfContextMap();
    CallableWithTracingAndMdcSupport instance = new CallableWithTracingAndMdcSupport(
        callableMock, spanStack, mdcInfo
    );
    resetTracingAndMdc();
    assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isNull();
    assertThat(MDC.getCopyOfContextMap()).isEmpty();

    // when
    Throwable ex = catchThrowable(() -> instance.call());

    // then
    verify(callableMock).call();
    if (throwException)
        assertThat(ex).isNotNull();
    else
        assertThat(ex).isNull();

    assertThat(currentSpanStackWhenCallableWasCalled.get(0)).isEqualTo(spanStack);
    assertThat(currentMdcInfoWhenCallableWasCalled.get(0)).isEqualTo(mdcInfo);

    assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isNull();
    assertThat(MDC.getCopyOfContextMap()).isEmpty();
}
 
Example #19
Source File: WingtipsSpringUtilTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
private void verifyListenableFutureCallbackWithTracing(ListenableFutureCallback result,
                                                       ListenableFutureCallback expectedCoreInstance,
                                                       Deque<Span> expectedSpanStack,
                                                       Map<String, String> expectedMdcInfo) {
    assertThat(result).isInstanceOf(ListenableFutureCallbackWithTracing.class);
    assertThat(Whitebox.getInternalState(result, "origListenableFutureCallback")).isSameAs(expectedCoreInstance);
    assertThat(Whitebox.getInternalState(result, "spanStackForExecution")).isEqualTo(expectedSpanStack);
    assertThat(Whitebox.getInternalState(result, "mdcContextMapForExecution")).isEqualTo(expectedMdcInfo);
}
 
Example #20
Source File: ChannelPipelineFinalizerHandlerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true   |   true",
    "false  |   true",
    "true   |   false",
    "false  |   false"
}, splitBy = "\\|")
@Test
public void doChannelInactive_completes_releases_resources_and_completes_tracing_if_necessary(
    boolean tracingAlreadyDone, boolean responseSendingCompleted
) throws Exception {
    // given
    Span span = setupTracingForChannelInactive(tracingAlreadyDone);
    doReturn(responseSendingCompleted).when(responseInfoMock).isResponseSendingLastChunkSent();
    if (responseSendingCompleted) {
        state.setResponseWriterFinalChunkChannelFuture(mock(ChannelFuture.class));
    }

    // when
    PipelineContinuationBehavior result = handler.doChannelInactive(ctxMock);

    // then
    Assertions.assertThat(span.isCompleted()).isEqualTo(!tracingAlreadyDone);
    Assertions.assertThat(state.isTraceCompletedOrScheduled()).isTrue();

    verify(requestInfoMock).releaseAllResources();
    verify(proxyRouterStateMock).cancelRequestStreaming(any(), any());
    verify(proxyRouterStateMock).cancelDownstreamRequest(any());
    Assertions.assertThat(result).isEqualTo(PipelineContinuationBehavior.CONTINUE);
}
 
Example #21
Source File: AsyncWingtipsHelperTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void linkTracingToCurrentThread_pair_works_as_expected_with_non_null_pair_and_null_innards(
    boolean useStaticMethod
) {
    // given
    Pair<Deque<Span>, Map<String, String>> infoForLinking = Pair.of(null, null);
    resetTracing();
    Tracer.getInstance().startRequestWithRootSpan("foo-" + UUID.randomUUID().toString());
    Pair<Deque<Span>, Map<String, String>> expectedPreCallInfo = Pair.of(
        Tracer.getInstance().getCurrentSpanStackCopy(),
        MDC.getCopyOfContextMap()
    );

    // when
    Pair<Deque<Span>, Map<String, String>> preCallInfo =
        (useStaticMethod)
        ? linkTracingToCurrentThread(infoForLinking)
        : DEFAULT_IMPL.linkTracingToCurrentThread(infoForLinking);
    
    Pair<Deque<Span>, Map<String, String>> postCallInfo = Pair.of(
        Tracer.getInstance().getCurrentSpanStackCopy(),
        MDC.getCopyOfContextMap()
    );

    // then
    assertThat(preCallInfo).isEqualTo(expectedPreCallInfo);
    assertThat(postCallInfo.getLeft()).isNull();
    assertThat(postCallInfo.getRight()).isNullOrEmpty();
}
 
Example #22
Source File: SpanParserTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Test
public void convertSpanToKeyValueFormat_should_function_properly_for_completed_spans() {
    // given: valid span and completed, and key/value string from SpanParser.convertSpanToKeyValueFormat()
    Span validSpan = Span.generateRootSpanForNewTrace(spanName, spanPurpose).build();
    completeSpan(validSpan);
    assertThat(validSpan.isCompleted()).isTrue();
    String keyValueStr = SpanParser.convertSpanToKeyValueFormat(validSpan);

    // when: the string is deserialized into a map
    Map<String, Object> deserializedValues = deserializeKeyValueSpanString(keyValueStr);

    // then: the original span and deserialized map values should be exactly the same
    verifySpanEqualsDeserializedValues(validSpan, deserializedValues);
}
 
Example #23
Source File: AsyncCompletionHandlerWithTracingAndMdcSupportTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "NULL",
    "EMPTY",
    "HAS_EXISTING_SPAN"
}, splitBy = "\\|")
@Test
public void getTraceForCall_works_as_expected(ExistingSpanStackState existingSpanStackState) {
    // given
    Deque<Span> spanStack;
    Span expectedResult;
    switch (existingSpanStackState) {
        case NULL:
            spanStack = null;
            expectedResult = null;
            break;
        case EMPTY:
            spanStack = new LinkedList<>();
            expectedResult = null;
            break;
        case HAS_EXISTING_SPAN:
            spanStack = handlerSpy.distributedTraceStackToUse;
            assertThat(spanStack).isNotEmpty();
            expectedResult = spanStack.peek();
            break;
        default:
            throw new IllegalArgumentException("Unhandled state: " + existingSpanStackState.name());
    }
    Whitebox.setInternalState(handlerSpy, "distributedTraceStackToUse", spanStack);

    // when
    Span spanForCall = handlerSpy.getSpanForCall();

    // then
    assertThat(spanForCall).isEqualTo(expectedResult);
}
 
Example #24
Source File: RequestTracingFilterComponentTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void verify_blocking_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(port)
            .headers(upstreamSpanInfo.getRight())
            .log().all()
        .when()
            .get(BLOCKING_PATH)
        .then()
            .log().all()
            .extract();

    assertThat(response.statusCode()).isEqualTo(200);
    assertThat(response.asString()).isEqualTo(BLOCKING_RESULT);
    Span completedSpan =
        verifySingleSpanCompletedAndReturnedInResponse(response, SLEEP_TIME_MILLIS, upstreamSpanInfo.getLeft());
    verifySpanNameAndTags(
        completedSpan,
        "GET",
        "GET",
        BLOCKING_PATH,
        "http://localhost:" + port + BLOCKING_PATH,
        null,
        response.statusCode(),
        null,
        "servlet"
    );
}
 
Example #25
Source File: VerifySampleEndpointsComponentTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
private Span findCompletedSpanByCriteria(Predicate<Span> criteria) {
    List<Span> matchingSpans = spanRecorder.completedSpans.stream().filter(criteria).collect(Collectors.toList());
    assertThat(matchingSpans)
        .withFailMessage(
            "Expected to find exactly 1 span matching the specified criteria - instead found: "
            + matchingSpans.size()
        )
        .hasSize(1);

    return matchingSpans.get(0);
}
 
Example #26
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_blocking_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(BLOCKING_PATH)
        .then()
            .log().all()
            .extract();

    assertThat(response.statusCode()).isEqualTo(200);
    assertThat(response.asString()).isEqualTo(BLOCKING_RESULT);
    Span completedSpan =
        verifySingleSpanCompletedAndReturnedInResponse(response, SLEEP_TIME_MILLIS, upstreamSpanInfo.getLeft());
    verifySpanNameAndTags(
        completedSpan,
        "GET " + BLOCKING_PATH,
        "GET",
        BLOCKING_PATH,
        "http://localhost:" + SERVER_PORT + BLOCKING_PATH + "?foo=bar",
        BLOCKING_PATH,
        response.statusCode(),
        null,
        "servlet"
    );
}
 
Example #27
Source File: AsyncWingtipsHelperJava7Test.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Test
public void runnableWithTracing_pair_works_as_expected() {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingInfo();

    // when
    Runnable result = runnableWithTracing(runnableMock, setupInfo);

    // then
    verifyRunnableWithTracing(result, runnableMock, setupInfo.getLeft(), setupInfo.getRight());
}
 
Example #28
Source File: ArgCapturingHttpTagAndSpanNamingStrategy.java    From riposte with Apache License 2.0 5 votes vote down vote up
public void verifyArgs(
    Span expectedSpan, REQ expectedRequest, RES expectedResponse,
    Throwable expectedError, HttpTagAndSpanNamingAdapter expectedAdapter
) {
    assertThat(span).isSameAs(expectedSpan);
    assertThat(request).isSameAs(expectedRequest);
    assertThat(response).isSameAs(expectedResponse);
    assertThat(error).isSameAs(expectedError);
    assertThat(adapter).isSameAs(expectedAdapter);
}
 
Example #29
Source File: ChannelPipelineFinalizerHandlerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
private Span setupTracingForChannelInactive(boolean traceCompletedOrScheduled) {
    state.setTraceCompletedOrScheduled(traceCompletedOrScheduled);
    Span span = Span.newBuilder("fooSpan", Span.SpanPurpose.SERVER).build();
    Assertions.assertThat(span.isCompleted()).isFalse();
    Deque<Span> spanStack = new LinkedList<>();
    spanStack.add(span);
    state.setDistributedTraceStack(spanStack);

    return span;
}
 
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_CompletableFuture_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_FUTURE_PATH)
        .then()
            .log().all()
            .extract();

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