TraceValve extends ValveBase { @Override public void invoke(Request request, Response response) throws IOException, ServletException { Tracer tracer = traceService.getTracer(); SpanContextHandle contextHandle = null; String traceHeader = request.getHeader(X_CLOUD_TRACE_HEADER); if (traceHeader != null) { SpanContext spanContext = traceService .getSpanContextFactory() .fromHeader(traceHeader); contextHandle = traceService.getSpanContextHandler().attach(spanContext); log.debug("Tracing request with header: " + request.getHeader(X_CLOUD_TRACE_HEADER)); } TraceContext context = tracer.startSpan(request.getRequestURI()); getNext().invoke(request, response); tracer.annotateSpan(context, createLabels(request, response)); tracer.endSpan(context); if (contextHandle != null) { contextHandle.detach(); } }  @Override void invoke(Request request, Response response); void setTraceScheduledDelay(Integer traceScheduledDelay); void setTraceService(TraceService traceService);  }
@Test public void testRequestForwarding() throws Exception { valve.invoke(request, response); verify(nextValve).invoke(any(), any()); }
@Test public void testSpanCreation() throws Exception { when(request.getRequestURI()).thenReturn("/index"); when(response.getStatus()).thenReturn(200); ArgumentCaptor<Labels> labelsArgument = ArgumentCaptor.forClass(Labels.class); ArgumentCaptor<TraceContext> traceArgument = ArgumentCaptor.forClass(TraceContext.class); Label indexLabel = new Label(HttpLabels.HTTP_URL.getValue(), "/index"); Label statusCodeLabel = new Label(HttpLabels.HTTP_STATUS_CODE.getValue(), "200"); valve.invoke(request, response); verify(tracer).startSpan(matches("/index")); verify(tracer).annotateSpan(traceArgument.capture(), labelsArgument.capture()); verify(tracer).endSpan(traceContext); assertEquals(labelsArgument.getValue().getLabels().size(), 2); assertTrue(labelsArgument.getValue().getLabels().contains(indexLabel)); assertTrue(labelsArgument.getValue().getLabels().contains(statusCodeLabel)); }
@Test public void testTraceHeader() throws Exception { SpanContext contextFromHeader = mock(SpanContext.class); when(request.getHeader(SpanContextFactory.headerKey())).thenReturn("traceid/spanid"); when(spanContextFactory.fromHeader("traceid/spanid")).thenReturn(contextFromHeader); valve.invoke(request, response); verify(spanContextHandler).attach(contextFromHeader); }
@Test public void testThatSpanHandleIsDetached() throws Exception { when(request.getHeader(anyString())).thenReturn(""); SpanContextHandle contextHandle = mock(SpanContextHandle.class); when(traceService.getSpanContextHandler().attach(any())).thenReturn(contextHandle); valve.invoke(request, response); verify(contextHandle).detach(); }