Removes Zipkin dependency from all tests (#1645)

Brave's SpanHandler can report natively in other formats which have different
constraints than Zipkin and often extensions to the data model.

This change ports all tests away from Zipkin's types so that it is more clear
what's actually recorded vs what's a side-effect of Zipkin conversion.

This removes `BlockingQueueSpanReporter` which was never released, also.
This commit is contained in:
Adrian Cole
2020-05-18 17:02:29 +08:00
committed by GitHub
parent 99ce7cdd1c
commit 40785d642a
101 changed files with 1070 additions and 1319 deletions

View File

@@ -33,7 +33,7 @@
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<spring-boot.version>2.2.5.RELEASE</spring-boot.version>
<brave.version>5.12.1</brave.version>
<brave.version>5.12.2</brave.version>
<okhttp.version>3.14.6</okhttp.version>
</properties>

View File

@@ -19,11 +19,10 @@ package org.springframework.cloud.sleuth.benchmarks.app.webflux;
import java.util.regex.Pattern;
import brave.sampler.Sampler;
import brave.handler.SpanHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.WebApplicationType;
@@ -80,8 +79,10 @@ public class SleuthBenchmarkingSpringWebFluxApp
}
@Bean
public Reporter<Span> reporter() {
return Reporter.NOOP;
public SpanHandler spanHandler() {
return new SpanHandler() {
// intentionally anonymous to prevent logging fallback on NOOP
};
}
@Override

View File

@@ -20,6 +20,7 @@ import java.io.IOException;
import java.util.concurrent.TimeUnit;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.http.HttpTracing;
import brave.httpclient.TracingHttpClientBuilder;
import brave.propagation.CurrentTraceContext;
@@ -45,7 +46,6 @@ import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import zipkin2.reporter.Reporter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
@@ -61,6 +61,9 @@ import org.springframework.context.ConfigurableApplicationContext;
@Threads(2)
@State(Scope.Benchmark)
public class SpringWebFluxBenchmarks {
static final SpanHandler FAKE_SPAN_HANDLER = new SpanHandler() {
// intentionally anonymous to prevent logging fallback on NOOP
};
protected static TraceContext defaultTraceContext = TraceContext.newBuilder()
.traceIdHigh(333L).traceId(444L).spanId(3).sampled(true).build();
@@ -109,9 +112,9 @@ public class SpringWebFluxBenchmarks {
baseUrl = "http://127.0.0.1:" + springWebFluxApp.port + "/foo";
client = newClient();
tracedClient = newClient(HttpTracing
.create(Tracing.newBuilder().spanReporter(Reporter.NOOP).build()));
.create(Tracing.newBuilder().addSpanHandler(FAKE_SPAN_HANDLER).build()));
unsampledClient = newClient(HttpTracing.create(Tracing.newBuilder()
.sampler(Sampler.NEVER_SAMPLE).spanReporter(Reporter.NOOP).build()));
.sampler(Sampler.NEVER_SAMPLE).addSpanHandler(FAKE_SPAN_HANDLER).build()));
postSetUp();
}

View File

@@ -264,7 +264,7 @@
<spring-cloud-stream.version>Horsham.SR3</spring-cloud-stream.version>
<spring-cloud-netflix.version>2.2.3.BUILD-SNAPSHOT</spring-cloud-netflix.version>
<spring-cloud-openfeign.version>2.2.3.BUILD-SNAPSHOT</spring-cloud-openfeign.version>
<brave.version>5.12.1</brave.version>
<brave.version>5.12.2</brave.version>
<spring-security-boot-autoconfigure.version>2.1.7.RELEASE</spring-security-boot-autoconfigure.version>
<spring-cloud-aws.version>2.2.1.RELEASE</spring-cloud-aws.version>
<disable.nohttp.checks>false</disable.nohttp.checks>

View File

@@ -1,74 +0,0 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.sleuth.util;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
/**
* Like {@link ArrayListSpanReporter}, except appropriate for async instrumentation.
*/
public class BlockingQueueSpanReporter implements Reporter<Span> {
private final LinkedBlockingQueue<Span> spans = new LinkedBlockingQueue<>();
/**
* Blocks until a span is reported or throws an {@link AssertionError}.
* @return the first span not yet taken.
*/
public Span takeSpan() {
Span result = takeSpan(3_000);
if (result == null) {
throw new AssertionError("Span was not reported");
}
return result;
}
@Override
public String toString() {
return "BlockingQueueSpanReporter{spans=" + spans + '}';
}
@Override
public void report(Span span) {
spans.add(span);
}
/** Use this as a post-condition to ensure all spans are accounted for. */
public void assertEmpty() {
if (takeSpan(100) != null) {
throw new AssertionError(
"Span remaining in queue. Check for redundant reporting!");
}
}
private Span takeSpan(long timeout) {
Span result;
try {
result = spans.poll(timeout, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError(e);
}
return result;
}
}

View File

@@ -66,12 +66,12 @@ public class SpanAdjusterTests {
return Sampler.ALWAYS_SAMPLE;
}
// This uses
@Bean
Reporter<zipkin2.Span> reporter() {
return new ArrayListSpanReporter();
}
// tag::adjuster[]
@Bean
SpanAdjuster adjusterOne() {
return span -> span.toBuilder().name("foo").build();
@@ -81,7 +81,6 @@ public class SpanAdjusterTests {
SpanAdjuster adjusterTwo() {
return span -> span.toBuilder().name(span.name() + " bar").build();
}
// end::adjuster[]
}

View File

@@ -22,16 +22,15 @@ import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.propagation.TraceContext;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -47,7 +46,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
public class SpanHandlerTests {
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Autowired
Tracer tracer;
@@ -58,8 +57,8 @@ public class SpanHandlerTests {
hello.finish();
BDDAssertions.then(this.reporter.getSpans()).hasSize(1);
BDDAssertions.then(this.reporter.getSpans().get(0).name()).isEqualTo("foo bar");
BDDAssertions.then(this.spans).hasSize(1);
BDDAssertions.then(this.spans.get(0).name()).isEqualTo("foo bar");
}
@Configuration
@@ -72,8 +71,8 @@ public class SpanHandlerTests {
}
@Bean
Reporter<zipkin2.Span> reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
// tag::spanHandler[]

View File

@@ -16,17 +16,18 @@
package org.springframework.cloud.sleuth.annotation;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import brave.Span;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.propagation.TraceContext;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.apache.commons.lang3.StringUtils;
import org.awaitility.Awaitility;
import org.junit.Before;
@@ -35,13 +36,10 @@ import org.junit.runner.RunWith;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import zipkin2.Annotation;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -61,7 +59,7 @@ public class SleuthSpanCreatorAspectFluxTests {
Tracer tracer;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
private static String toHexString(Long value) {
then(value).isNotNull();
@@ -84,7 +82,7 @@ public class SleuthSpanCreatorAspectFluxTests {
@Before
public void setup() {
this.reporter.clear();
this.spans.clear();
this.testBean.reset();
}
@@ -95,10 +93,9 @@ public class SleuthSpanCreatorAspectFluxTests {
verifyNoSpansUntilFluxComplete(flux);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -110,10 +107,9 @@ public class SleuthSpanCreatorAspectFluxTests {
verifyNoSpansUntilFluxComplete(flux);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method2");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method2");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -125,10 +121,9 @@ public class SleuthSpanCreatorAspectFluxTests {
verifyNoSpansUntilFluxComplete(flux);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method3");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method3");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -140,10 +135,9 @@ public class SleuthSpanCreatorAspectFluxTests {
verifyNoSpansUntilFluxComplete(flux);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method4");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method4");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -157,11 +151,10 @@ public class SleuthSpanCreatorAspectFluxTests {
verifyNoSpansUntilFluxComplete(flux);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method5");
then(spans.get(0).tags()).containsEntry("testTag", "test");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method5");
then(this.spans.get(0).tags()).containsEntry("testTag", "test");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -173,11 +166,10 @@ public class SleuthSpanCreatorAspectFluxTests {
verifyNoSpansUntilFluxComplete(flux);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method6");
then(spans.get(0).tags()).containsEntry("testTag6", "test");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method6");
then(this.spans.get(0).tags()).containsEntry("testTag6", "test");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -189,10 +181,9 @@ public class SleuthSpanCreatorAspectFluxTests {
verifyNoSpansUntilFluxComplete(flux);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method8");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method8");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -204,12 +195,11 @@ public class SleuthSpanCreatorAspectFluxTests {
verifyNoSpansUntilFluxComplete(flux);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method9");
then(spans.get(0).tags()).containsEntry("class", "TestBean")
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method9");
then(this.spans.get(0).tags()).containsEntry("class", "TestBean")
.containsEntry("method", "testMethod9");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -228,14 +218,13 @@ public class SleuthSpanCreatorAspectFluxTests {
}
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -246,14 +235,13 @@ public class SleuthSpanCreatorAspectFluxTests {
verifyNoSpansUntilFluxComplete(flux);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method10");
then(spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method10");
then(this.spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -272,14 +260,13 @@ public class SleuthSpanCreatorAspectFluxTests {
}
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -299,16 +286,15 @@ public class SleuthSpanCreatorAspectFluxTests {
}
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("class", "TestBean")
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("class", "TestBean")
.containsEntry("method", "testMethod11")
.containsEntry("customTestTag11", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -318,7 +304,7 @@ public class SleuthSpanCreatorAspectFluxTests {
try {
Flux<String> flux = this.testBean.testMethod12("test");
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
flux.toIterable().iterator().next();
}
@@ -326,12 +312,11 @@ public class SleuthSpanCreatorAspectFluxTests {
}
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method12");
then(spans.get(0).tags()).containsEntry("testTag12", "test")
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method12");
then(this.spans.get(0).tags()).containsEntry("testTag12", "test")
.containsEntry("error", "test exception 12");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -344,7 +329,7 @@ public class SleuthSpanCreatorAspectFluxTests {
// tag::continue_span_execution[]
Flux<String> flux = this.testBean.testMethod13();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
flux.toIterable().iterator().next();
// end::continue_span_execution[]
@@ -356,14 +341,13 @@ public class SleuthSpanCreatorAspectFluxTests {
}
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("error", "test exception 13");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("error", "test exception 13");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("testMethod13.before",
"testMethod13.afterFailure", "testMethod13.after");
then(spans.get(0).duration()).isNotZero();
then(spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -374,8 +358,7 @@ public class SleuthSpanCreatorAspectFluxTests {
verifyNoSpansUntilFluxComplete(flux);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = new ArrayList<>(this.reporter.getSpans());
then(spans).isEmpty();
then(this.spans).isEmpty();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -386,10 +369,9 @@ public class SleuthSpanCreatorAspectFluxTests {
Long newSpanId = flux.blockFirst();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("span-in-trace-context");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("span-in-trace-context");
then(this.spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(this.tracer.currentSpan()).isNull();
});
}
@@ -400,10 +382,9 @@ public class SleuthSpanCreatorAspectFluxTests {
Long newSpanId = flux.blockFirst();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("span-in-subscriber-context");
then(spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("span-in-subscriber-context");
then(this.spans.get(0).id()).isEqualTo(toHexString(newSpanId));
then(this.tracer.currentSpan()).isNull();
});
}
@@ -411,12 +392,12 @@ public class SleuthSpanCreatorAspectFluxTests {
private void verifyNoSpansUntilFluxComplete(Flux<String> flux) {
Iterator<String> iterator = flux.toIterable().iterator();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
this.testBean.proceed();
String result1 = iterator.next();
then(result1).isEqualTo(TEST_STRING1);
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
this.testBean.proceed();
String result2 = iterator.next();
@@ -625,8 +606,8 @@ public class SleuthSpanCreatorAspectFluxTests {
}
@Bean
Reporter<zipkin2.Span> spanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -16,8 +16,6 @@
package org.springframework.cloud.sleuth.annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collector;
@@ -27,19 +25,19 @@ import javax.annotation.concurrent.NotThreadSafe;
import brave.Span;
import brave.Tracer;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import reactor.core.publisher.Mono;
import zipkin2.Annotation;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
@@ -66,7 +64,7 @@ public class SleuthSpanCreatorAspectMonoTests {
Tracer tracer;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
protected static String id(Tracer tracer) {
if (tracer.currentSpan() == null) {
@@ -77,22 +75,21 @@ public class SleuthSpanCreatorAspectMonoTests {
@Before
public void setup() {
this.reporter.clear();
this.spans.clear();
}
@Test
public void shouldCreateSpanWhenAnnotationOnInterfaceMethod() {
Mono<String> mono = this.testBean.testMethod();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -101,15 +98,14 @@ public class SleuthSpanCreatorAspectMonoTests {
public void shouldCreateSpanWhenAnnotationOnClassMethod() {
Mono<String> mono = this.testBean.testMethod2();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method2");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method2");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -118,16 +114,15 @@ public class SleuthSpanCreatorAspectMonoTests {
public void shouldCreateSpanWithCustomNameWhenAnnotationOnClassMethod() {
Mono<String> mono = this.testBean.testMethod3();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
String result = mono.block();
Awaitility.await().untilAsserted(() -> {
then(result).isEqualTo(TEST_STRING);
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method3");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method3");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -136,15 +131,14 @@ public class SleuthSpanCreatorAspectMonoTests {
public void shouldCreateSpanWithCustomNameWhenAnnotationOnInterfaceMethod() {
Mono<String> mono = this.testBean.testMethod4();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method4");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method4");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -155,16 +149,15 @@ public class SleuthSpanCreatorAspectMonoTests {
Mono<String> mono = this.testBean.testMethod5("test");
// end::execution[]
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method5");
then(spans.get(0).tags()).containsEntry("testTag", "test");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method5");
then(this.spans.get(0).tags()).containsEntry("testTag", "test");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -173,16 +166,15 @@ public class SleuthSpanCreatorAspectMonoTests {
public void shouldCreateSpanWithTagWhenAnnotationOnClassMethod() {
Mono<String> mono = this.testBean.testMethod6("test");
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method6");
then(spans.get(0).tags()).containsEntry("testTag6", "test");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method6");
then(this.spans.get(0).tags()).containsEntry("testTag6", "test");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -191,15 +183,14 @@ public class SleuthSpanCreatorAspectMonoTests {
public void shouldCreateSpanWithLogWhenAnnotationOnInterfaceMethod() {
Mono<String> mono = this.testBean.testMethod8("test");
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method8");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method8");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -208,17 +199,16 @@ public class SleuthSpanCreatorAspectMonoTests {
public void shouldCreateSpanWithLogWhenAnnotationOnClassMethod() {
Mono<String> mono = this.testBean.testMethod9("test");
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method9");
then(spans.get(0).tags()).containsEntry("class", "TestBean")
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method9");
then(this.spans.get(0).tags()).containsEntry("class", "TestBean")
.containsEntry("method", "testMethod9");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -230,7 +220,7 @@ public class SleuthSpanCreatorAspectMonoTests {
try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.start())) {
Mono<String> mono = this.testBean.testMethod10("test");
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
}
@@ -239,14 +229,13 @@ public class SleuthSpanCreatorAspectMonoTests {
}
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -256,14 +245,13 @@ public class SleuthSpanCreatorAspectMonoTests {
this.testBean.testMethod10("test").block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method10");
then(spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method10");
then(this.spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -275,7 +263,7 @@ public class SleuthSpanCreatorAspectMonoTests {
try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.start())) {
Mono<String> mono = this.testBean.testMethod10_v2("test");
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
}
@@ -284,14 +272,13 @@ public class SleuthSpanCreatorAspectMonoTests {
}
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -304,7 +291,7 @@ public class SleuthSpanCreatorAspectMonoTests {
// tag::continue_span_execution[]
Mono<String> mono = this.testBean.testMethod11("test");
// end::continue_span_execution[]
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
}
@@ -313,16 +300,15 @@ public class SleuthSpanCreatorAspectMonoTests {
}
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("class", "TestBean")
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("class", "TestBean")
.containsEntry("method", "testMethod11")
.containsEntry("customTestTag11", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -332,7 +318,7 @@ public class SleuthSpanCreatorAspectMonoTests {
try {
Mono<String> mono = this.testBean.testMethod12("test");
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
}
@@ -340,12 +326,11 @@ public class SleuthSpanCreatorAspectMonoTests {
}
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method12");
then(spans.get(0).tags()).containsEntry("testTag12", "test")
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method12");
then(this.spans.get(0).tags()).containsEntry("testTag12", "test")
.containsEntry("error", "test exception 12");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -358,7 +343,7 @@ public class SleuthSpanCreatorAspectMonoTests {
// tag::continue_span_execution[]
Mono<String> mono = this.testBean.testMethod13();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
mono.block();
// end::continue_span_execution[]
@@ -370,14 +355,13 @@ public class SleuthSpanCreatorAspectMonoTests {
}
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("error", "test exception 13");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("error", "test exception 13");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("testMethod13.before",
"testMethod13.afterFailure", "testMethod13.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -388,8 +372,7 @@ public class SleuthSpanCreatorAspectMonoTests {
mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = new ArrayList<>(this.reporter.getSpans());
then(spans).isEmpty();
then(this.spans).isEmpty();
then(this.tracer.currentSpan()).isNull();
});
}
@@ -398,15 +381,14 @@ public class SleuthSpanCreatorAspectMonoTests {
public void shouldReturnNewSpanFromTraceContext() {
Mono<String> mono = this.testBean.newSpanInTraceContext();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
String newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("span-in-trace-context");
then(spans.get(0).id()).isEqualTo(newSpanId);
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("span-in-trace-context");
then(this.spans.get(0).id()).isEqualTo(newSpanId);
then(this.tracer.currentSpan()).isNull();
});
}
@@ -416,7 +398,7 @@ public class SleuthSpanCreatorAspectMonoTests {
Mono<Pair<Pair<String, String>, String>> mono = this.testBeanOuter
.outerNewSpanInTraceContext();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
Pair<Pair<String, String>, String> pair = mono.block();
String outerSpanIdBefore = pair.getFirst().getFirst();
@@ -425,14 +407,13 @@ public class SleuthSpanCreatorAspectMonoTests {
then(outerSpanIdBefore).isNotEqualTo(innerSpanId);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
zipkin2.Span outerSpan = spans.stream()
MutableSpan outerSpan = spans.spans().stream()
.filter(span -> span.name().equals("outer-span-in-trace-context"))
.findFirst().orElseThrow(() -> new AssertionError(
"No span with name [outer-span-in-trace-context] found"));
then(outerSpan.name()).isEqualTo("outer-span-in-trace-context");
then(outerSpan.id()).isEqualTo(outerSpanIdBefore);
zipkin2.Span innerSpan = spans.stream()
MutableSpan innerSpan = spans.spans().stream()
.filter(span -> span.name().equals("span-in-trace-context"))
.findFirst().orElseThrow(() -> new AssertionError(
"No span with name [span-in-trace-context] found"));
@@ -446,15 +427,14 @@ public class SleuthSpanCreatorAspectMonoTests {
public void shouldReturnNewSpanFromSubscriberContext() {
Mono<String> mono = this.testBean.newSpanInSubscriberContext();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
String newSpanId = mono.block();
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("span-in-subscriber-context");
then(spans.get(0).id()).isEqualTo(newSpanId);
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("span-in-subscriber-context");
then(this.spans.get(0).id()).isEqualTo(newSpanId);
then(this.tracer.currentSpan()).isNull();
});
}
@@ -464,7 +444,7 @@ public class SleuthSpanCreatorAspectMonoTests {
Mono<Pair<Pair<String, String>, String>> mono = this.testBeanOuter
.outerNewSpanInSubscriberContext();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
Pair<Pair<String, String>, String> pair = mono.block();
String outerSpanIdBefore = pair.getFirst().getFirst();
@@ -473,14 +453,13 @@ public class SleuthSpanCreatorAspectMonoTests {
then(outerSpanIdBefore).isNotEqualTo(innerSpanId);
Awaitility.await().untilAsserted(() -> {
List<zipkin2.Span> spans = this.reporter.getSpans();
zipkin2.Span outerSpan = spans.stream().filter(
MutableSpan outerSpan = spans.spans().stream().filter(
span -> span.name().equals("outer-span-in-subscriber-context"))
.findFirst().orElseThrow(() -> new AssertionError(
"No span with name [outer-span-in-subscriber-context] found"));
then(outerSpan.name()).isEqualTo("outer-span-in-subscriber-context");
then(outerSpan.id()).isEqualTo(outerSpanIdBefore);
zipkin2.Span innerSpan = spans.stream()
MutableSpan innerSpan = spans.spans().stream()
.filter(span -> span.name().equals("span-in-subscriber-context"))
.findFirst().orElseThrow(() -> new AssertionError(
"No span with name [span-in-subscriber-context] found"));
@@ -697,8 +676,8 @@ public class SleuthSpanCreatorAspectMonoTests {
}
@Bean
Reporter<zipkin2.Span> spanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -16,19 +16,16 @@
package org.springframework.cloud.sleuth.annotation;
import java.util.List;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -46,27 +43,26 @@ public class SleuthSpanCreatorAspectNegativeTests {
TestBeanInterface annotatedTestBean;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void setup() {
this.reporter.clear();
this.spans.clear();
}
@Test
public void shouldNotCallAdviceForNotAnnotatedBean() {
this.testBean.testMethod();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
}
@Test
public void shouldCallAdviceForAnnotatedBean() throws Throwable {
this.annotatedTestBean.testMethod();
List<Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method");
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method");
}
protected interface NotAnnotatedTestBeanInterface {
@@ -145,8 +141,8 @@ public class SleuthSpanCreatorAspectNegativeTests {
protected static class TestConfiguration {
@Bean
Reporter<Span> spanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -16,22 +16,21 @@
package org.springframework.cloud.sleuth.annotation;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import brave.Span;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Annotation;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
@@ -52,21 +51,20 @@ public class SleuthSpanCreatorAspectTests {
Tracer tracer;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void setup() {
this.reporter.clear();
this.spans.clear();
}
@Test
public void shouldCreateSpanWhenAnnotationOnInterfaceMethod() {
this.testBean.testMethod();
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -74,10 +72,9 @@ public class SleuthSpanCreatorAspectTests {
public void shouldCreateSpanWhenAnnotationOnClassMethod() {
this.testBean.testMethod2();
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method2");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method2");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -85,10 +82,9 @@ public class SleuthSpanCreatorAspectTests {
public void shouldCreateSpanWithCustomNameWhenAnnotationOnClassMethod() {
this.testBean.testMethod3();
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method3");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method3");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -96,10 +92,9 @@ public class SleuthSpanCreatorAspectTests {
public void shouldCreateSpanWithCustomNameWhenAnnotationOnInterfaceMethod() {
this.testBean.testMethod4();
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method4");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method4");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -109,11 +104,10 @@ public class SleuthSpanCreatorAspectTests {
this.testBean.testMethod5("test");
// end::execution[]
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method5");
then(spans.get(0).tags()).containsEntry("testTag", "test");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method5");
then(this.spans.get(0).tags()).containsEntry("testTag", "test");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -121,11 +115,10 @@ public class SleuthSpanCreatorAspectTests {
public void shouldCreateSpanWithTagWhenAnnotationOnClassMethod() {
this.testBean.testMethod6("test");
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method6");
then(spans.get(0).tags()).containsEntry("testTag6", "test");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method6");
then(this.spans.get(0).tags()).containsEntry("testTag6", "test");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -133,10 +126,9 @@ public class SleuthSpanCreatorAspectTests {
public void shouldCreateSpanWithLogWhenAnnotationOnInterfaceMethod() {
this.testBean.testMethod8("test");
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method8");
then(spans.get(0).duration()).isNotZero();
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method8");
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -144,12 +136,11 @@ public class SleuthSpanCreatorAspectTests {
public void shouldCreateSpanWithLogWhenAnnotationOnClassMethod() {
this.testBean.testMethod9("test");
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("custom-name-on-test-method9");
then(spans.get(0).tags()).containsEntry("class", "TestBean")
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("custom-name-on-test-method9");
then(this.spans.get(0).tags()).containsEntry("class", "TestBean")
.containsEntry("method", "testMethod9");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -164,14 +155,13 @@ public class SleuthSpanCreatorAspectTests {
span.finish();
}
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -179,14 +169,13 @@ public class SleuthSpanCreatorAspectTests {
public void shouldStartAndCloseSpanOnContinueSpanIfSpanNotSet() {
this.testBean.testMethod10("test");
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method10");
then(spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method10");
then(this.spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -201,14 +190,13 @@ public class SleuthSpanCreatorAspectTests {
span.finish();
}
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("customTestTag10", "test");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -225,16 +213,15 @@ public class SleuthSpanCreatorAspectTests {
span.finish();
}
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("class", "TestBean")
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("class", "TestBean")
.containsEntry("method", "testMethod11")
.containsEntry("customTestTag11", "test");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("customTest.before",
"customTest.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -246,12 +233,11 @@ public class SleuthSpanCreatorAspectTests {
catch (RuntimeException ignored) {
}
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("test-method12");
then(spans.get(0).tags()).containsEntry("testTag12", "test")
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("test-method12");
then(this.spans.get(0).tags()).containsEntry("testTag12", "test")
.containsEntry("error", "test exception 12");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -270,14 +256,13 @@ public class SleuthSpanCreatorAspectTests {
span.finish();
}
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("foo");
then(spans.get(0).tags()).containsEntry("error", "test exception 13");
then(spans.get(0).annotations().stream().map(Annotation::value)
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("foo");
then(this.spans.get(0).tags()).containsEntry("error", "test exception 13");
then(this.spans.get(0).annotations().stream().map(Map.Entry::getValue)
.collect(Collectors.toList())).contains("testMethod13.before",
"testMethod13.afterFailure", "testMethod13.after");
then(spans.get(0).duration()).isNotZero();
then(this.spans.get(0).finishTimestamp()).isNotZero();
then(this.tracer.currentSpan()).isNull();
}
@@ -285,8 +270,7 @@ public class SleuthSpanCreatorAspectTests {
public void shouldNotCreateSpanWhenNotAnnotated() {
this.testBean.testMethod7();
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).isEmpty();
then(this.spans).isEmpty();
then(this.tracer.currentSpan()).isNull();
}
@@ -426,8 +410,8 @@ public class SleuthSpanCreatorAspectTests {
}
@Bean
Reporter<zipkin2.Span> spanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -16,15 +16,14 @@
package org.springframework.cloud.sleuth.annotation;
import brave.handler.SpanHandler;
import brave.test.TestSpanHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -65,8 +64,8 @@ public class SleuthSpanCreatorCircularDependencyTests {
protected static class TestConfiguration {
@Bean
Reporter<Span> spanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -16,7 +16,6 @@
package org.springframework.cloud.sleuth.documentation;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
@@ -27,8 +26,10 @@ import java.util.concurrent.Future;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.propagation.StrictCurrentTraceContext;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.assertj.core.api.BDDAssertions;
import org.junit.After;
import org.junit.Before;
@@ -39,7 +40,6 @@ import org.springframework.cloud.sleuth.SpanName;
import org.springframework.cloud.sleuth.SpanNamer;
import org.springframework.cloud.sleuth.instrument.async.TraceCallable;
import org.springframework.cloud.sleuth.instrument.async.TraceRunnable;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -53,18 +53,18 @@ import static org.assertj.core.api.BDDAssertions.then;
*/
public class SpringCloudSleuthDocTests {
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.sampler(Sampler.ALWAYS_SAMPLE).spanReporter(this.reporter).build();
.sampler(Sampler.ALWAYS_SAMPLE).addSpanHandler(this.spans).build();
Tracer tracer = this.tracing.tracer();
@Before
public void setup() {
this.reporter.clear();
this.spans.clear();
}
@After
@@ -87,9 +87,8 @@ public class SpringCloudSleuthDocTests {
future.get();
// end::span_name_annotated_runnable_execution[]
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("calculatetax");
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("calculateTax");
}
@Test
@@ -115,9 +114,8 @@ public class SpringCloudSleuthDocTests {
future.get();
// end::span_name_to_string_runnable_execution[]
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("calculatetax");
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("calculateTax");
executorService.shutdown();
}
@@ -144,11 +142,10 @@ public class SpringCloudSleuthDocTests {
}
// end::manual_span_creation[]
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("calculatetax");
then(spans.get(0).tags()).containsEntry("taxValue", "10");
then(spans.get(0).annotations()).hasSize(1);
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("calculateTax");
then(this.spans.get(0).tags()).containsEntry("taxValue", "10");
then(this.spans.get(0).annotations()).hasSize(1);
}
@Test
@@ -182,9 +179,8 @@ public class SpringCloudSleuthDocTests {
newSpan.finish();
}
List<zipkin2.Span> spans = this.reporter.getSpans();
BDDAssertions.then(spans).hasSize(1);
BDDAssertions.then(spans.get(0).name()).isEqualTo("calculatetax");
BDDAssertions.then(spans.get(0).name()).isEqualTo("calculateTax");
BDDAssertions.then(spans.get(0).tags()).containsEntry("taxValue", "10");
BDDAssertions.then(spans.get(0).annotations()).hasSize(1);
executorService.shutdown();
@@ -222,9 +218,8 @@ public class SpringCloudSleuthDocTests {
// end::manual_span_joining[]
}).get();
List<zipkin2.Span> spans = this.reporter.getSpans();
Optional<zipkin2.Span> calculateTax = spans.stream()
.filter(span -> span.name().equals("calculatecommission")).findFirst();
Optional<MutableSpan> calculateTax = spans.spans().stream()
.filter(span -> span.name().equals("calculateCommission")).findFirst();
BDDAssertions.then(calculateTax).isPresent();
BDDAssertions.then(calculateTax.get().tags()).containsEntry("commissionValue",
"10");

View File

@@ -18,6 +18,7 @@ package org.springframework.cloud.sleuth.instrument.async;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.assertj.core.api.BDDAssertions;
@@ -28,7 +29,6 @@ import org.mockito.BDDMockito;
import org.mockito.Mockito;
import org.springframework.cloud.sleuth.DefaultSpanNamer;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
/**
* @author Marcin Grzejszczak
@@ -37,10 +37,10 @@ public class TraceAsyncAspectTest {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
ProceedingJoinPoint point = Mockito.mock(ProceedingJoinPoint.class);
@@ -73,9 +73,9 @@ public class TraceAsyncAspectTest {
asyncAspect.traceBackgroundThread(this.point);
BDDAssertions.then(this.reporter.getSpans()).hasSize(1);
BDDAssertions.then(this.reporter.getSpans().get(0).name()).isEqualTo("foo-bar");
BDDAssertions.then(this.reporter.getSpans().get(0).timestamp()).isPositive();
BDDAssertions.then(this.spans).hasSize(1);
BDDAssertions.then(this.spans.get(0).name()).isEqualTo("foo-bar");
BDDAssertions.then(this.spans.get(0).finishTimestamp()).isPositive();
}
}

View File

@@ -24,6 +24,7 @@ import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -31,7 +32,6 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.cloud.sleuth.DefaultSpanNamer;
import org.springframework.cloud.sleuth.SpanName;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import static org.assertj.core.api.BDDAssertions.then;
@@ -42,10 +42,10 @@ public class TraceCallableTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
Tracer tracer = this.tracing.tracer();
@@ -53,7 +53,7 @@ public class TraceCallableTests {
public void clean() {
this.executor.shutdown();
this.tracing.close();
this.reporter.clear();
this.spans.clear();
this.currentTraceContext.close();
}
@@ -98,9 +98,8 @@ public class TraceCallableTests {
public void should_take_name_of_span_from_span_name_annotation() throws Exception {
whenATraceKeepingCallableGetsSubmitted();
then(this.reporter.getSpans()).hasSize(1);
then(this.reporter.getSpans().get(0).name())
.isEqualTo("some-callable-name-from-annotation");
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("some-callable-name-from-annotation");
}
@Test
@@ -108,9 +107,8 @@ public class TraceCallableTests {
throws Exception {
whenCallableGetsSubmitted(thatRetrievesTraceFromThreadLocal());
then(this.reporter.getSpans()).hasSize(1);
then(this.reporter.getSpans().get(0).name())
.isEqualTo("some-callable-name-from-to-string");
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("some-callable-name-from-to-string");
}
private Callable<Span> thatRetrievesTraceFromThreadLocal() {

View File

@@ -24,6 +24,7 @@ import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -31,7 +32,6 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.cloud.sleuth.DefaultSpanNamer;
import org.springframework.cloud.sleuth.SpanName;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import static org.assertj.core.api.BDDAssertions.then;
@@ -42,10 +42,10 @@ public class TraceRunnableTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
Tracer tracer = this.tracing.tracer();
@@ -53,7 +53,7 @@ public class TraceRunnableTests {
public void clean() {
this.executor.shutdown();
this.tracing.close();
this.reporter.clear();
this.spans.clear();
this.currentTraceContext.close();
}
@@ -102,9 +102,8 @@ public class TraceRunnableTests {
whenRunnableGetsSubmitted(traceKeepingRunnable);
then(this.reporter.getSpans()).hasSize(1);
then(this.reporter.getSpans().get(0).name())
.isEqualTo("some-runnable-name-from-annotation");
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("some-runnable-name-from-annotation");
}
@Test
@@ -115,9 +114,8 @@ public class TraceRunnableTests {
whenRunnableGetsSubmitted(runnable);
then(this.reporter.getSpans()).hasSize(1);
then(this.reporter.getSpans().get(0).name())
.isEqualTo("some-runnable-name-from-to-string");
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("some-runnable-name-from-to-string");
}
private TraceKeepingRunnable runnableThatRetrievesTraceFromThreadLocal() {

View File

@@ -33,6 +33,7 @@ import brave.Tracer;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.propagation.TraceContext;
import brave.test.TestSpanHandler;
import org.assertj.core.api.BDDAssertions;
import org.junit.After;
import org.junit.Before;
@@ -47,7 +48,6 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.cloud.sleuth.DefaultSpanNamer;
import org.springframework.cloud.sleuth.SpanNamer;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.BDDAssertions.then;
@@ -66,10 +66,10 @@ public class TraceableExecutorServiceTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
Tracer tracer = this.tracing.tracer();
@@ -79,7 +79,7 @@ public class TraceableExecutorServiceTests {
public void setup() {
this.traceManagerableExecutorService = new TraceableExecutorService(
beanFactory(true), this.executorService);
this.reporter.clear();
this.spans.clear();
this.spanVerifyingRunnable.clear();
}

View File

@@ -21,7 +21,10 @@ import java.util.concurrent.atomic.AtomicReference;
import brave.ScopedSpan;
import brave.Span;
import brave.Tracer;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.assertj.core.api.BDDAssertions;
import org.junit.Before;
import org.junit.Test;
@@ -32,7 +35,6 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -44,7 +46,7 @@ import static org.assertj.core.api.BDDAssertions.then;
public class CircuitBreakerIntegrationTests {
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Autowired
Tracer tracer;
@@ -54,7 +56,7 @@ public class CircuitBreakerIntegrationTests {
@Before
public void setup() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -94,7 +96,7 @@ public class CircuitBreakerIntegrationTests {
throw new IllegalStateException("boom2");
})).isInstanceOf(IllegalStateException.class).hasMessageContaining("boom2");
then(this.reporter.getSpans()).hasSize(2);
then(this.spans).hasSize(2);
then(scopedSpan.context().traceIdString())
.isEqualTo(first.get().context().traceIdString());
then(scopedSpan.context().traceIdString())
@@ -102,12 +104,12 @@ public class CircuitBreakerIntegrationTests {
then(first.get().context().spanIdString())
.isNotEqualTo(second.get().context().spanIdString());
zipkin2.Span reportedSpan = this.reporter.getSpans().get(0);
then(reportedSpan.name()).contains("circuitbreakerintegrationtests");
MutableSpan reportedSpan = this.spans.get(0);
then(reportedSpan.name()).contains("CircuitBreakerIntegrationTests");
then(reportedSpan.tags().get("error")).contains("boom");
reportedSpan = this.reporter.getSpans().get(1);
then(reportedSpan.name()).contains("circuitbreakerintegrationtests");
reportedSpan = this.spans.get(1);
then(reportedSpan.name()).contains("CircuitBreakerIntegrationTests");
then(reportedSpan.tags().get("error")).contains("boom2");
}
finally {
@@ -120,8 +122,8 @@ public class CircuitBreakerIntegrationTests {
static class Config {
@Bean
ArrayListSpanReporter arrayListSpanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -22,15 +22,16 @@ import brave.ScopedSpan;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.propagation.StrictCurrentTraceContext;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.assertj.core.api.BDDAssertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import static org.assertj.core.api.BDDAssertions.then;
@@ -38,16 +39,16 @@ public class CircuitBreakerTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).sampler(Sampler.ALWAYS_SAMPLE).build();
.addSpanHandler(this.spans).sampler(Sampler.ALWAYS_SAMPLE).build();
Tracer tracer = this.tracing.tracer();
@Before
public void setup() {
this.reporter.clear();
this.spans.clear();
}
@After
@@ -96,7 +97,7 @@ public class CircuitBreakerTests {
}))).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("boom2");
then(this.reporter.getSpans()).hasSize(2);
then(this.spans).hasSize(2);
then(scopedSpan.context().traceIdString())
.isEqualTo(first.get().context().traceIdString());
then(scopedSpan.context().traceIdString())
@@ -104,8 +105,8 @@ public class CircuitBreakerTests {
then(first.get().context().spanIdString())
.isNotEqualTo(second.get().context().spanIdString());
zipkin2.Span reportedSpan = this.reporter.getSpans().get(1);
then(reportedSpan.name()).contains("circuitbreakertests");
MutableSpan reportedSpan = this.spans.get(1);
then(reportedSpan.name()).contains("CircuitBreakerTests");
then(reportedSpan.tags().get("error")).contains("boom2");
}
finally {

View File

@@ -24,6 +24,7 @@ import brave.Tracing;
import brave.propagation.CurrentTraceContext;
import brave.propagation.StrictCurrentTraceContext;
import brave.propagation.TraceContext;
import brave.test.TestSpanHandler;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.HystrixPlugins;
@@ -42,7 +43,6 @@ import org.mockito.Mockito;
import org.springframework.cloud.sleuth.DefaultSpanNamer;
import org.springframework.cloud.sleuth.instrument.async.TraceCallable;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import static org.assertj.core.api.BDDAssertions.then;
@@ -51,18 +51,18 @@ import static org.assertj.core.api.BDDAssertions.then;
*/
public class SleuthHystrixConcurrencyStrategyTest {
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
@Before
@After
public void setup() {
HystrixPlugins.reset();
this.reporter.clear();
this.spans.clear();
this.currentTraceContext.close();
}
@@ -122,7 +122,7 @@ public class SleuthHystrixConcurrencyStrategyTest {
callable.call();
then(callable).isInstanceOf(TraceCallable.class);
then(this.reporter.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
}
@Test

View File

@@ -16,7 +16,6 @@
package org.springframework.cloud.sleuth.instrument.hystrix;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import brave.Span;
@@ -24,6 +23,7 @@ import brave.Tracer;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
@@ -34,8 +34,6 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import static com.netflix.hystrix.HystrixCommand.Setter.withGroupKey;
import static com.netflix.hystrix.HystrixCommandGroupKey.Factory.asKey;
import static org.assertj.core.api.BDDAssertions.then;
@@ -44,17 +42,17 @@ public class TraceCommandTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(currentTraceContext)
.spanReporter(this.reporter).sampler(Sampler.ALWAYS_SAMPLE).build();
.addSpanHandler(this.spans).sampler(Sampler.ALWAYS_SAMPLE).build();
Tracer tracer = this.tracing.tracer();
@Before
public void setup() {
HystrixPlugins.reset();
this.reporter.clear();
this.spans.clear();
}
@After
@@ -80,10 +78,9 @@ public class TraceCommandTests {
throws Exception {
whenCommandIsExecuted(traceReturningCommand());
then(this.reporter.getSpans()).hasSize(1);
then(this.reporter.getSpans().get(0).tags()).containsEntry("commandKey",
"traceCommandKey");
then(this.reporter.getSpans().get(0).duration()).isGreaterThan(0L);
then(this.spans).hasSize(1);
then(this.spans.get(0).tags()).containsEntry("commandKey", "traceCommandKey");
then(this.spans.get(0).finishTimestamp()).isGreaterThan(0L);
}
@Test
@@ -98,10 +95,9 @@ public class TraceCommandTests {
span.finish();
}
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(2);
then(spans.get(0).traceId()).isEqualTo(span.context().traceIdString());
then(spans.get(0).tags()).containsEntry("commandKey", "traceCommandKey")
then(this.spans).hasSize(2);
then(this.spans.get(0).traceId()).isEqualTo(span.context().traceIdString());
then(this.spans.get(0).tags()).containsEntry("commandKey", "traceCommandKey")
.containsEntry("commandGroup", "group")
.containsEntry("threadPoolKey", "group");
}
@@ -162,10 +158,9 @@ public class TraceCommandTests {
BDDAssertions.then(span.context().traceIdString())
.isEqualTo(spanBeforeThrowingException.get().context().traceIdString());
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).traceId()).isEqualTo(span.context().traceIdString());
then(spans.get(0).tags()).containsEntry("commandKey", "command")
then(this.spans).hasSize(1);
then(this.spans.get(0).traceId()).isEqualTo(span.context().traceIdString());
then(this.spans.get(0).tags()).containsEntry("commandKey", "command")
.containsEntry("commandGroup", "group")
.containsEntry("threadPoolKey", "group")
.containsEntry("fallbackMethodName", "getFallback_foobar");

View File

@@ -16,19 +16,20 @@
package org.springframework.cloud.sleuth.instrument.messaging;
import brave.handler.SpanHandler;
import brave.messaging.MessagingRequest;
import brave.messaging.MessagingRuleSampler;
import brave.sampler.Matchers;
import brave.sampler.RateLimitingSampler;
import brave.sampler.Sampler;
import brave.sampler.SamplerFunction;
import brave.test.TestSpanHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -55,8 +56,8 @@ public class TraceMessagingAutoConfigurationIntegrationTests {
public static class Config {
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
// tag::custom_messaging_consumer_sampler[]

View File

@@ -22,11 +22,13 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import brave.Span;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Test;
import zipkin2.Span;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.integration.channel.DirectChannel;
@@ -52,10 +54,10 @@ public class TracingChannelInterceptorTest {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
List<Span> spans = new ArrayList<>();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.spans::add).build();
.addSpanHandler(this.spans).build();
ChannelInterceptor interceptor = TracingChannelInterceptor.create(tracing);
@@ -94,7 +96,7 @@ public class TracingChannelInterceptorTest {
assertThat(this.channel.receive().getHeaders()).containsKeys("X-B3-TraceId",
"X-B3-SpanId", "X-B3-Sampled", "nativeHeaders");
assertThat(this.spans).hasSize(1).flatExtracting(Span::kind)
assertThat(this.spans).hasSize(1).extracting(MutableSpan::kind)
.containsExactly(Span.Kind.PRODUCER);
}
@@ -107,7 +109,7 @@ public class TracingChannelInterceptorTest {
assertThat(this.message).isNotNull();
assertThat(this.message.getHeaders()).containsKeys("X-B3-TraceId", "X-B3-SpanId",
"X-B3-Sampled", "nativeHeaders");
assertThat(this.spans).flatExtracting(Span::kind).contains(Span.Kind.CONSUMER,
assertThat(this.spans).extracting(MutableSpan::kind).contains(Span.Kind.CONSUMER,
Span.Kind.PRODUCER);
}
@@ -171,7 +173,7 @@ public class TracingChannelInterceptorTest {
assertThat(this.channel.receive().getHeaders()).containsKeys("X-B3-TraceId",
"X-B3-SpanId", "X-B3-Sampled", "nativeHeaders");
assertThat(this.spans).hasSize(1).flatExtracting(Span::kind)
assertThat(this.spans).hasSize(1).extracting(MutableSpan::kind)
.containsExactly(Span.Kind.CONSUMER);
}
@@ -197,7 +199,7 @@ public class TracingChannelInterceptorTest {
assertThat(messages.get(0).getHeaders()).doesNotContainKeys("X-B3-TraceId",
"X-B3-SpanId", "X-B3-Sampled", "nativeHeaders");
assertThat(this.spans).flatExtracting(Span::kind)
assertThat(this.spans).extracting(MutableSpan::kind)
.containsExactly(Span.Kind.CONSUMER, null);
}
@@ -239,7 +241,7 @@ public class TracingChannelInterceptorTest {
this.channel.send(MessageBuilder.withPayload("foo").build());
this.channel.receive();
assertThat(this.spans).flatExtracting(Span::kind)
assertThat(this.spans).extracting(MutableSpan::kind)
.containsExactlyInAnyOrder(Span.Kind.CONSUMER, Span.Kind.PRODUCER);
}
@@ -252,7 +254,7 @@ public class TracingChannelInterceptorTest {
channel.send(MessageBuilder.withPayload("foo").build());
assertThat(this.spans).flatExtracting(Span::kind)
assertThat(this.spans).extracting(MutableSpan::kind)
.containsExactly(Span.Kind.CONSUMER, null, Span.Kind.PRODUCER);
}
@@ -347,7 +349,8 @@ public class TracingChannelInterceptorTest {
headers.put(KafkaHeaders.MESSAGE_KEY, "hello");
channel.send(MessageBuilder.createMessage("foo", new MessageHeaders(headers)));
assertThat(this.spans).flatExtracting(Span::remoteServiceName).contains("kafka");
assertThat(this.spans).extracting(MutableSpan::remoteServiceName)
.contains("kafka");
}
@Test
@@ -361,7 +364,7 @@ public class TracingChannelInterceptorTest {
headers.put(AmqpHeaders.RECEIVED_ROUTING_KEY, "hello");
channel.send(MessageBuilder.createMessage("foo", new MessageHeaders(headers)));
assertThat(this.spans).flatExtracting(Span::remoteServiceName)
assertThat(this.spans).extracting(MutableSpan::remoteServiceName)
.contains("rabbitmq");
}
@@ -375,7 +378,7 @@ public class TracingChannelInterceptorTest {
Map<String, Object> headers = new HashMap<>();
channel.send(MessageBuilder.createMessage("foo", new MessageHeaders(headers)));
assertThat(this.spans).flatExtracting(Span::remoteServiceName)
assertThat(this.spans).extracting(MutableSpan::remoteServiceName)
.containsOnly("broker", null);
}

View File

@@ -23,8 +23,11 @@ import java.util.stream.Collectors;
import brave.Span;
import brave.Tracer;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.propagation.ExtraFieldPropagation;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -34,7 +37,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -65,7 +67,7 @@ public class MultipleHopsIntegrationTests {
Tracer tracer;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Autowired
RestTemplate restTemplate;
@@ -78,7 +80,7 @@ public class MultipleHopsIntegrationTests {
@Before
public void setup() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -87,16 +89,15 @@ public class MultipleHopsIntegrationTests {
"http://localhost:" + this.config.port + "/greeting", String.class);
await().atMost(5, SECONDS).untilAsserted(() -> {
then(this.reporter.getSpans()).hasSize(14);
then(this.spans).hasSize(14);
});
then(this.reporter.getSpans().stream().map(zipkin2.Span::name).collect(toList()))
then(this.spans).extracting(MutableSpan::name)
.containsAll(asList("http:/greeting", "send"));
then(this.reporter.getSpans().stream().map(zipkin2.Span::kind)
then(this.spans).extracting(MutableSpan::kind)
// no server kind due to test constraints
.collect(toList()))
.containsAll(asList(zipkin2.Span.Kind.CONSUMER,
zipkin2.Span.Kind.PRODUCER, zipkin2.Span.Kind.SERVER));
then(this.reporter.getSpans().stream().map(span -> span.tags().get("channel"))
.containsAll(
asList(Span.Kind.CONSUMER, Span.Kind.PRODUCER, Span.Kind.SERVER));
then(this.spans.spans().stream().map(span -> span.tags().get("channel"))
.filter(Objects::nonNull).distinct().collect(toList())).hasSize(3)
.containsAll(asList("words", "counts", "greetings"));
}
@@ -141,7 +142,7 @@ public class MultipleHopsIntegrationTests {
initialSpan.finish();
}
await().atMost(5, SECONDS).untilAsserted(() -> {
then(this.reporter.getSpans()).isNotEmpty();
then(this.spans).isNotEmpty();
});
then(this.application.allSpans()).as("All have foo")
@@ -151,7 +152,7 @@ public class MultipleHopsIntegrationTests {
then(this.application.allSpans().stream()
.filter(span -> "baz".equals(baggage(span, "baz")))
.collect(Collectors.toList())).as("Someone has baz").isNotEmpty();
then(this.reporter.getSpans().stream()
then(this.spans.spans().stream()
.filter(span -> span.tags().containsKey("foo")
&& span.tags().containsKey("UPPER_CASE"))
.collect(Collectors.toList())).as("Someone has foo and UPPER_CASE tags")
@@ -183,8 +184,8 @@ public class MultipleHopsIntegrationTests {
}
@Bean
ArrayListSpanReporter arrayListSpanAccumulator() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -22,23 +22,23 @@ import java.util.Map;
import brave.Span;
import brave.Tracer.SpanInScope;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.opentracing.BraveSpan;
import brave.opentracing.BraveSpanContext;
import brave.opentracing.BraveTracer;
import brave.propagation.TraceContext;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import io.opentracing.Scope;
import io.opentracing.propagation.Format;
import io.opentracing.propagation.TextMapAdapter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Annotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -59,10 +59,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = NONE,
properties = "spring.sleuth.baggage-keys=country-code,user-id")
public class BraveTracerTest {
public class OpenTracingTest {
@Autowired
ArrayListSpanReporter spans;
TestSpanHandler spans;
@Autowired
Tracing brave;
@@ -154,13 +154,12 @@ public class BraveTracerTest {
}
void checkSpanReportedToZipkin() {
assertThat(this.spans.getSpans()).first().satisfies(s -> {
assertThat(this.spans).first().satisfies(s -> {
assertThat(s.name()).isEqualTo("encode");
assertThat(s.timestamp()).isEqualTo(1L);
assertThat(s.annotations())
.containsExactly(Annotation.create(2L, "pump fake"));
assertThat(s.startTimestamp()).isEqualTo(1L);
assertThat(s.annotations()).containsExactly(entry(2L, "pump fake"));
assertThat(s.tags()).containsExactly(entry("lc", "codec"));
assertThat(s.duration()).isEqualTo(2L);
assertThat(s.finishTimestamp()).isEqualTo(3L);
});
}
@@ -261,14 +260,14 @@ public class BraveTracerTest {
public void ignoresErrorFalseTag_beforeStart() {
this.opentracing.buildSpan("encode").withTag("error", false).start().finish();
assertThat(this.spans.getSpans().get(0).tags()).isEmpty();
assertThat(this.spans.get(0).tags()).isEmpty();
}
@Test
public void ignoresErrorFalseTag_afterStart() {
this.opentracing.buildSpan("encode").start().setTag("error", false).finish();
assertThat(this.spans.getSpans().get(0).tags()).isEmpty();
assertThat(this.spans.get(0).tags()).isEmpty();
}
@Before
@@ -286,8 +285,8 @@ public class BraveTracerTest {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -16,18 +16,19 @@
package org.springframework.cloud.sleuth.instrument.quartz;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Properties;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import brave.Tracer.SpanInScope;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.propagation.Propagation.Setter;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.IntegrationTestSpanHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.quartz.Job;
import org.quartz.JobDataMap;
@@ -45,7 +46,6 @@ import org.quartz.impl.StdSchedulerFactory;
import org.quartz.listeners.JobListenerSupport;
import org.quartz.listeners.TriggerListenerSupport;
import org.quartz.utils.StringKeyDirtyFlagMap;
import zipkin2.Span;
import static org.assertj.core.api.Assertions.assertThat;
import static org.quartz.JobBuilder.newJob;
@@ -59,6 +59,9 @@ import static org.springframework.cloud.sleuth.instrument.quartz.TracingJobListe
*/
public class TracingJobListenerTest {
@Rule
public IntegrationTestSpanHandler spanHandler = new IntegrationTestSpanHandler();
private static final JobKey SUCCESSFUL_JOB_KEY = new JobKey("SuccessfulJob");
private static final JobKey EXCEPTIONAL_JOB_KEY = new JobKey("ExceptionalJob");
@@ -74,9 +77,7 @@ public class TracingJobListenerTest {
private StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext
.create();
private Queue<Span> spans = new ArrayDeque<>();
private Tracing tracing = Tracing.newBuilder().spanReporter(spans::add)
private Tracing tracing = Tracing.newBuilder().addSpanHandler(spanHandler)
.currentTraceContext(currentTraceContext).build();
@Before
@@ -124,7 +125,7 @@ public class TracingJobListenerTest {
runJob(trigger);
// expect
takeSpan();
spanHandler.takeLocalSpan();
}
@Test
@@ -138,7 +139,7 @@ public class TracingJobListenerTest {
runJob(trigger);
// expect
Span span = takeSpan();
MutableSpan span = spanHandler.takeLocalSpan();
assertThat(span.name()).isEqualToIgnoringCase(SUCCESSFUL_JOB_KEY.toString());
assertThat(span.tags().get(TRIGGER_TAG_KEY))
.isEqualToIgnoringCase(TRIGGER_KEY.toString());
@@ -153,7 +154,7 @@ public class TracingJobListenerTest {
runJob(trigger);
// expect
takeSpan();
spanHandler.takeLocalSpan();
}
@Test
@@ -166,7 +167,7 @@ public class TracingJobListenerTest {
runJob(trigger);
// expect
takeSpan();
spanHandler.takeLocalSpan();
}
@Test
@@ -179,15 +180,13 @@ public class TracingJobListenerTest {
// when
runJob(trigger);
// expect
requireNoSpan();
// expect no span
}
@Test
public void should_have_parent_and_child_span_when_trigger_contains_span_info()
throws Exception {
// given
brave.Span span = tracing.tracer().nextSpan();
JobDataMap data = new JobDataMap();
addSpanToJobData(data);
Trigger trigger = newTrigger().forJob(SUCCESSFUL_JOB_KEY).usingJobData(data)
@@ -197,8 +196,8 @@ public class TracingJobListenerTest {
runJob(trigger);
// expect
Span parent = takeSpan();
Span child = takeSpan();
MutableSpan parent = spanHandler.takeLocalSpan();
MutableSpan child = spanHandler.takeLocalSpan();
assertThat(parent.parentId()).isNull();
assertThat(child.parentId()).isEqualTo(parent.id());
}
@@ -216,8 +215,8 @@ public class TracingJobListenerTest {
runJob(trigger);
// expect
Span parent = takeSpan();
Span child = takeSpan();
MutableSpan parent = spanHandler.takeLocalSpan();
MutableSpan child = spanHandler.takeLocalSpan();
assertThat(parent.parentId()).isNull();
assertThat(child.parentId()).isEqualTo(parent.id());
}
@@ -239,7 +238,7 @@ public class TracingJobListenerTest {
}
void addSpanToJobData(JobDataMap data) {
brave.Span span = tracing.tracer().nextSpan();
brave.Span span = tracing.tracer().nextSpan().start();
try (SpanInScope spanInScope = tracing.tracer().withSpanInScope(span)) {
tracing.propagation()
.injector((Setter<JobDataMap, String>) StringKeyDirtyFlagMap::put)
@@ -250,19 +249,6 @@ public class TracingJobListenerTest {
}
}
Span takeSpan() throws InterruptedException {
Span result = spans.poll();
assertThat(result).withFailMessage("Span was not reported, but was expected")
.isNotNull();
return result;
}
void requireNoSpan() throws InterruptedException {
Span result = spans.poll();
assertThat(result).withFailMessage("Span was reported, but was not expected")
.isNull();
}
public static class CompleteableTriggerListener extends CompletableFuture
implements TriggerListener, JobListener {

View File

@@ -16,19 +16,20 @@
package org.springframework.cloud.sleuth.instrument.rpc;
import brave.handler.SpanHandler;
import brave.rpc.RpcRequest;
import brave.rpc.RpcRuleSampler;
import brave.sampler.Matcher;
import brave.sampler.RateLimitingSampler;
import brave.sampler.Sampler;
import brave.sampler.SamplerFunction;
import brave.test.TestSpanHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -57,8 +58,8 @@ public class TraceRpcAutoConfigurationIntegrationTests {
public static class Config {
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
// tag::custom_rpc_server_sampler[]

View File

@@ -17,7 +17,9 @@
package org.springframework.cloud.sleuth.instrument.web;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -29,7 +31,6 @@ import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.sleuth.DisableSecurity;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -49,7 +50,7 @@ import static org.assertj.core.api.BDDAssertions.then;
public class IgnoreAutoConfiguredSkipPatternsIntegrationTests {
@Autowired
ArrayListSpanReporter accumulator;
TestSpanHandler spans;
@Autowired
Tracer tracer;
@@ -60,7 +61,7 @@ public class IgnoreAutoConfiguredSkipPatternsIntegrationTests {
@Before
@After
public void clearSpans() {
this.accumulator.clear();
this.spans.clear();
}
@Test
@@ -70,7 +71,7 @@ public class IgnoreAutoConfiguredSkipPatternsIntegrationTests {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.accumulator.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
}
@Test
@@ -80,7 +81,7 @@ public class IgnoreAutoConfiguredSkipPatternsIntegrationTests {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.accumulator.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
}
@Test
@@ -90,7 +91,7 @@ public class IgnoreAutoConfiguredSkipPatternsIntegrationTests {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.accumulator.getSpans()).hasSize(0);
then(this.spans).hasSize(0);
}
@EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class)
@@ -108,8 +109,8 @@ public class IgnoreAutoConfiguredSkipPatternsIntegrationTests {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -17,7 +17,9 @@
package org.springframework.cloud.sleuth.instrument.web;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -29,7 +31,6 @@ import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.sleuth.DisableSecurity;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -49,7 +50,7 @@ import static org.assertj.core.api.BDDAssertions.then;
public class SkipEndPointsIntegrationTestsWithContextPathWithBasePath {
@Autowired
ArrayListSpanReporter accumulator;
TestSpanHandler spans;
@Autowired
Tracer tracer;
@@ -60,7 +61,7 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithBasePath {
@Before
@After
public void clearSpans() {
this.accumulator.clear();
this.spans.clear();
}
@Test
@@ -70,7 +71,7 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.accumulator.getSpans()).hasSize(0);
then(this.spans).hasSize(0);
}
@Test
@@ -80,7 +81,7 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.accumulator.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
}
@EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class)
@@ -94,8 +95,8 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithBasePath {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -17,7 +17,9 @@
package org.springframework.cloud.sleuth.instrument.web;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -29,7 +31,6 @@ import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.sleuth.DisableSecurity;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -53,7 +54,7 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithoutBasePath {
int port;
@Autowired
private ArrayListSpanReporter spanReporter;
private TestSpanHandler spans;
@Autowired
private Tracer tracer;
@@ -61,7 +62,7 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithoutBasePath {
@Before
@After
public void clearSpans() {
this.spanReporter.clear();
this.spans.clear();
}
@Test
@@ -71,7 +72,7 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithoutBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
}
@Test
@@ -81,7 +82,7 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithoutBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
}
@Test
@@ -90,7 +91,7 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithoutBasePath {
"http://localhost:" + this.port + "/context-path/health", String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(0);
then(this.spans).hasSize(0);
}
@Test
@@ -100,7 +101,7 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithoutBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(0);
then(this.spans).hasSize(0);
}
@EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class)
@@ -122,8 +123,8 @@ public class SkipEndPointsIntegrationTestsWithContextPathWithoutBasePath {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -17,7 +17,9 @@
package org.springframework.cloud.sleuth.instrument.web;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -29,7 +31,6 @@ import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.sleuth.DisableSecurity;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -51,7 +52,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath {
int port;
@Autowired
private ArrayListSpanReporter spanReporter;
private TestSpanHandler spans;
@Autowired
private Tracer tracer;
@@ -59,7 +60,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath {
@Before
@After
public void clearSpans() {
this.spanReporter.clear();
this.spans.clear();
}
@Test
@@ -68,7 +69,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
}
@Test
@@ -77,7 +78,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
}
@Test
@@ -86,7 +87,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath {
"http://localhost:" + this.port + "/actuator/health", String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(0);
then(this.spans).hasSize(0);
}
@Test
@@ -95,7 +96,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath {
"http://localhost:" + this.port + "/actuator/metrics?xyz", String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(0);
then(this.spans).hasSize(0);
}
@EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class)
@@ -117,8 +118,8 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -17,7 +17,9 @@
package org.springframework.cloud.sleuth.instrument.web;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -29,7 +31,6 @@ import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.sleuth.DisableSecurity;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -52,7 +53,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithoutBasePath {
int port;
@Autowired
private ArrayListSpanReporter spanReporter;
private TestSpanHandler spans;
@Autowired
private Tracer tracer;
@@ -60,7 +61,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithoutBasePath {
@Before
@After
public void clearSpans() {
this.spanReporter.clear();
this.spans.clear();
}
@Test
@@ -69,7 +70,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithoutBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
}
@Test
@@ -78,7 +79,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithoutBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
}
@Test
@@ -87,7 +88,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithoutBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(0);
then(this.spans).hasSize(0);
}
@Test
@@ -96,7 +97,7 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithoutBasePath {
String.class);
then(this.tracer.currentSpan()).isNull();
then(this.spanReporter.getSpans()).hasSize(0);
then(this.spans).hasSize(0);
}
@EnableAutoConfiguration(exclude = RabbitAutoConfiguration.class)
@@ -118,8 +119,8 @@ public class SkipEndPointsIntegrationTestsWithoutContextPathWithoutBasePath {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -16,21 +16,23 @@
package org.springframework.cloud.sleuth.instrument.web;
import java.util.Map;
import brave.Span;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.http.HttpResponse;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.assertj.core.api.BDDAssertions;
import org.junit.Test;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
public class SleuthHttpServerParserTests {
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
@Test
public void should_tag_span_with_error_when_response_has_error_and_status_is_ok() {
@@ -60,17 +62,13 @@ public class SleuthHttpServerParserTests {
}
private void thenReportedSpanContainsErrorTag() {
BDDAssertions
.then(this.reporter.getSpans().stream()
.flatMap(s -> s.tags().keySet().stream()))
.contains("http.status_code");
BDDAssertions.then(this.spans).extracting(MutableSpan::tags)
.flatExtracting(Map::keySet).contains("http.status_code");
}
private void thenReportedSpanDoesNotContainErrorTag() {
BDDAssertions
.then(this.reporter.getSpans().stream()
.flatMap(s -> s.tags().keySet().stream()))
.doesNotContain("http.status_code");
BDDAssertions.then(this.spans).extracting(MutableSpan::tags)
.flatExtracting(Map::keySet).doesNotContain("http.status_code");
}
private HttpResponse errorResponseWithOkStatus() {
@@ -87,7 +85,7 @@ public class SleuthHttpServerParserTests {
}
private Span newSpan() {
return Tracing.newBuilder().spanReporter(this.reporter)
return Tracing.newBuilder().addSpanHandler(this.spans)
.sampler(Sampler.ALWAYS_SAMPLE).build().tracer().nextSpan().name("span")
.start();
}

View File

@@ -18,7 +18,6 @@ package org.springframework.cloud.sleuth.instrument.web;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import brave.Span;
@@ -28,12 +27,12 @@ import brave.http.HttpTracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.sampler.Sampler;
import brave.spring.web.TracingClientHttpRequestInterceptor;
import brave.test.TestSpanHandler;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.cloud.sleuth.util.SpanUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.ClientHttpRequestInterceptor;
@@ -56,10 +55,10 @@ public class TraceRestTemplateInterceptorTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
Tracer tracer = this.tracing.tracer();
@@ -133,9 +132,8 @@ public class TraceRestTemplateInterceptorTests {
span.finish();
}
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).isNotEmpty();
then(spans.get(0).tags()).containsEntry("http.url", "/foo?a=b")
then(this.spans).isNotEmpty();
then(this.spans.get(0).tags()).containsEntry("http.url", "/foo?a=b")
.containsEntry("http.path", "/foo").containsEntry("http.method", "GET");
}
@@ -143,7 +141,7 @@ public class TraceRestTemplateInterceptorTests {
public void notSampledHeaderAddedWhenNotExportable() {
this.tracing.close();
this.tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).sampler(Sampler.NEVER_SAMPLE).build();
.addSpanHandler(this.spans).sampler(Sampler.NEVER_SAMPLE).build();
this.template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList(
TracingClientHttpRequestInterceptor.create(HttpTracing.create(tracing))));
@@ -157,7 +155,7 @@ public class TraceRestTemplateInterceptorTests {
span.finish();
}
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
}
// issue #198
@@ -195,10 +193,9 @@ public class TraceRestTemplateInterceptorTests {
span.finish();
}
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(2);
then(this.spans).hasSize(2);
String spanName = spans.get(0).name();
then(spanName).isEqualTo("http:/cas~fs~%c3%a5%cb%86%e2%80%99");
then(spanName).isEqualTo("http:/cas~fs~%C3%A5%CB%86%E2%80%99");
then(StringUtils.isAsciiPrintable(spanName));
}
@@ -218,9 +215,8 @@ public class TraceRestTemplateInterceptorTests {
span.finish();
}
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).isNotEmpty();
String spanName = spans.get(0).name();
then(this.spans).isNotEmpty();
String spanName = this.spans.get(0).name();
then(spanName).hasSize(50);
then(StringUtils.isAsciiPrintable(spanName));
}

View File

@@ -16,18 +16,18 @@
package org.springframework.cloud.sleuth.instrument.web.client;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.propagation.B3SinglePropagation;
import brave.propagation.CurrentTraceContext;
import brave.propagation.CurrentTraceContext.Scope;
import brave.propagation.Propagation;
import brave.propagation.TraceContext;
import brave.sampler.Sampler;
import brave.test.IntegrationTestSpanHandler;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.After;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import reactor.core.publisher.Flux;
@@ -37,8 +37,6 @@ import reactor.netty.http.client.HttpClient;
import reactor.netty.http.client.HttpClientResponse;
import reactor.netty.http.client.PrematureCloseException;
import reactor.netty.http.server.HttpServer;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -48,6 +46,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.reactive.function.client.WebClient;
import static brave.Span.Kind.CLIENT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -65,14 +64,14 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(SpringRunner.class)
public class ReactorNettyHttpClientSpringBootTests {
@ClassRule
public static IntegrationTestSpanHandler spanHandler = new IntegrationTestSpanHandler();
DisposableServer disposableServer;
@Autowired
HttpClient httpClient;
@Autowired
BlockingQueue<Span> spans;
@Autowired
CurrentTraceContext currentTraceContext;
@@ -84,7 +83,6 @@ public class ReactorNettyHttpClientSpringBootTests {
if (disposableServer != null) {
disposableServer.disposeNow();
}
this.spans.clear();
}
@Test
@@ -97,12 +95,10 @@ public class ReactorNettyHttpClientSpringBootTests {
assertThat(response.status()).isEqualTo(HttpResponseStatus.OK);
Span clientSpan = takeClientSpan();
MutableSpan clientSpan = spanHandler.takeRemoteSpan(CLIENT);
assertThat(clientSpan.remoteEndpoint()).satisfiesAnyOf(
ep -> assertThat(ep.ipv4()).isNotNull(),
ep -> assertThat(ep.ipv6()).isNotNull());
assertThat(clientSpan.remoteEndpoint().portAsInt()).isNotZero();
assertThat(clientSpan.remoteIp()).isNotNull();
assertThat(clientSpan.remotePort()).isNotZero();
}
@Test
@@ -119,7 +115,7 @@ public class ReactorNettyHttpClientSpringBootTests {
.uri("/").responseContent().aggregate().asString().block();
}
Span clientSpan = takeClientSpan();
MutableSpan clientSpan = spanHandler.takeRemoteSpan(CLIENT);
assertThat(b3SingleHeaderReadByServer).isEqualTo(context.traceIdString() + "-"
+ clientSpan.id() + "-1-" + context.spanIdString());
@@ -138,14 +134,14 @@ public class ReactorNettyHttpClientSpringBootTests {
String b3SingleHeaderReadByServer = request.block();
Span clientSpan = takeClientSpan();
MutableSpan clientSpan = spanHandler.takeRemoteSpan(CLIENT);
assertThat(b3SingleHeaderReadByServer)
.isEqualTo(clientSpan.traceId() + "-" + clientSpan.id() + "-1");
}
@Test
public void shouldTagOnRequestError() throws InterruptedException {
public void shouldRecordRequestError() {
disposableServer = HttpServer.create().port(0).handle((req, resp) -> {
throw new RuntimeException("test");
}).bindNow();
@@ -156,17 +152,7 @@ public class ReactorNettyHttpClientSpringBootTests {
assertThatThrownBy(request::block)
.hasCauseInstanceOf(PrematureCloseException.class);
Span clientSpan = takeClientSpan();
assertThat(clientSpan.tags()).containsKey("error");
}
/** Call this to block until a span was reported */
Span takeClientSpan() throws InterruptedException {
Span result = spans.poll(1, TimeUnit.SECONDS);
assertThat(result).withFailMessage("Span was not reported").isNotNull();
assertThat(result.kind()).isEqualTo(Span.Kind.CLIENT);
return result;
spanHandler.takeRemoteSpanWithError(CLIENT);
}
@Configuration
@@ -183,17 +169,9 @@ public class ReactorNettyHttpClientSpringBootTests {
return Sampler.ALWAYS_SAMPLE;
}
/**
* Use a blocking queue as it is simpler than wrapping everything in awaitility
*/
@Bean
BlockingQueue<Span> spans() {
return new LinkedBlockingQueue<>();
}
@Bean
Reporter<zipkin2.Span> spanReporter(BlockingQueue<Span> spans) {
return spans::add;
SpanHandler testSpanHandler() {
return spanHandler;
}
@Bean

View File

@@ -22,12 +22,12 @@ import java.util.Collections;
import brave.Tracing;
import brave.http.HttpTracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import org.assertj.core.api.BDDAssertions;
import org.junit.After;
import org.junit.Test;
import org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
@@ -36,10 +36,10 @@ public class TraceRequestHttpHeadersFilterTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
HttpTracing httpTracing = HttpTracing.newBuilder(this.tracing).build();

View File

@@ -19,12 +19,12 @@ package org.springframework.cloud.sleuth.instrument.web.client;
import brave.Tracing;
import brave.http.HttpTracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import org.assertj.core.api.BDDAssertions;
import org.junit.After;
import org.junit.Test;
import org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
@@ -33,10 +33,10 @@ public class TraceResponseHttpHeadersFilterTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
HttpTracing httpTracing = HttpTracing.newBuilder(this.tracing).build();
@@ -59,7 +59,7 @@ public class TraceResponseHttpHeadersFilterTests {
filter.filter(httpHeaders, exchange);
BDDAssertions.then(this.reporter.getSpans()).isEmpty();
BDDAssertions.then(this.spans).isEmpty();
}
@Test
@@ -77,7 +77,7 @@ public class TraceResponseHttpHeadersFilterTests {
filter.filter(httpHeaders, exchange);
BDDAssertions.then(this.reporter.getSpans()).isNotEmpty();
BDDAssertions.then(this.spans).isNotEmpty();
}
}

View File

@@ -23,9 +23,11 @@ import java.util.Map;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.http.HttpTracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.spring.web.TracingClientHttpRequestInterceptor;
import brave.test.TestSpanHandler;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.SocketPolicy;
@@ -35,7 +37,6 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
@@ -53,10 +54,10 @@ public class TraceRestTemplateInterceptorIntegrationTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
Tracer tracer = this.tracing.tracer();
@@ -96,10 +97,10 @@ public class TraceRestTemplateInterceptorIntegrationTests {
}
// 1 span "new race", 1 span "rest template"
BDDAssertions.then(this.reporter.getSpans()).hasSize(2);
zipkin2.Span span1 = this.reporter.getSpans().get(0);
BDDAssertions.then(span1.tags()).containsEntry("error", "Read timed out");
BDDAssertions.then(span1.kind().ordinal()).isEqualTo(Span.Kind.CLIENT.ordinal());
BDDAssertions.then(this.spans).hasSize(2);
MutableSpan span1 = this.spans.get(0);
BDDAssertions.then(span1.error()).hasMessage("Read timed out");
BDDAssertions.then(span1.kind()).isEqualTo(Span.Kind.CLIENT);
}
private ClientHttpRequestFactory clientHttpRequestFactory() {

View File

@@ -17,17 +17,17 @@
package org.springframework.cloud.sleuth.instrument.web.client.discoveryexception;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import brave.Span;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -39,7 +39,6 @@ import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
@@ -72,11 +71,11 @@ public class WebClientDiscoveryExceptionTests {
Tracer tracer;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void close() {
this.reporter.clear();
this.spans.clear();
}
// issue #240
@@ -96,8 +95,7 @@ public class WebClientDiscoveryExceptionTests {
// hystrix commands should finish at this point
Thread.sleep(200);
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans.stream().filter(span1 -> span1.kind() == zipkin2.Span.Kind.CLIENT)
then(this.spans.spans().stream().filter(span1 -> span1.kind() == Span.Kind.CLIENT)
.findFirst().get().tags()).containsKey("error");
}
@@ -149,8 +147,8 @@ public class WebClientDiscoveryExceptionTests {
}
@Bean
Reporter<zipkin2.Span> mySpanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -23,7 +23,9 @@ import java.util.Map;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
@@ -45,7 +47,6 @@ import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
@@ -88,11 +89,11 @@ public class WebClientExceptionTests {
Tracing tracer;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void open() {
this.reporter.clear();
this.spans.clear();
}
// issue #198
@@ -115,8 +116,8 @@ public class WebClientExceptionTests {
}
then(this.tracer.tracer().currentSpan()).isNull();
then(this.reporter.getSpans()).isNotEmpty();
then(this.reporter.getSpans().get(0).tags()).containsKey("error");
then(this.spans).isNotEmpty();
then(this.spans.get(0).tags()).containsKey("error");
}
Object[] parametersForShouldCloseSpanUponException() {
@@ -164,8 +165,8 @@ public class WebClientExceptionTests {
}
@Bean
ArrayListSpanReporter accumulator() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -21,9 +21,11 @@ import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import brave.Span;
import brave.Tracing;
import brave.http.HttpTracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import feign.Client;
import feign.Feign;
import feign.FeignException;
@@ -40,10 +42,8 @@ import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import zipkin2.Span;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.assertj.core.api.BDDAssertions.then;
@@ -62,10 +62,10 @@ public class FeignRetriesTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
HttpTracing httpTracing = HttpTracing.newBuilder(this.tracing).build();
@@ -130,10 +130,8 @@ public class FeignRetriesTests {
then(api.decodedPost()).isEqualTo("OK");
// request interception should take place only twice (1st request & 2nd retry)
then(atomicInteger.get()).isEqualTo(2);
then(this.reporter.getSpans().get(0).tags()).containsEntry("error",
"IOException");
then(this.reporter.getSpans().get(1).kind().ordinal())
.isEqualTo(Span.Kind.CLIENT.ordinal());
then(this.spans.get(0).error()).isInstanceOf(IOException.class);
then(this.spans.get(1).kind()).isEqualTo(Span.Kind.CLIENT);
}
interface TestInterface {

View File

@@ -17,15 +17,14 @@
package org.springframework.cloud.sleuth.instrument.web.client.feign;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.http.HttpTracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import feign.Client;
import feign.Request;
import feign.RequestTemplate;
@@ -59,10 +58,10 @@ public class TracingFeignClientTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
List<zipkin2.Span> spans = new ArrayList<>();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(currentTraceContext)
.spanReporter(spans::add).build();
.addSpanHandler(spans).build();
Tracer tracer = this.tracing.tracer();
@@ -95,15 +94,15 @@ public class TracingFeignClientTests {
span.finish();
}
then(spans.get(0)).extracting("kind.ordinal")
.isEqualTo(Span.Kind.CLIENT.ordinal());
then(spans.get(0).kind()).isEqualTo(Span.Kind.CLIENT);
}
@Test
public void should_log_error_when_exception_thrown() throws IOException {
RuntimeException error = new RuntimeException("exception has occurred");
Span span = this.tracer.nextSpan().name("foo");
BDDMockito.given(this.client.execute(BDDMockito.any(), BDDMockito.any()))
.willThrow(new RuntimeException("exception has occurred"));
.willThrow(error);
try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.start())) {
this.traceFeignClient.execute(this.request, this.options);
@@ -115,9 +114,8 @@ public class TracingFeignClientTests {
span.finish();
}
then(this.spans.get(0)).extracting("kind.ordinal")
.isEqualTo(Span.Kind.CLIENT.ordinal());
then(this.spans.get(0).tags()).containsEntry("error", "exception has occurred");
then(this.spans.get(0).kind()).isEqualTo(Span.Kind.CLIENT);
then(this.spans.get(0).error()).isSameAs(error);
}
@Test

View File

@@ -16,7 +16,6 @@
package org.springframework.cloud.sleuth.instrument.web.client.integration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -32,9 +31,12 @@ import javax.servlet.http.HttpServletRequest;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.propagation.SamplingFlags;
import brave.propagation.TraceContextOrSamplingFlags;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
@@ -58,8 +60,6 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
import zipkin2.Annotation;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -78,7 +78,6 @@ import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
@@ -140,7 +139,7 @@ public class WebClientTests {
HttpAsyncClientBuilder httpAsyncClientBuilder; // #845
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Autowired
Tracer tracer;
@@ -163,7 +162,7 @@ public class WebClientTests {
@After
@Before
public void close() {
this.reporter.clear();
this.spans.clear();
this.testErrorController.clear();
this.fooController.clear();
}
@@ -178,9 +177,8 @@ public class WebClientTests {
Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> {
then(getHeader(response, TRACE_ID_NAME)).isNull();
then(getHeader(response, SPAN_ID_NAME)).isNull();
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).isNotEmpty();
Optional<zipkin2.Span> noTraceSpan = new ArrayList<>(spans).stream()
then(this.spans).isNotEmpty();
Optional<MutableSpan> noTraceSpan = this.spans.spans().stream()
.filter(span -> "http:/notrace".equals(span.name())
&& !span.tags().isEmpty()
&& span.tags().containsKey("http.path"))
@@ -241,7 +239,7 @@ public class WebClientTests {
span.finish();
}
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
then(this.tracer.currentSpan()).isNull();
}
@@ -272,7 +270,7 @@ public class WebClientTests {
}
then(this.tracer.currentSpan()).isNull();
then(this.reporter.getSpans()).isNotEmpty();
then(this.spans).isNotEmpty();
}
@Test
@@ -290,9 +288,9 @@ public class WebClientTests {
}
then(this.tracer.currentSpan()).isNull();
then(this.reporter.getSpans()).isNotEmpty().extracting("traceId", String.class)
then(this.spans).isNotEmpty().extracting("traceId", String.class)
.containsOnly(span.context().traceIdString());
then(this.reporter.getSpans()).extracting("kind.name").contains("CLIENT");
then(this.spans).extracting("kind.name").contains("CLIENT");
}
@Test
@@ -329,9 +327,9 @@ public class WebClientTests {
}
then(this.tracer.currentSpan()).isNull();
then(this.reporter.getSpans()).isNotEmpty().extracting("traceId", String.class)
then(this.spans).isNotEmpty().extracting("traceId", String.class)
.containsOnly(span.context().traceIdString());
then(this.reporter.getSpans()).extracting("kind.name").contains("CLIENT");
then(this.spans).extracting("kind.name").contains("CLIENT");
}
@Test
@@ -347,8 +345,7 @@ public class WebClientTests {
span.finish();
}
then(this.tracer.currentSpan()).isNull();
then(this.reporter.getSpans()).isNotEmpty().extracting("kind.name")
.contains("CLIENT");
then(this.spans).isNotEmpty().extracting("kind.name").contains("CLIENT");
}
@Test
@@ -368,8 +365,7 @@ public class WebClientTests {
}
then(this.tracer.currentSpan()).isNull();
then(this.reporter.getSpans()).isNotEmpty().extracting("kind.name")
.contains("CLIENT");
then(this.spans).isNotEmpty().extracting("kind.name").contains("CLIENT");
}
/**
@@ -387,18 +383,18 @@ public class WebClientTests {
}
});
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
}
@Test
public void shouldRespectSkipPattern() {
this.webClient.get().uri("http://localhost:" + this.port + "/skip").retrieve()
.bodyToMono(String.class).block();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
this.webClient.get().uri("http://localhost:" + this.port + "/doNotSkip")
.retrieve().bodyToMono(String.class).block();
then(this.reporter.getSpans()).isNotEmpty();
then(this.spans).isNotEmpty();
}
Object[] parametersForShouldAttachTraceIdWhenCallingAnotherService() {
@@ -422,7 +418,7 @@ public class WebClientTests {
}
then(this.tracer.currentSpan()).isNull();
then(this.reporter.getSpans()).isNotEmpty();
then(this.spans).isNotEmpty();
}
Object[] parametersForShouldAttachTraceIdWhenUsingFeignClientWithoutResponseBody() {
@@ -443,22 +439,20 @@ public class WebClientTests {
}
then(this.tracer.currentSpan()).isNull();
Optional<zipkin2.Span> storedSpan = this.reporter.getSpans().stream()
Optional<MutableSpan> storedSpan = this.spans.spans().stream()
.filter(span -> "404".equals(span.tags().get("http.status_code")))
.findFirst();
then(storedSpan.isPresent()).isTrue();
List<zipkin2.Span> spans = this.reporter.getSpans();
spans.stream().forEach(span -> {
this.spans.spans().stream().forEach(span -> {
int initialSize = span.annotations().size();
int distinctSize = span.annotations().stream().map(Annotation::value)
int distinctSize = span.annotations().stream().map(Map.Entry::getValue)
.distinct().collect(Collectors.toList()).size();
log.info("logs " + span.annotations());
then(initialSize).as("there are no duplicate log entries")
.isEqualTo(distinctSize);
});
then(this.reporter.getSpans()).isNotEmpty().extracting("kind.name")
.contains("CLIENT");
then(this.spans).isNotEmpty().extracting("kind.name").contains("CLIENT");
}
@Test
@@ -484,7 +478,7 @@ public class WebClientTests {
}
then(this.tracer.currentSpan()).isNull();
then(this.customizer.isExecuted()).isTrue();
then(this.reporter.getSpans()).extracting("kind.name").contains("CLIENT");
then(this.spans).extracting("kind.name").contains("CLIENT");
}
@Test
@@ -573,8 +567,8 @@ public class WebClientTests {
}
@Bean
Reporter<zipkin2.Span> spanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -16,8 +16,6 @@
package org.springframework.cloud.sleuth.instrument.zuul;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -26,6 +24,7 @@ import brave.Tracer;
import brave.Tracing;
import brave.http.HttpTracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.monitoring.TracerFactory;
import org.junit.After;
@@ -37,7 +36,6 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.cloud.netflix.zuul.metrics.EmptyTracerFactory;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import static org.assertj.core.api.BDDAssertions.then;
@@ -56,10 +54,10 @@ public class TracePostZuulFilterTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
HttpTracing httpTracing = HttpTracing.newBuilder(this.tracing).build();
@@ -110,11 +108,10 @@ public class TracePostZuulFilterTests {
span.finish();
}
List<zipkin2.Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(this.spans).hasSize(1);
// initial span
then(spans.get(0).tags()).containsEntry("http.status_code", "456");
then(spans.get(0).name()).isEqualTo("http:start");
then(this.spans.get(0).tags()).containsEntry("http.status_code", "456");
then(this.spans.get(0).name()).isEqualTo("http:start");
then(this.tracing.tracer().currentSpan()).isNull();
}

View File

@@ -16,14 +16,13 @@
package org.springframework.cloud.sleuth.propagation;
import java.util.List;
import java.util.Map;
import brave.ScopedSpan;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.propagation.ExtraFieldPropagation;
import brave.propagation.TraceContext;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -31,7 +30,6 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -61,13 +59,13 @@ public class TagPropagationFinishedSpanHandlerTest {
private Tracer tracer;
@Autowired
private ArrayListSpanReporter arrayListSpanReporter;
private TestSpanHandler spans;
private ScopedSpan span;
@Before
public void setUp() {
this.arrayListSpanReporter.clear();
this.spans.clear();
this.span = this.tracer.startScopedSpan("my-scoped-span");
TraceContext context = this.span.context();
ExtraFieldPropagation.set(context, BAGGAGE_KEY, BAGGAGE_VALUE);
@@ -79,12 +77,10 @@ public class TagPropagationFinishedSpanHandlerTest {
public void shouldReportWithBaggageInTags() {
this.span.finish();
List<zipkin2.Span> spans = this.arrayListSpanReporter.getSpans();
assertThat(spans).hasSize(1);
Map<String, String> tags = spans.get(0).tags();
assertThat(tags).hasSize(2);
assertThat(tags).containsEntry(BAGGAGE_KEY, BAGGAGE_VALUE);
assertThat(tags).containsEntry(PROPAGATION_KEY, PROPAGATION_VALUE);
assertThat(this.spans).hasSize(1);
assertThat(this.spans.get(0).tags()).hasSize(2)
.containsEntry(BAGGAGE_KEY, BAGGAGE_VALUE)
.containsEntry(PROPAGATION_KEY, PROPAGATION_VALUE);
}
@Configuration
@@ -92,8 +88,8 @@ public class TagPropagationFinishedSpanHandlerTest {
public static class TestConfiguration {
@Bean
public ArrayListSpanReporter arrayListSpanReporter() {
return new ArrayListSpanReporter();
public SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -140,7 +140,7 @@ public class SamplerAutoConfigurationTests {
static class WithSpanHandler {
@Bean
SpanHandler spanHandler() {
SpanHandler testSpanHandler() {
return new SpanHandler() {
@Override
public boolean end(TraceContext context, MutableSpan span, Cause cause) {

View File

@@ -1,55 +0,0 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.sleuth.util;
import org.junit.jupiter.api.Test;
import zipkin2.Span;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class BlockingQueueSpanReporterTests {
Span span1 = Span.newBuilder().traceId("1").id("1").build();
Span span2 = Span.newBuilder().traceId("1").id("2").build();
BlockingQueueSpanReporter reporter = new BlockingQueueSpanReporter();
@Test
void takeSpan_fifo_order() {
reporter.report(span1);
reporter.report(span2);
assertThat(reporter.takeSpan()).isSameAs(span1);
assertThat(reporter.takeSpan()).isSameAs(span2);
}
@Test
void assertEmpty() {
reporter.assertEmpty();
}
@Test
void assertEmpty_fails_when_not_empty() {
reporter.report(span1);
assertThatThrownBy(reporter::assertEmpty).isInstanceOf(AssertionError.class)
.hasMessage("Span remaining in queue. Check for redundant reporting!");
}
}

View File

@@ -31,8 +31,8 @@
<name>spring-cloud-sleuth-dependencies</name>
<description>Spring Cloud Sleuth Dependencies</description>
<properties>
<brave.version>5.12.1</brave.version>
<brave.opentracing.version>0.37.1</brave.opentracing.version>
<brave.version>5.12.2</brave.version>
<brave.opentracing.version>0.37.2</brave.opentracing.version>
<grpc.spring.boot.version>3.4.1</grpc.spring.boot.version>
</properties>
<dependencyManagement>

View File

@@ -16,10 +16,11 @@
package sample;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.propagation.TraceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -43,11 +44,12 @@ public class SampleFeignApplication {
// Use this for debugging (or if there is no Zipkin server running on port 9411)
@Bean
@ConditionalOnProperty(value = "sample.zipkin.enabled", havingValue = "false")
public Reporter<Span> spanReporter() {
return new Reporter<Span>() {
public SpanHandler spanHandler() {
return new SpanHandler() {
@Override
public void report(Span span) {
public boolean end(TraceContext context, MutableSpan span, Cause cause) {
logger.info(span);
return true;
}
};
}

View File

@@ -96,6 +96,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>

View File

@@ -20,26 +20,28 @@ import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.propagation.TraceContext;
import org.apache.commons.logging.Log;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
/**
* Span Collector that logs spans and adds Spans to a list.
*
* @author Marcin Grzejszczak
*/
public class IntegrationTestZipkinSpanReporter implements Reporter<Span> {
public class IntegrationTestZipkinSpanHandler extends SpanHandler {
private static final Log log = org.apache.commons.logging.LogFactory
.getLog(IntegrationTestZipkinSpanReporter.class);
.getLog(IntegrationTestZipkinSpanHandler.class);
public List<Span> hashedSpans = Collections.synchronizedList(new LinkedList<>());
public List<MutableSpan> spans = Collections.synchronizedList(new LinkedList<>());
@Override
public void report(Span span) {
public boolean end(TraceContext context, MutableSpan span, Cause cause) {
log.debug(span);
this.hashedSpans.add(span);
this.spans.add(span);
return true;
}
}

View File

@@ -21,6 +21,9 @@ import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;
import brave.Span;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import integration.MessagingApplicationTests.IntegrationSpanCollectorConfig;
import org.junit.After;
@@ -29,8 +32,6 @@ import org.junit.runner.RunWith;
import sample.SampleMessagingApplication;
import tools.AbstractIntegrationTest;
import tools.SpanUtil;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@@ -58,11 +59,11 @@ public class MessagingApplicationTests extends AbstractIntegrationTest {
private static String sampleAppUrl = "http://localhost:" + port;
@Autowired
IntegrationTestZipkinSpanReporter integrationTestSpanCollector;
IntegrationTestZipkinSpanHandler testSpanHandler;
@After
public void cleanup() {
this.integrationTestSpanCollector.hashedSpans.clear();
this.testSpanHandler.spans.clear();
}
@Test
@@ -107,18 +108,15 @@ public class MessagingApplicationTests extends AbstractIntegrationTest {
}
private void thenThereIsAtLeastOneTagWithKey(String key) {
then(this.integrationTestSpanCollector.hashedSpans.stream().map(Span::tags)
then(this.testSpanHandler.spans.stream().map(MutableSpan::tags)
.flatMap(m -> m.keySet().stream()).anyMatch(b -> b.equals(key))).isTrue();
}
private void thenAllSpansHaveTraceIdEqualTo(long traceId) {
String traceIdHex = Long.toHexString(traceId);
log.info(
"Stored spans: [\n"
+ this.integrationTestSpanCollector.hashedSpans.stream()
.map(Span::toString).collect(Collectors.joining("\n"))
+ "\n]");
then(this.integrationTestSpanCollector.hashedSpans.stream()
log.info("Stored spans: [\n" + this.testSpanHandler.spans.stream()
.map(MutableSpan::toString).collect(Collectors.joining("\n")) + "\n]");
then(this.testSpanHandler.spans.stream()
.filter(span -> !span.traceId().equals(SpanUtil.idToHex(traceId)))
.collect(Collectors.toList()))
.describedAs("All spans have same trace id [" + traceIdHex + "]")
@@ -126,62 +124,62 @@ public class MessagingApplicationTests extends AbstractIntegrationTest {
}
private void thenTheSpansHaveProperParentStructure() {
Optional<Span> firstHttpSpan = findFirstHttpRequestSpan();
List<Span> eventSpans = findAllEventRelatedSpans();
Optional<Span> eventSentSpan = findSpanWithKind(Span.Kind.SERVER);
Optional<Span> producerSpan = findSpanWithKind(Span.Kind.PRODUCER);
Optional<Span> lastHttpSpansParent = findLastHttpSpansParent();
Optional<MutableSpan> firstHttpSpan = findFirstHttpRequestSpan();
List<MutableSpan> eventSpans = findAllEventRelatedSpans();
Optional<MutableSpan> eventSentSpan = findSpanWithKind(Span.Kind.SERVER);
Optional<MutableSpan> producerSpan = findSpanWithKind(Span.Kind.PRODUCER);
Optional<MutableSpan> lastHttpSpansParent = findLastHttpSpansParent();
// "http:/parent/" -> "message:messages" -> "http:/foo" (CS + CR) -> "http:/foo"
// (SS)
thenAllSpansArePresent(firstHttpSpan, eventSpans, lastHttpSpansParent,
eventSentSpan, producerSpan);
then(this.integrationTestSpanCollector.hashedSpans).as("There were 6 spans")
.hasSize(6);
then(this.testSpanHandler.spans).as("There were 6 spans").hasSize(6);
log.info("Checking the parent child structure");
List<Optional<Span>> parentChild = this.integrationTestSpanCollector.hashedSpans
.stream().filter(span -> span.parentId() != null)
.map(span -> this.integrationTestSpanCollector.hashedSpans.stream()
List<Optional<MutableSpan>> parentChild = this.testSpanHandler.spans.stream()
.filter(span -> span.parentId() != null)
.map(span -> this.testSpanHandler.spans.stream()
.filter(span1 -> span1.id().equals(span.parentId())).findAny())
.collect(Collectors.toList());
log.info("List of parents and children " + parentChild);
then(parentChild.stream().allMatch(Optional::isPresent)).isTrue();
}
private Optional<Span> findLastHttpSpansParent() {
return this.integrationTestSpanCollector.hashedSpans.stream()
private Optional<MutableSpan> findLastHttpSpansParent() {
return this.testSpanHandler.spans.stream()
.filter(span -> "http:/".equals(span.name()) && span.kind() != null)
.findFirst();
}
private Optional<Span> findSpanWithKind(Span.Kind kind) {
return this.integrationTestSpanCollector.hashedSpans.stream()
private Optional<MutableSpan> findSpanWithKind(Span.Kind kind) {
return this.testSpanHandler.spans.stream()
.filter(span -> kind.equals(span.kind())).findFirst();
}
private List<Span> findAllEventRelatedSpans() {
return this.integrationTestSpanCollector.hashedSpans.stream()
private List<MutableSpan> findAllEventRelatedSpans() {
return this.testSpanHandler.spans.stream()
.filter(span -> "send".equals(span.name()) && span.parentId() != null)
.collect(Collectors.toList());
}
private Optional<Span> findFirstHttpRequestSpan() {
return this.integrationTestSpanCollector.hashedSpans.stream()
private Optional<MutableSpan> findFirstHttpRequestSpan() {
return this.testSpanHandler.spans.stream()
// home is the name of the method
.filter(span -> span.tags().values().stream().anyMatch("home"::equals))
.findFirst();
}
private void thenAllSpansArePresent(Optional<Span> firstHttpSpan,
List<Span> eventSpans, Optional<Span> lastHttpSpan,
Optional<Span> eventSentSpan, Optional<Span> eventReceivedSpan) {
private void thenAllSpansArePresent(Optional<MutableSpan> firstHttpSpan,
List<MutableSpan> eventSpans, Optional<MutableSpan> lastHttpSpan,
Optional<MutableSpan> eventSentSpan,
Optional<MutableSpan> eventReceivedSpan) {
log.info("Found following spans");
log.info("First http span " + firstHttpSpan);
log.info("Event spans " + eventSpans);
log.info("Event sent span " + eventSentSpan);
log.info("Event received span " + eventReceivedSpan);
log.info("Last http span " + lastHttpSpan);
log.info("All found spans \n" + this.integrationTestSpanCollector.hashedSpans
.stream().map(Span::toString).collect(Collectors.joining("\n")));
log.info("All found spans \n" + this.testSpanHandler.spans.stream()
.map(MutableSpan::toString).collect(Collectors.joining("\n")));
then(firstHttpSpan.isPresent()).isTrue();
then(eventSpans).isNotEmpty();
then(eventSentSpan.isPresent()).isTrue();
@@ -193,8 +191,8 @@ public class MessagingApplicationTests extends AbstractIntegrationTest {
public static class IntegrationSpanCollectorConfig {
@Bean
Reporter<Span> integrationTestZipkinSpanReporter() {
return new IntegrationTestZipkinSpanReporter();
SpanHandler testSpanHandler() {
return new IntegrationTestZipkinSpanHandler();
}
@Bean

View File

@@ -16,10 +16,11 @@
package sample;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.propagation.TraceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -51,11 +52,12 @@ public class SampleRibbonApplication {
// Use this for debugging (or if there is no Zipkin server running on port 9411)
@Bean
@ConditionalOnProperty(value = "sample.zipkin.enabled", havingValue = "false")
public Reporter<Span> spanReporter() {
return new Reporter<Span>() {
public SpanHandler spanHandler() {
return new SpanHandler() {
@Override
public void report(Span span) {
public boolean end(TraceContext context, MutableSpan span, Cause cause) {
logger.info(span);
return true;
}
};
}

View File

@@ -16,8 +16,9 @@
package sample;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.propagation.TraceContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -45,8 +46,14 @@ public class SampleZipkinApplication {
// Use this for debugging (or if there is no Zipkin server running on port 9411)
@Bean
@ConditionalOnProperty(value = "sample.zipkin.enabled", havingValue = "false")
public Reporter<Span> spanReporter() {
return Reporter.CONSOLE;
public SpanHandler spanHandler() {
return new SpanHandler() {
@Override
public boolean end(TraceContext context, MutableSpan span, Cause cause) {
System.out.println(span.toString());
return true;
}
};
}
}

View File

@@ -60,13 +60,13 @@
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>

View File

@@ -34,6 +34,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@@ -41,6 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE,
classes = { TraceAsyncIntegrationTests.TraceAsyncITestConfiguration.class })
@DirtiesContext // flakey otherwise
public class TraceAsyncIntegrationTests {
@ClassRule
@@ -57,54 +59,36 @@ public class TraceAsyncIntegrationTests {
@Test
public void should_set_span_on_an_async_annotated_method() {
asyncLogic.invokeAsync();
try (Scope ws = currentTraceContext.maybeScope(context)) {
asyncLogic.invokeAsync();
assertSpan_invokeAsync(takeDesirableSpan());
MutableSpan span = takeDesirableSpan();
assertThat(span.name()).isEqualTo("invoke-async");
assertThat(span.containsAnnotation("@Async")).isTrue();
assertThat(span.tags()).containsEntry("class", "AsyncLogic")
.containsEntry("method", "invokeAsync");
// continues the trace
assertThat(span.traceId()).isEqualTo(context.traceIdString());
}
}
@Test
public void should_set_span_with_custom_method_on_an_async_annotated_method() {
asyncLogic.invokeAsync_customName();
assertSpan_invokeAsync_customName(takeDesirableSpan());
}
@Test
public void should_continue_a_span_on_an_async_annotated_method() {
try (Scope ws = currentTraceContext.maybeScope(context)) {
asyncLogic.invokeAsync();
MutableSpan span = assertSpan_invokeAsync(takeDesirableSpan());
assertThat(span.traceId()).isEqualTo(context.traceIdString());
}
}
@Test
public void should_continue_a_span_with_custom_method_on_an_async_annotated_method() {
try (Scope ws = currentTraceContext.maybeScope(context)) {
asyncLogic.invokeAsync_customName();
MutableSpan span = assertSpan_invokeAsync_customName(takeDesirableSpan());
MutableSpan span = takeDesirableSpan();
assertThat(span.name()).isEqualTo("foo");
assertThat(span.containsAnnotation("@Async")).isTrue();
assertThat(span.tags()).containsEntry("class", "AsyncLogic")
.containsEntry("method", "invokeAsync_customName");
// continues the trace
assertThat(span.traceId()).isEqualTo(context.traceIdString());
}
}
static MutableSpan assertSpan_invokeAsync_customName(MutableSpan span) {
assertThat(span.name()).isEqualTo("foo");
assertThat(span.containsAnnotation("@Async")).isTrue();
assertThat(span.tags()).containsEntry("class", "AsyncLogic")
.containsEntry("method", "invokeAsync_customName");
return span;
}
static MutableSpan assertSpan_invokeAsync(MutableSpan span) {
assertThat(span.name()).isEqualTo("invoke-async");
assertThat(span.containsAnnotation("@Async")).isTrue();
assertThat(span.tags()).containsEntry("class", "AsyncLogic")
.containsEntry("method", "invokeAsync");
return span;
}
// Sleuth adds spans named "async" with no tags when an executor is used.
// We don't want that one.
MutableSpan takeDesirableSpan() {
@@ -124,7 +108,7 @@ public class TraceAsyncIntegrationTests {
}
@Bean
SpanHandler spanHandler() {
SpanHandler testSpanHandler() {
return spans;
}

View File

@@ -81,6 +81,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -19,9 +19,10 @@ package org.springframework.cloud.sleuth.instrument.feign.issues.issue1125;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import feign.Client;
import feign.Request;
import feign.RequestTemplate;
@@ -29,8 +30,6 @@ import feign.Response;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -40,7 +39,6 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
@@ -65,11 +63,11 @@ public class ManuallyCreatedLoadBalancerFeignClientTests {
AnnotatedFeignClient annotatedFeignClient;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void open() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -78,10 +76,9 @@ public class ManuallyCreatedLoadBalancerFeignClientTests {
then(this.myLoadBalancerClient.wasCalled()).isTrue();
then(response).isEqualTo("foo");
List<Span> spans = this.reporter.getSpans();
// retries
then(spans).hasSize(1);
then(spans.get(0).tags().get("http.path")).isEqualTo("/test");
then(this.spans).hasSize(1);
then(this.spans.get(0).tags().get("http.path")).isEqualTo("/test");
}
@Test
@@ -93,10 +90,9 @@ public class ManuallyCreatedLoadBalancerFeignClientTests {
@Test
public void span_captured() {
this.annotatedFeignClient.get();
List<Span> spans = this.reporter.getSpans();
// retries
then(spans).hasSize(1);
then(spans.get(0).tags().get("http.path")).isEqualTo("/test");
then(this.spans).hasSize(1);
then(this.spans.get(0).tags().get("http.path")).isEqualTo("/test");
}
}
@@ -119,8 +115,8 @@ class Application {
}
@Bean
public Reporter<Span> spanReporter() {
return new ArrayListSpanReporter();
public SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -19,9 +19,10 @@ package org.springframework.cloud.sleuth.instrument.feign.issues.issue1125delega
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import feign.Client;
import feign.Contract;
import feign.Feign;
@@ -34,8 +35,6 @@ import feign.codec.Encoder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -45,7 +44,6 @@ import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@@ -74,11 +72,11 @@ public class ManuallyCreatedDelegateLoadBalancerFeignClientTests {
AnnotatedFeignClient annotatedFeignClient;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void open() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -88,10 +86,9 @@ public class ManuallyCreatedDelegateLoadBalancerFeignClientTests {
then(this.myLoadBalancerClient.wasCalled()).isTrue();
then(this.myDelegateClient.wasCalled()).isTrue();
then(response).isEqualTo("foo");
List<Span> spans = this.reporter.getSpans();
// retries
then(spans).hasSize(1);
then(spans.get(0).tags().get("http.path")).isEqualTo("/test");
then(this.spans).hasSize(1);
then(this.spans.get(0).tags().get("http.path")).isEqualTo("/test");
}
@Test
@@ -104,10 +101,9 @@ public class ManuallyCreatedDelegateLoadBalancerFeignClientTests {
@Test
public void span_captured() {
this.annotatedFeignClient.get();
List<Span> spans = this.reporter.getSpans();
// retries
then(spans).hasSize(1);
then(spans.get(0).tags().get("http.path")).isEqualTo("/test");
then(this.spans).hasSize(1);
then(this.spans.get(0).tags().get("http.path")).isEqualTo("/test");
}
}
@@ -143,8 +139,8 @@ class Application {
}
@Bean
public Reporter<Span> spanReporter() {
return new ArrayListSpanReporter();
public SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -16,17 +16,16 @@
package org.springframework.cloud.sleuth.instrument.feign.issues.issue350;
import java.util.List;
import java.util.concurrent.ExecutionException;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import feign.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -35,7 +34,6 @@ import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@@ -74,11 +72,11 @@ public class Issue350Tests {
Tracing tracer;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void setup() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -86,9 +84,8 @@ public class Issue350Tests {
this.template.getForEntity("http://localhost:9988/sleuth/test-not-ok",
String.class);
List<Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).tags()).containsEntry("http.status_code", "406");
then(this.spans).hasSize(1);
then(this.spans.get(0).tags()).containsEntry("http.status_code", "406");
}
}
@@ -119,8 +116,8 @@ class Application {
}
@Bean
public Reporter<Span> spanReporter() {
return new ArrayListSpanReporter();
public SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -18,14 +18,15 @@ package org.springframework.cloud.sleuth.instrument.feign.issues.issue362;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import feign.Client;
import feign.Logger;
import feign.Request;
@@ -36,8 +37,6 @@ import feign.codec.ErrorDecoder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -45,7 +44,6 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@@ -91,12 +89,12 @@ public class Issue362Tests {
Tracing tracer;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void setup() {
this.feignComponentAsserter.executedComponents.clear();
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -109,9 +107,8 @@ public class Issue362Tests {
then(response.getBody()).isEqualTo("I'm OK");
then(this.feignComponentAsserter.executedComponents).containsEntry(Client.class,
true);
List<Span> spans = this.reporter.getSpans();
then(spans).hasSize(1);
then(spans.get(0).tags()).containsEntry("http.path", "/service/ok");
then(this.spans).hasSize(1);
then(this.spans.get(0).tags()).containsEntry("http.path", "/service/ok");
}
@Test
@@ -128,10 +125,9 @@ public class Issue362Tests {
then(this.feignComponentAsserter.executedComponents)
.containsEntry(ErrorDecoder.class, true)
.containsEntry(Client.class, true);
List<Span> spans = this.reporter.getSpans();
// retries
then(spans).hasSize(5);
then(spans.stream().map(span -> span.tags().get("http.status_code"))
then(this.spans).hasSize(5);
then(this.spans.spans().stream().map(span -> span.tags().get("http.status_code"))
.collect(Collectors.toList())).containsOnly("409");
}
@@ -168,8 +164,8 @@ class Application {
}
@Bean
public Reporter<Span> spanReporter() {
return new ArrayListSpanReporter();
public SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -16,17 +16,16 @@
package org.springframework.cloud.sleuth.instrument.feign.issues.issue393;
import java.util.List;
import java.util.stream.Collectors;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import feign.okhttp.OkHttpClient;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -35,7 +34,6 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
@@ -70,14 +68,14 @@ public class Issue393Tests {
RestTemplate template = new RestTemplate();
@Autowired
ArrayListSpanReporter reporter;
Tracing tracer;
@Autowired
Tracing tracer;
TestSpanHandler spans;
@Before
public void open() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -87,10 +85,9 @@ public class Issue393Tests {
ResponseEntity<String> response = this.template.getForEntity(url, String.class);
then(response.getBody()).isEqualTo("mikesarver foo");
List<Span> spans = this.reporter.getSpans();
// retries
then(spans).hasSize(2);
then(spans.stream().map(span -> span.tags().get("http.path"))
then(this.spans).hasSize(2);
then(this.spans.spans().stream().map(span -> span.tags().get("http.path"))
.collect(Collectors.toList())).containsOnly("/name/mikesarver");
}
@@ -124,8 +121,8 @@ class Application {
}
@Bean
public Reporter<Span> spanReporter() {
return new ArrayListSpanReporter();
public SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -18,9 +18,10 @@ package org.springframework.cloud.sleuth.instrument.feign.issues.issue502;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import feign.Client;
import feign.Request;
import feign.RequestTemplate;
@@ -28,15 +29,12 @@ import feign.Response;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -69,11 +67,11 @@ public class Issue502Tests {
MyNameRemote myNameRemote;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void open() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -82,10 +80,9 @@ public class Issue502Tests {
then(this.myClient.wasCalled()).isTrue();
then(response).isEqualTo("foo");
List<Span> spans = this.reporter.getSpans();
// retries
then(spans).hasSize(1);
then(spans.get(0).tags().get("http.path")).isEqualTo("");
then(this.spans).hasSize(1);
then(this.spans.get(0).tags().get("http.path")).isEqualTo("");
}
}
@@ -106,8 +103,8 @@ class Application {
}
@Bean
public Reporter<Span> spanReporter() {
return new ArrayListSpanReporter();
public SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -64,6 +64,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -19,7 +19,10 @@ package org.springframework.cloud.sleuth.instrument.grpc;
import java.util.List;
import java.util.concurrent.TimeUnit;
import brave.Span.Kind;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import io.grpc.ClientInterceptor;
import io.grpc.ManagedChannel;
import io.grpc.ServerBuilder;
@@ -32,8 +35,6 @@ import org.lognet.springboot.grpc.GRpcServerBuilderConfigurer;
import org.lognet.springboot.grpc.GRpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zipkin2.Span;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -43,7 +44,6 @@ import org.springframework.cloud.sleuth.instrument.grpc.stubs.HelloRequest;
import org.springframework.cloud.sleuth.instrument.grpc.stubs.HelloServiceGrpc;
import org.springframework.cloud.sleuth.instrument.grpc.stubs.HelloServiceGrpc.HelloServiceBlockingStub;
import org.springframework.cloud.sleuth.instrument.grpc.stubs.HelloServiceGrpc.HelloServiceImplBase;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@@ -73,16 +73,16 @@ public class GrpcTracingIntegrationTests {
SpringAwareManagedChannelBuilder clientManagedChannelBuilder;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void beforeTest() {
this.reporter.clear();
this.spans.clear();
}
@After
public void afterTest() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -95,10 +95,9 @@ public class GrpcTracingIntegrationTests {
assertThat(client.sayHello("Testy McTest Face"))
.isEqualTo("Hello Testy McTest Face");
List<Span> spans = this.reporter.getSpans();
assertThat(spans).hasSize(2);
assertThat(spans.get(0).kind()).isEqualTo(Span.Kind.SERVER);
assertThat(spans.get(1).kind()).isEqualTo(Span.Kind.CLIENT);
assertThat(this.spans).hasSize(2);
assertThat(this.spans.get(0).kind()).isEqualTo(Kind.SERVER);
assertThat(this.spans.get(1).kind()).isEqualTo(Kind.CLIENT);
// ManagedChannel does not implement Closeable...
inProcessManagedChannel.shutdownNow();
@@ -141,9 +140,8 @@ public class GrpcTracingIntegrationTests {
}
@Bean
Reporter<zipkin2.Span> reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -64,6 +64,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -64,6 +64,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -77,6 +77,11 @@ https://www.w3.org/2001/XMLSchema-instance ">
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -16,8 +16,6 @@
package org.springframework.cloud.sleuth.instrument.messaging;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -26,7 +24,9 @@ import javax.annotation.PreDestroy;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -76,7 +76,7 @@ public class ITTracingChannelInterceptorTests implements MessageHandler {
Tracer tracer;
@Autowired
List<zipkin2.Span> spans;
TestSpanHandler spans;
@Autowired
MessagingTemplate messagingTemplate;
@@ -149,8 +149,8 @@ public class ITTracingChannelInterceptorTests implements MessageHandler {
ExecutorService service = Executors.newSingleThreadExecutor();
@Bean
List<zipkin2.Span> spans() {
return new ArrayList<>();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean
@@ -161,7 +161,7 @@ public class ITTracingChannelInterceptorTests implements MessageHandler {
@Bean
Tracing tracing() {
return Tracing.newBuilder().currentTraceContext(currentTraceContext())
.spanReporter(spans()::add).build();
.addSpanHandler(testSpanHandler()).build();
}
@Bean

View File

@@ -18,10 +18,6 @@ package org.springframework.cloud.sleuth.instrument.messaging;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
@@ -33,16 +29,18 @@ import javax.jms.XAConnection;
import javax.jms.XAConnectionFactory;
import javax.resource.spi.ResourceAdapter;
import brave.Span.Kind;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.propagation.CurrentTraceContext;
import brave.propagation.TraceContext;
import brave.test.IntegrationTestSpanHandler;
import org.apache.activemq.ra.ActiveMQActivationSpec;
import org.apache.activemq.ra.ActiveMQResourceAdapter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
import org.junit.ClassRule;
import org.junit.Test;
import zipkin2.Span;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@@ -74,16 +72,15 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class JmsTracingConfigurationTest {
@ClassRule
public static IntegrationTestSpanHandler spanHandler = new IntegrationTestSpanHandler();
final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(JmsTestTracingConfiguration.class,
AnnotationJmsListenerConfiguration.class, XAConfiguration.class,
SimpleJmsListenerConfiguration.class,
JcaJmsListenerConfiguration.class));
static void clearSpans(AssertableApplicationContext ctx) throws JMSException {
ctx.getBean(JmsTestTracingConfiguration.class).clearSpan();
}
static void checkConnection(AssertableApplicationContext ctx) throws JMSException {
// Not using try-with-resources as that doesn't exist in JMS 1.1
Connection con = ctx.getBean(ConnectionFactory.class).createConnection();
@@ -136,7 +133,6 @@ public class JmsTracingConfigurationTest {
@Test
public void tracesXAConnectionFactories() {
this.contextRunner.withUserConfiguration(XAConfiguration.class).run(ctx -> {
clearSpans(ctx);
checkConnection(ctx);
checkXAConnection(ctx);
});
@@ -145,7 +141,6 @@ public class JmsTracingConfigurationTest {
@Test
public void tracesTopicConnectionFactories() {
this.contextRunner.withUserConfiguration(XAConfiguration.class).run(ctx -> {
clearSpans(ctx);
checkConnection(ctx);
checkTopicConnection(ctx);
});
@@ -155,35 +150,36 @@ public class JmsTracingConfigurationTest {
public void tracesListener_jmsMessageListener() {
this.contextRunner.withUserConfiguration(SimpleJmsListenerConfiguration.class)
.run(ctx -> {
clearSpans(ctx);
ctx.getBean(JmsTemplate.class).convertAndSend("myQueue", "foo");
Callable<Span> takeSpan = ctx.getBean("takeSpan", Callable.class);
List<Span> trace = Arrays.asList(takeSpan.call(), takeSpan.call(),
takeSpan.call());
MutableSpan producer = spanHandler.takeRemoteSpan(Kind.PRODUCER);
MutableSpan consumer = spanHandler.takeRemoteSpan(Kind.CONSUMER);
MutableSpan listener = spanHandler.takeLocalSpan();
List<MutableSpan> trace = Arrays.asList(producer, consumer, listener);
assertThat(trace).allSatisfy(s -> assertThat(s.traceId())
.isEqualTo(trace.get(0).traceId()));
assertThat(trace).isNotNull().extracting(Span::name).contains("send",
"receive", "on-message");
assertThat(trace).isNotNull().extracting(MutableSpan::name)
.contains("send", "receive", "on-message");
});
}
@Test
@Ignore("flakey")
public void tracesListener_annotationMessageListener() {
this.contextRunner.withUserConfiguration(AnnotationJmsListenerConfiguration.class)
.run(ctx -> {
clearSpans(ctx);
ctx.getBean(JmsTemplate.class).convertAndSend("myQueue", "foo");
Callable<Span> takeSpan = ctx.getBean("takeSpan", Callable.class);
List<Span> trace = Arrays.asList(takeSpan.call(), takeSpan.call(),
takeSpan.call());
MutableSpan producer = spanHandler.takeRemoteSpan(Kind.PRODUCER);
MutableSpan consumer = spanHandler.takeRemoteSpan(Kind.CONSUMER);
MutableSpan listener = spanHandler.takeLocalSpan();
List<MutableSpan> trace = Arrays.asList(producer, consumer, listener);
assertThat(trace).allSatisfy(s -> assertThat(s.traceId())
.isEqualTo(trace.get(0).traceId()));
assertThat(trace).isNotNull().extracting(Span::name)
assertThat(trace).isNotNull().extracting(MutableSpan::name)
.containsExactlyInAnyOrder("send", "receive", "on-message");
});
}
@@ -192,16 +188,17 @@ public class JmsTracingConfigurationTest {
public void tracesListener_jcaMessageListener() {
this.contextRunner.withUserConfiguration(JcaJmsListenerConfiguration.class)
.run(ctx -> {
clearSpans(ctx);
ctx.getBean(JmsTemplate.class).convertAndSend("myQueue", "foo");
Callable<Span> takeSpan = ctx.getBean("takeSpan", Callable.class);
List<Span> trace = Arrays.asList(takeSpan.call(), takeSpan.call(),
takeSpan.call());
MutableSpan producer = spanHandler.takeRemoteSpan(Kind.PRODUCER);
MutableSpan consumer = spanHandler.takeRemoteSpan(Kind.CONSUMER);
MutableSpan listener = spanHandler.takeLocalSpan();
List<MutableSpan> trace = Arrays.asList(producer, consumer, listener);
assertThat(trace).allSatisfy(s -> assertThat(s.traceId())
.isEqualTo(trace.get(0).traceId()));
assertThat(trace).isNotNull().extracting(Span::name)
assertThat(trace).isNotNull().extracting(MutableSpan::name)
.containsExactlyInAnyOrder("send", "receive", "on-message");
});
}
@@ -309,41 +306,16 @@ public class JmsTracingConfigurationTest {
}
}
@Configuration
@EnableAutoConfiguration(exclude = KafkaAutoConfiguration.class)
static class JmsTestTracingConfiguration {
@Configuration
@EnableAutoConfiguration(exclude = KafkaAutoConfiguration.class)
class JmsTestTracingConfiguration {
@Bean
Tracing tracing(CurrentTraceContext currentTraceContext) {
return Tracing.newBuilder().addSpanHandler(spanHandler)
.currentTraceContext(currentTraceContext).build();
}
/**
* When testing servers or asynchronous clients, spans are reported on a worker
* thread. In order to read them on the main thread, we use a concurrent queue. As
* some implementations report after a response is sent, we use a blocking queue to
* prevent race conditions in tests.
*/
BlockingQueue<Span> spans = new LinkedBlockingQueue<>();
void clearSpan() {
this.spans.clear();
}
/**
* Call this to block until a span was reported.
* @return span from queue
*/
@Bean
Callable<Span> takeSpan() {
return () -> {
Span result = this.spans.poll(3, TimeUnit.SECONDS);
assertThat(result).withFailMessage("Span was not reported").isNotNull();
return result;
};
}
@Bean
Tracing tracing(CurrentTraceContext currentTraceContext) {
return Tracing.newBuilder().spanReporter(spans::add)
.currentTraceContext(currentTraceContext).build();
}
}

View File

@@ -19,7 +19,9 @@ package org.springframework.cloud.sleuth.instrument.messaging;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -29,7 +31,6 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.instrument.util.SpanUtil;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.QueueChannel;
@@ -57,11 +58,11 @@ public class TraceContextPropagationChannelInterceptorTests {
private Tracing tracing;
@Autowired
private ArrayListSpanReporter reporter;
private TestSpanHandler spans;
@After
public void close() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -95,7 +96,7 @@ public class TraceContextPropagationChannelInterceptorTests {
String parentId = message.getHeaders().get(TraceMessageHeaders.PARENT_ID_NAME,
String.class);
assertThat(parentId).as("parentId was not equal to parent's id")
.isEqualTo(this.reporter.getSpans().get(0).id());
.isEqualTo(this.spans.get(0).id());
}
@Configuration
@@ -113,8 +114,8 @@ public class TraceContextPropagationChannelInterceptorTests {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -17,6 +17,7 @@
package org.springframework.cloud.sleuth.instrument.messaging;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.kafka.clients.KafkaTracing;
import brave.messaging.MessagingRequest;
import brave.messaging.MessagingTracing;
@@ -24,6 +25,7 @@ import brave.sampler.Sampler;
import brave.sampler.SamplerFunction;
import brave.sampler.SamplerFunctions;
import brave.spring.rabbit.SpringRabbitTracing;
import brave.test.TestSpanHandler;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.Producer;
@@ -41,7 +43,6 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cloud.sleuth.autoconfig.TraceAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListener;
@@ -64,7 +65,7 @@ public class TraceMessagingAutoConfigurationTests {
RabbitTemplate rabbitTemplate;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Autowired
TestSleuthRabbitBeanPostProcessor postProcessor;
@@ -163,8 +164,8 @@ public class TraceMessagingAutoConfigurationTests {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -19,7 +19,9 @@ package org.springframework.cloud.sleuth.instrument.messaging;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -29,7 +31,6 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.instrument.util.SpanUtil;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.cloud.stream.binder.test.OutputDestination;
import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration;
import org.springframework.cloud.stream.function.StreamBridge;
@@ -60,11 +61,11 @@ public class TraceStreamChannelInterceptorTests {
private StreamBridge streamBridge;
@Autowired
private ArrayListSpanReporter reporter;
private TestSpanHandler spans;
@After
public void close() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -100,7 +101,7 @@ public class TraceStreamChannelInterceptorTests {
// [0] - producer
// [1] - http:testsendmessage
assertThat(parentId).as("parentId was not equal to parent's id")
.isEqualTo(this.reporter.getSpans().get(1).id());
.isEqualTo(this.spans.get(1).id());
}
@Configuration
@@ -114,8 +115,8 @@ public class TraceStreamChannelInterceptorTests {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -16,13 +16,14 @@
package org.springframework.cloud.sleuth.instrument.messaging.issues.issue_943;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.integration.config.EnableIntegration;
@@ -51,8 +52,8 @@ public class HelloSpringIntegration {
}
@Bean
ArrayListSpanReporter accumulator() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -20,10 +20,10 @@ import java.util.stream.Collectors;
import brave.Span;
import brave.Tracer;
import brave.test.TestSpanHandler;
import org.junit.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.client.RestTemplate;
@@ -59,12 +59,11 @@ public class Issue943Tests {
}
// then
ArrayListSpanReporter accumulator = applicationContext
.getBean(ArrayListSpanReporter.class);
TestSpanHandler spans = applicationContext.getBean(TestSpanHandler.class);
then(object).contains("Hellow World Message 1 Persist into DB")
.contains("Hellow World Message 2 Persist into DB")
.contains("Hellow World Message 3 Persist into DB");
then(accumulator.getSpans().stream().filter(
then(spans.spans().stream().filter(
span -> span.traceId().equals(newSpan.context().traceIdString()))
.map(span -> span.tags().getOrDefault("channel",
span.tags().get("http.path")))

View File

@@ -69,6 +69,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -21,7 +21,10 @@ import java.util.concurrent.atomic.AtomicReference;
import brave.Span;
import brave.Tracer;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Before;
@@ -32,7 +35,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.SpanName;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
@@ -56,11 +58,11 @@ public class TraceAsyncIntegrationTests {
Tracer tracer;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void cleanup() {
this.reporter.clear();
this.spans.clear();
this.classPerformingAsyncLogic.clear();
}
@@ -122,11 +124,11 @@ public class TraceAsyncIntegrationTests {
Awaitility.await().atMost(5, SECONDS).untilAsserted(() -> {
then(TraceAsyncIntegrationTests.this.classPerformingAsyncLogic.getSpan()
.context().traceId()).isEqualTo(span.context().traceId());
then(this.reporter.getSpans()).hasSize(2);
then(this.spans).hasSize(2);
// HTTP
then(this.reporter.getSpans().get(0).name()).isEqualTo("http:existing");
then(this.spans.get(0).name()).isEqualTo("http:existing");
// ASYNC
then(this.reporter.getSpans().get(1).tags())
then(this.spans.get(1).tags())
.containsEntry("class", "ClassPerformingAsyncLogic")
.containsEntry("method", "invokeAsynchronousLogic");
});
@@ -134,8 +136,8 @@ public class TraceAsyncIntegrationTests {
private void thenANewAsyncSpanGetsCreated() {
Awaitility.await().atMost(5, SECONDS).untilAsserted(() -> {
then(this.reporter.getSpans()).hasSize(1);
zipkin2.Span storedSpan = this.reporter.getSpans().get(0);
then(this.spans).hasSize(1);
MutableSpan storedSpan = this.spans.get(0);
then(storedSpan.name()).isEqualTo("invoke-asynchronous-logic");
then(storedSpan.tags()).containsEntry("class", "ClassPerformingAsyncLogic")
.containsEntry("method", "invokeAsynchronousLogic");
@@ -147,11 +149,11 @@ public class TraceAsyncIntegrationTests {
Awaitility.await().atMost(5, SECONDS).untilAsserted(() -> {
then(TraceAsyncIntegrationTests.this.classPerformingAsyncLogic.getSpan()
.context().traceId()).isEqualTo(span.context().traceId());
then(this.reporter.getSpans()).hasSize(2);
then(this.spans).hasSize(2);
// HTTP
then(this.reporter.getSpans().get(0).name()).isEqualTo("http:existing");
then(this.spans.get(0).name()).isEqualTo("http:existing");
// ASYNC
then(this.reporter.getSpans().get(1).tags())
then(this.spans.get(1).tags())
.containsEntry("class", "ClassPerformingAsyncLogic")
.containsEntry("method", "customNameInvokeAsynchronousLogic");
});
@@ -159,8 +161,8 @@ public class TraceAsyncIntegrationTests {
private void thenAsyncSpanHasCustomName() {
Awaitility.await().atMost(5, SECONDS).untilAsserted(() -> {
then(this.reporter.getSpans()).hasSize(1);
zipkin2.Span storedSpan = this.reporter.getSpans().get(0);
then(this.spans).hasSize(1);
MutableSpan storedSpan = this.spans.get(0);
then(storedSpan.name()).isEqualTo("foo");
then(storedSpan.tags()).containsEntry("class", "ClassPerformingAsyncLogic")
.containsEntry("method", "customNameInvokeAsynchronousLogic");
@@ -169,7 +171,7 @@ public class TraceAsyncIntegrationTests {
@After
public void cleanTrace() {
this.reporter.clear();
this.spans.clear();
}
@EnableAutoConfiguration
@@ -188,8 +190,8 @@ public class TraceAsyncIntegrationTests {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -30,8 +30,11 @@ import javax.servlet.http.HttpServletResponse;
import brave.Span;
import brave.Tracer;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.servlet.TracingFilter;
import brave.test.TestSpanHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
@@ -44,7 +47,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.cloud.sleuth.util.SpanUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -88,7 +90,7 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
MyFilter myFilter;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Autowired
Tracer tracer;
@@ -96,15 +98,15 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
@Before
@After
public void clearSpans() {
this.reporter.clear();
this.spans.clear();
}
@Test
public void should_create_a_trace() throws Exception {
whenSentPingWithoutTracingData();
then(this.reporter.getSpans()).hasSize(1);
zipkin2.Span span = this.reporter.getSpans().get(0);
then(this.spans).hasSize(1);
MutableSpan span = this.spans.get(0);
then(span.tags()).containsKey(TraceWebFilter.MVC_CONTROLLER_CLASS_KEY)
.containsKey(TraceWebFilter.MVC_CONTROLLER_METHOD_KEY);
then(this.tracer.currentSpan()).isNull();
@@ -118,7 +120,7 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
// https://github.com/spring-cloud/spring-cloud-sleuth/issues/327
// we don't want to respond with any tracing data
then(notSampledHeaderIsPresent(mvcResult)).isEqualTo(false);
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
then(this.tracer.currentSpan()).isNull();
}
@@ -129,7 +131,7 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
whenSentPingWithTraceId(expectedTraceId);
then(this.reporter.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
then(this.tracer.currentSpan()).isNull();
}
@@ -141,7 +143,7 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
whenSentPingWithTraceId(expectedTraceId);
then(MDC.getCopyOfContextMap()).isEmpty();
then(this.reporter.getSpans()).hasSize(1);
then(this.spans).hasSize(1);
then(this.tracer.currentSpan()).isNull();
}
@@ -165,7 +167,7 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk())
.andReturn();
Optional<zipkin2.Span> taggedSpan = this.reporter.getSpans().stream()
Optional<MutableSpan> taggedSpan = this.spans.spans().stream()
.filter(span -> span.tags().containsKey("tag")).findFirst();
then(taggedSpan.isPresent()).isTrue();
then(taggedSpan.get().tags()).containsEntry("tag", "value")
@@ -182,8 +184,8 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
whenSentToNonExistentEndpointWithTraceId(expectedTraceId);
// it's a span with the same ids
then(this.reporter.getSpans()).hasSize(1);
zipkin2.Span serverSpan = this.reporter.getSpans().get(0);
then(this.spans).hasSize(1);
MutableSpan serverSpan = this.spans.get(0);
then(serverSpan.tags()).containsEntry("custom", "tag")
.containsEntry("http.status_code", "404");
then(this.tracer.currentSpan()).isNull();
@@ -204,8 +206,8 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
// we need to dump the span cause it's not in TracingFilter since TF
// has also error dispatch and the ErrorController would report the span
then(this.reporter.getSpans()).hasSize(1);
then(this.reporter.getSpans().get(0).tags()).containsEntry("error",
then(this.spans).hasSize(1);
then(this.spans.get(0).tags()).containsEntry("error",
"Request processing failed; nested exception is java.lang.RuntimeException");
}
@@ -217,9 +219,8 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
whenSentRequestWithTraceIdAndNoSpanId(expectedTraceId);
whenSentRequestWithTraceIdAndNoSpanId(expectedTraceId);
then(this.reporter.getSpans().stream()
.filter(span -> span.id().equals(span.traceId())).findAny().isPresent())
.as("a root span exists").isTrue();
then(this.spans.spans().stream().filter(span -> span.id().equals(span.traceId()))
.findAny().isPresent()).as("a root span exists").isTrue();
then(this.tracer.currentSpan()).isNull();
}
@@ -232,8 +233,8 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
then(mvcResult.getResponse().getHeader("ZIPKIN-TRACE-ID"))
.isEqualTo(SpanUtil.idToHex(expectedTraceId));
then(this.reporter.getSpans()).hasSize(1);
then(this.reporter.getSpans().get(0).tags()).containsEntry("custom", "tag");
then(this.spans).hasSize(1);
then(this.spans.get(0).tags()).containsEntry("custom", "tag");
}
@Override
@@ -323,8 +324,8 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest {
private static final Log log = LogFactory.getLog(Config.class);
@Bean
public ArrayListSpanReporter testSpanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -30,7 +30,9 @@ import javax.servlet.ServletResponse;
import brave.Span;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -39,7 +41,6 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@@ -73,7 +74,7 @@ public class TraceFilterWebIntegrationMultipleFiltersTests {
MyFilter myFilter;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
// issue #550
@Autowired
@@ -97,7 +98,7 @@ public class TraceFilterWebIntegrationMultipleFiltersTests {
then(this.tracer.tracer().currentSpan()).isNull();
then(this.myFilter.getSpan().get()).isNotNull();
then(this.reporter.getSpans()).isNotEmpty();
then(this.spans).isNotEmpty();
}
private int port() {
@@ -156,8 +157,8 @@ public class TraceFilterWebIntegrationMultipleFiltersTests {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -32,20 +32,19 @@ import brave.propagation.CurrentTraceContext.Scope;
import brave.propagation.TraceContext;
import brave.sampler.Sampler;
import brave.sampler.SamplerFunction;
import brave.test.IntegrationTestSpanHandler;
import org.assertj.core.api.BDDAssertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.ClassRule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zipkin2.Span;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.cloud.sleuth.util.BlockingQueueSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@@ -71,15 +70,15 @@ import static org.assertj.core.api.BDDAssertions.then;
properties = "spring.sleuth.http.legacy.enabled=true")
public class TraceFilterWebIntegrationTests {
@ClassRule
public static IntegrationTestSpanHandler spanHandler = new IntegrationTestSpanHandler();
private static final Logger log = LoggerFactory
.getLogger(TraceFilterWebIntegrationTests.class);
@Autowired
CurrentTraceContext currentTraceContext;
@Autowired
BlockingQueueSpanReporter reporter;
@Autowired
@HttpServerSampler
SamplerFunction<HttpRequest> sampler;
@@ -87,18 +86,13 @@ public class TraceFilterWebIntegrationTests {
@Autowired
Environment environment;
@AfterEach
public void cleanup() {
this.reporter.assertEmpty();
}
@Test
public void should_tag_url() {
new RestTemplate().getForObject("http://localhost:" + port() + "/good",
String.class);
then(this.currentTraceContext.get()).isNull();
then(this.reporter.takeSpan().tags()).containsKey("http.url");
then(spanHandler.takeRemoteSpan(Kind.SERVER).tags()).containsKey("http.url");
}
@Test
@@ -113,11 +107,11 @@ public class TraceFilterWebIntegrationTests {
}
then(this.currentTraceContext.get()).isNull();
Span fromFirstTraceFilterFlow = this.reporter.takeSpan();
MutableSpan fromFirstTraceFilterFlow = spanHandler.takeRemoteSpanWithErrorTag(
Kind.SERVER,
"Request processing failed; nested exception is java.lang.RuntimeException: Throwing exception");
then(fromFirstTraceFilterFlow.tags()).containsEntry("http.method", "GET")
.containsEntry("mvc.controller.class", "ExceptionThrowingController")
.containsEntry("error",
"Request processing failed; nested exception is java.lang.RuntimeException: Throwing exception");
.containsEntry("mvc.controller.class", "BasicErrorController");
// Trace IDs in logs: issue#714
String hex = fromFirstTraceFilterFlow.traceId();
String[] split = capture.toString().split("\n");
@@ -139,8 +133,7 @@ public class TraceFilterWebIntegrationTests {
}
then(this.currentTraceContext.get()).isNull();
Span span = this.reporter.takeSpan();
then(span.kind().ordinal()).isEqualTo(Span.Kind.SERVER.ordinal());
MutableSpan span = spanHandler.takeRemoteSpan(Kind.SERVER);
then(span.tags()).containsEntry("http.status_code", "400");
then(span.tags()).containsEntry("http.path", "/test_bad_request");
}
@@ -169,8 +162,8 @@ public class TraceFilterWebIntegrationTests {
}
@Bean
BlockingQueueSpanReporter reporter() {
return new BlockingQueueSpanReporter();
SpanHandler testSpanHandler() {
return spanHandler;
}
@Bean

View File

@@ -21,22 +21,24 @@ import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import brave.Span;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.propagation.CurrentTraceContext;
import brave.sampler.Sampler;
import brave.spring.web.TracingAsyncClientHttpRequestInterceptor;
import brave.test.TestSpanHandler;
import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Span;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
@@ -84,7 +86,7 @@ public class RestTemplateTraceAspectIntegrationTests {
Tracing tracer;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Autowired
RestTemplate restTemplate;
@@ -95,7 +97,7 @@ public class RestTemplateTraceAspectIntegrationTests {
public void init() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
this.controller.reset();
this.reporter.clear();
this.spans.clear();
}
@Before
@@ -147,7 +149,7 @@ public class RestTemplateTraceAspectIntegrationTests {
whenARequestIsSentToASyncEndpointThatShouldBeFilteredOut();
then(this.currentTraceContext.get()).isNull();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
}
private void whenARequestIsSentToAnAsyncRestTemplateEndpoint() throws Exception {
@@ -174,7 +176,7 @@ public class RestTemplateTraceAspectIntegrationTests {
// Brave was never designed to run tests of server and client in one test
// that's why we have to pick only CLIENT side
private void thenClientKindIsReported() {
assertThat(this.reporter.getSpans().stream().map(Span::kind)
assertThat(this.spans.spans().stream().map(MutableSpan::kind)
.collect(Collectors.toList())).contains(Span.Kind.CLIENT);
}
@@ -210,8 +212,8 @@ public class RestTemplateTraceAspectIntegrationTests {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -20,21 +20,23 @@ import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.assertj.core.api.BDDAssertions;
import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.Span;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@@ -64,14 +66,14 @@ public class TraceWebAsyncClientAutoConfigurationTests {
Environment environment;
@Autowired
ArrayListSpanReporter accumulator;
TestSpanHandler spans;
@Autowired
Tracing tracer;
@Before
public void setup() {
this.accumulator.clear();
this.spans.clear();
}
@Test
@@ -92,17 +94,17 @@ public class TraceWebAsyncClientAutoConfigurationTests {
}
Awaitility.await().untilAsserted(() -> {
then(this.accumulator.getSpans().stream()
then(this.spans.spans().stream()
.filter(span -> Span.Kind.CLIENT == span.kind()).findFirst().get())
.matches(span -> span.duration() >= TimeUnit.MILLISECONDS
.toMicros(100));
.matches(span -> span.finishTimestamp()
- span.startTimestamp() >= TimeUnit.MILLISECONDS
.toMicros(100));
then(this.tracer.tracer().currentSpan()).isNull();
});
}
@Test
public void should_close_span_upon_failure_callback()
throws ExecutionException, InterruptedException {
public void should_close_span_upon_failure_callback() {
ListenableFuture<ResponseEntity<String>> future;
try {
future = this.asyncRestTemplate.getForEntity(
@@ -114,10 +116,10 @@ public class TraceWebAsyncClientAutoConfigurationTests {
}
Awaitility.await().untilAsserted(() -> {
Span reportedRpcSpan = new ArrayList<>(this.accumulator.getSpans()).stream()
MutableSpan reportedRpcSpan = new ArrayList<>(this.spans.spans()).stream()
.filter(span -> Span.Kind.CLIENT == span.kind()).findFirst().get();
then(reportedRpcSpan).matches(
span -> span.duration() >= TimeUnit.MILLISECONDS.toMicros(100));
then(reportedRpcSpan).matches(span -> span.finishTimestamp()
- span.startTimestamp() >= TimeUnit.MILLISECONDS.toMicros(100));
then(reportedRpcSpan.tags()).containsKey("error");
then(this.tracer.tracer().currentSpan()).isNull();
});
@@ -136,8 +138,8 @@ public class TraceWebAsyncClientAutoConfigurationTests {
public static class TestConfiguration {
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -22,8 +22,10 @@ import javax.servlet.http.HttpServletRequest;
import brave.Span;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.propagation.CurrentTraceContext;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -35,7 +37,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -61,7 +62,7 @@ public class Issue585Tests {
CurrentTraceContext currentTraceContext;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@LocalServerPort
int port;
@@ -74,7 +75,7 @@ public class Issue585Tests {
then(this.currentTraceContext.get()).isNull();
then(entity.getStatusCode().value()).isEqualTo(500);
then(this.reporter.getSpans().get(0).tags()).containsEntry("custom", "tag")
then(this.spans.get(0).tags()).containsEntry("custom", "tag")
.containsKeys("error");
}
@@ -84,8 +85,8 @@ public class Issue585Tests {
class TestConfig {
@Bean
ArrayListSpanReporter testSpanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -16,10 +16,11 @@
package org.springframework.cloud.sleuth.instrument.web.view;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
@@ -35,8 +36,8 @@ public class Issue469 extends WebMvcConfigurerAdapter {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -16,12 +16,12 @@
package org.springframework.cloud.sleuth.instrument.web.view;
import brave.test.TestSpanHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
@@ -37,7 +37,7 @@ import static org.assertj.core.api.BDDAssertions.then;
public class Issue469Tests {
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Autowired
Environment environment;
@@ -45,8 +45,7 @@ public class Issue469Tests {
RestTemplate restTemplate = new RestTemplate();
@Test
public void should_not_result_in_tracing_exceptions_when_using_view_controllers()
throws Exception {
public void should_not_result_in_tracing_exceptions_when_using_view_controllers() {
try {
this.restTemplate.getForObject("http://localhost:" + port() + "/welcome",
String.class);
@@ -56,7 +55,7 @@ public class Issue469Tests {
then(e).hasMessageContaining("404");
}
then(this.reporter.getSpans()).isNotEmpty();
then(this.spans).isNotEmpty();
}
private int port() {

View File

@@ -75,6 +75,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -21,7 +21,10 @@ import java.util.List;
import java.util.stream.Collectors;
import brave.Tracer;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.awaitility.Awaitility;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -31,7 +34,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import zipkin2.Span;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -40,7 +42,6 @@ import org.springframework.boot.test.system.OutputCaptureRule;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.sleuth.instrument.reactor.Issue866Configuration;
import org.springframework.cloud.sleuth.instrument.reactor.TraceReactorAutoConfigurationAccessorConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -113,30 +114,30 @@ public class FlatMapTests {
}
private void assertReactorTracing(ConfigurableApplicationContext context) {
ArrayListSpanReporter accumulator = context.getBean(ArrayListSpanReporter.class);
TestSpanHandler spans = context.getBean(TestSpanHandler.class);
int port = context.getBean(Environment.class).getProperty("local.server.port",
Integer.class);
RequestSender sender = context.getBean(RequestSender.class);
TestConfiguration config = context.getBean(TestConfiguration.class);
FactoryUser factoryUser = context.getBean(FactoryUser.class);
sender.port = port;
accumulator.clear();
spans.clear();
Awaitility.await().untilAsserted(() -> {
// when
LOGGER.info("Start");
accumulator.clear();
String firstTraceId = flatMapTraceId(accumulator, callFlatMap(port).block());
spans.clear();
String firstTraceId = flatMapTraceId(spans, callFlatMap(port).block());
// then
LOGGER.info("Checking first trace id");
thenAllWebClientCallsHaveSameTraceId(firstTraceId, sender);
thenSpanInFooHasSameTraceId(firstTraceId, config);
accumulator.clear();
spans.clear();
LOGGER.info("All web client calls have same trace id");
// when
LOGGER.info("Second trace start");
String secondTraceId = flatMapTraceId(accumulator, callFlatMap(port).block());
String secondTraceId = flatMapTraceId(spans, callFlatMap(port).block());
// then
then(firstTraceId).as("Id will not be reused between calls")
.isNotEqualTo(secondTraceId);
@@ -173,15 +174,14 @@ public class FlatMapTests {
.exchange();
}
private String flatMapTraceId(ArrayListSpanReporter accumulator,
ClientResponse response) {
private String flatMapTraceId(TestSpanHandler spans, ClientResponse response) {
then(response.statusCode().value()).isEqualTo(200);
then(accumulator.getSpans()).isNotEmpty();
LOGGER.info("Accumulated spans: " + accumulator.getSpans());
List<String> traceIdOfFlatMap = accumulator.getSpans().stream()
then(spans).isNotEmpty();
LOGGER.info("Accumulated spans: " + spans);
List<String> traceIdOfFlatMap = spans.spans().stream()
.filter(span -> span.tags().containsKey("http.path")
&& span.tags().get("http.path").equals("/withFlatMap"))
.map(Span::traceId).collect(Collectors.toList());
.map(MutableSpan::traceId).collect(Collectors.toList());
then(traceIdOfFlatMap).hasSize(1);
return traceIdOfFlatMap.get(0);
}
@@ -223,8 +223,8 @@ public class FlatMapTests {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -24,7 +24,6 @@ import reactor.core.CoreSubscriber;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Operators;
import reactor.util.context.Context;
import zipkin2.Callback;
/**
* {@link #subscribe} is made for reactor-netty and WebFlux client requests used in tests.
@@ -32,8 +31,8 @@ import zipkin2.Callback;
* signalling, or missing signals.
*
* <p>
* The implementation forwards signals to the supplied {@link Callback}, enforcing
* assumptions about a non-empty, {@link Mono} subscription.
* The implementation forwards signals to the supplied {@linkplain BiConsumer callback},
* enforcing assumptions about a non-empty, {@link Mono} subscription.
*/
final class TestHttpCallbackSubscriber implements CoreSubscriber<Integer> {

View File

@@ -64,6 +64,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -16,19 +16,20 @@
package org.springframework.cloud.sleuth.instrument.rpc;
import brave.handler.SpanHandler;
import brave.rpc.RpcRequest;
import brave.rpc.RpcRuleSampler;
import brave.sampler.Matcher;
import brave.sampler.RateLimitingSampler;
import brave.sampler.Sampler;
import brave.sampler.SamplerFunction;
import brave.test.TestSpanHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -57,8 +58,8 @@ public class TraceRpcAutoConfigurationIntegrationTests {
public static class Config {
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
// tag::custom_rpc_server_sampler[]

View File

@@ -60,6 +60,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -29,6 +29,7 @@ import java.util.concurrent.ThreadFactory;
import brave.Tracer;
import brave.Tracing;
import brave.propagation.StrictCurrentTraceContext;
import brave.test.TestSpanHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -38,8 +39,6 @@ import rx.plugins.RxJavaObservableExecutionHook;
import rx.plugins.RxJavaPlugins;
import rx.plugins.RxJavaSchedulersHook;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import static org.assertj.core.api.BDDAssertions.then;
/**
@@ -53,17 +52,17 @@ public class SleuthRxJavaSchedulersHookTests {
StrictCurrentTraceContext currentTraceContext = StrictCurrentTraceContext.create();
ArrayListSpanReporter reporter = new ArrayListSpanReporter();
TestSpanHandler spans = new TestSpanHandler();
Tracing tracing = Tracing.newBuilder().currentTraceContext(this.currentTraceContext)
.spanReporter(this.reporter).build();
.addSpanHandler(this.spans).build();
Tracer tracer = this.tracing.tracer();
@After
public void clean() {
this.tracing.close();
this.reporter.clear();
this.spans.clear();
this.currentTraceContext.close();
}
@@ -101,7 +100,7 @@ public class SleuthRxJavaSchedulersHookTests {
then(action).isInstanceOf(SleuthRxJavaSchedulersHook.TraceAction.class);
then(caller.toString()).isEqualTo("called_from_schedulers_hook");
then(this.reporter.getSpans()).isNotEmpty();
then(this.spans).isNotEmpty();
then(this.tracer.currentSpan()).isNull();
}
@@ -122,7 +121,7 @@ public class SleuthRxJavaSchedulersHookTests {
hello.get();
then(this.reporter.getSpans()).isEmpty();
then(this.spans).isEmpty();
then(this.tracer.currentSpan()).isNull();
}

View File

@@ -18,7 +18,9 @@ package org.springframework.cloud.sleuth.instrument.rxjava;
import brave.Span;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -32,7 +34,6 @@ import rx.schedulers.Schedulers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
@@ -48,7 +49,7 @@ import static org.awaitility.Awaitility.await;
public class SleuthRxJavaTests {
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Autowired
Tracer tracer;
@@ -63,7 +64,7 @@ public class SleuthRxJavaTests {
@Before
public void clean() {
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -76,11 +77,9 @@ public class SleuthRxJavaTests {
then(this.caller.toString()).isEqualTo("actual_action");
then(this.tracer.currentSpan()).isNull();
await().atMost(5, SECONDS)
.untilAsserted(() -> then(this.reporter.getSpans()).hasSize(1));
then(this.reporter.getSpans()).hasSize(1);
zipkin2.Span span = this.reporter.getSpans().get(0);
then(span.name()).isEqualTo("rxjava");
await().atMost(5, SECONDS).untilAsserted(() -> then(this.spans).hasSize(1));
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("rxjava");
}
@Test
@@ -100,9 +99,8 @@ public class SleuthRxJavaTests {
then(this.caller.toString()).isEqualTo("actual_action");
then(this.tracer.currentSpan()).isNull();
// making sure here that no new spans were created or reported as closed
then(this.reporter.getSpans()).hasSize(1);
zipkin2.Span span = this.reporter.getSpans().get(0);
then(span.name()).isEqualTo("current_span");
then(this.spans).hasSize(1);
then(this.spans.get(0).name()).isEqualTo("current_span");
}
@Configuration
@@ -115,8 +113,8 @@ public class SleuthRxJavaTests {
}
@Bean
ArrayListSpanReporter spanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}

View File

@@ -60,6 +60,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -21,18 +21,19 @@ import java.util.concurrent.atomic.AtomicBoolean;
import brave.Span;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import zipkin2.reporter.Reporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@@ -59,13 +60,13 @@ public class TracingOnScheduledTests {
TestBeanWithScheduledMethodThatThrowsAnException throwsAnException;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@Before
public void setup() {
this.beanWithScheduledMethod.clear();
this.beanWithScheduledMethodToBeIgnored.clear();
this.reporter.clear();
this.spans.clear();
}
@Test
@@ -107,28 +108,28 @@ public class TracingOnScheduledTests {
Span storedSpan = TracingOnScheduledTests.this.beanWithScheduledMethod.getSpan();
then(storedSpan).isNotNull();
then(storedSpan.context().traceId()).isNotNull();
zipkin2.Span foundSpan = this.reporter.getSpans().stream()
MutableSpan foundSpan = spans.spans().stream()
.filter(span -> !span.tags().containsKey("error")
&& span.tags().containsValue("TestBeanWithScheduledMethod"))
.findFirst().orElseThrow(() -> new AssertionError("Span is missing"));
then(foundSpan.tags()).contains(
new AbstractMap.SimpleEntry<>("class", "TestBeanWithScheduledMethod"),
new AbstractMap.SimpleEntry<>("method", "scheduledMethod"));
then(foundSpan.durationAsLong()).isGreaterThan(0L);
then(foundSpan.finishTimestamp()).isGreaterThan(0L);
}
private void spanIsSetOnAScheduledMethodWithErrorTag() {
Span storedSpan = TracingOnScheduledTests.this.beanWithScheduledMethod.getSpan();
then(storedSpan).isNotNull();
then(storedSpan.context().traceId()).isNotNull();
zipkin2.Span foundSpan = this.reporter.getSpans().stream()
MutableSpan foundSpan = spans.spans().stream()
.filter(span -> span.tags().containsKey("error")).findFirst()
.orElseThrow(() -> new AssertionError("Span is missing"));
then(foundSpan.tags()).contains(
new AbstractMap.SimpleEntry<>("class",
"TestBeanWithScheduledMethodThatThrowsAnException"),
new AbstractMap.SimpleEntry<>("method", "scheduledMethod"));
then(foundSpan.durationAsLong()).isGreaterThan(0L);
then(foundSpan.finishTimestamp()).isGreaterThan(0L);
then(foundSpan.tags().get("error")).isNotEmpty();
}
@@ -145,8 +146,8 @@ public class TracingOnScheduledTests {
class ScheduledTestConfiguration {
@Bean
Reporter<zipkin2.Span> testRepoter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -69,6 +69,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -18,7 +18,9 @@ package org.springframework.cloud.sleuth.instrument.web;
import brave.ScopedSpan;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.assertj.core.api.BDDAssertions;
@@ -31,7 +33,6 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;
@@ -56,7 +57,7 @@ public class GH1102Tests {
TestRetry testRetry;
@Autowired
ArrayListSpanReporter reporter;
TestSpanHandler spans;
@LocalServerPort
int port;
@@ -90,8 +91,8 @@ public class GH1102Tests {
}
@Bean
ArrayListSpanReporter reporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -16,12 +16,11 @@
package org.springframework.cloud.sleuth.instrument.web;
import java.util.List;
import java.util.stream.Collectors;
import brave.Span;
import brave.Tracer;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import org.awaitility.Awaitility;
import org.junit.Test;
import org.slf4j.Logger;
@@ -34,7 +33,6 @@ import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.sleuth.instrument.web.client.TraceWebClientAutoConfiguration;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -66,75 +64,69 @@ public class TraceWebFluxTests {
"security.basic.enabled=false",
"management.security.enabled=false")
.run();
ArrayListSpanReporter accumulator = context.getBean(ArrayListSpanReporter.class);
TestSpanHandler spans = context.getBean(TestSpanHandler.class);
int port = context.getBean(Environment.class).getProperty("local.server.port",
Integer.class);
Controller2 controller2 = context.getBean(Controller2.class);
clean(accumulator, controller2);
clean(spans, controller2);
// when
ClientResponse response = whenRequestIsSent(port, "/api/c2/10");
// then
thenSpanWasReportedWithTags(accumulator, response);
clean(accumulator, controller2);
thenSpanWasReportedWithTags(spans, response);
clean(spans, controller2);
// when
response = whenRequestIsSent(port, "/api/fn/20");
// then
thenFunctionalSpanWasReportedWithTags(accumulator, response);
accumulator.clear();
thenFunctionalSpanWasReportedWithTags(spans, response);
spans.clear();
// when
ClientResponse nonSampledResponse = whenNonSampledRequestIsSent(port);
// then
thenNoSpanWasReported(accumulator, nonSampledResponse, controller2);
accumulator.clear();
thenNoSpanWasReported(spans, nonSampledResponse, controller2);
spans.clear();
// when
ClientResponse skippedPatternResponse = whenRequestIsSentToSkippedPattern(port);
// then
thenNoSpanWasReported(accumulator, skippedPatternResponse, controller2);
thenNoSpanWasReported(spans, skippedPatternResponse, controller2);
// cleanup
context.close();
}
private void clean(ArrayListSpanReporter accumulator, Controller2 controller2) {
accumulator.clear();
private void clean(TestSpanHandler spans, Controller2 controller2) {
spans.clear();
controller2.span = null;
}
private void thenSpanWasReportedWithTags(ArrayListSpanReporter accumulator,
private void thenSpanWasReportedWithTags(TestSpanHandler spans,
ClientResponse response) {
Awaitility.await()
.untilAsserted(() -> then(response.statusCode().value()).isEqualTo(200));
List<zipkin2.Span> spans = accumulator.getSpans().stream()
.filter(span -> "get /api/c2/{id}".equals(span.name()))
.collect(Collectors.toList());
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("get /api/c2/{id}");
then(spans.get(0).name()).isEqualTo("GET /api/c2/{id}");
then(spans.get(0).tags()).containsEntry("mvc.controller.method", "successful")
.containsEntry("mvc.controller.class", "Controller2");
}
private void thenFunctionalSpanWasReportedWithTags(ArrayListSpanReporter accumulator,
private void thenFunctionalSpanWasReportedWithTags(TestSpanHandler spans,
ClientResponse response) {
Awaitility.await()
.untilAsserted(() -> then(response.statusCode().value()).isEqualTo(200));
List<zipkin2.Span> spans = accumulator.getSpans().stream()
.filter(span -> "get /api/fn/{id}".equals(span.name()))
.collect(Collectors.toList());
then(spans).hasSize(1);
then(spans.get(0).name()).isEqualTo("get /api/fn/{id}");
then(spans.get(0).name()).isEqualTo("GET /api/fn/{id}");
then(spans.get(0).tags()).hasEntrySatisfying("mvc.controller.class",
value -> then(value).startsWith("TraceWebFluxTests$Config$$Lambda$"));
}
private void thenNoSpanWasReported(ArrayListSpanReporter accumulator,
ClientResponse response, Controller2 controller2) {
private void thenNoSpanWasReported(TestSpanHandler spans, ClientResponse response,
Controller2 controller2) {
Awaitility.await().untilAsserted(() -> {
then(response.statusCode().value()).isEqualTo(200);
then(accumulator.getSpans()).isEmpty();
then(spans).isEmpty();
});
then(controller2.span).isNotNull();
then(controller2.span.context().traceIdString()).isEqualTo(EXPECTED_TRACE_ID);
@@ -178,15 +170,8 @@ public class TraceWebFluxTests {
}
@Bean
ArrayListSpanReporter spanReporter() {
return new ArrayListSpanReporter() {
@Override
public List<zipkin2.Span> getSpans() {
List<zipkin2.Span> spans = super.getSpans();
log.info("Reported the following spans: \n\n" + spans);
return spans;
}
};
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

View File

@@ -64,6 +64,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>

View File

@@ -24,7 +24,10 @@ import java.util.Objects;
import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.handler.MutableSpan;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import org.apache.commons.logging.Log;
@@ -47,7 +50,6 @@ import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator;
import org.springframework.cloud.sleuth.util.ArrayListSpanReporter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
@@ -81,7 +83,7 @@ public class TraceZuulIntegrationTests {
Tracing tracing;
@Autowired
ArrayListSpanReporter spanAccumulator;
TestSpanHandler spans;
@Autowired
RestTemplate restTemplate;
@@ -92,7 +94,7 @@ public class TraceZuulIntegrationTests {
@Before
@After
public void cleanup() {
this.spanAccumulator.clear();
this.spans.clear();
}
@Test
@@ -116,10 +118,9 @@ public class TraceZuulIntegrationTests {
}
then(this.tracing.tracer().currentSpan()).isNull();
List<zipkin2.Span> spans = this.spanAccumulator.getSpans();
then(spans).isNotEmpty();
everySpanHasTheSameTraceId(spans);
everyParentIdHasItsCorrespondingSpan(spans);
then(this.spans).isNotEmpty();
everySpanHasTheSameTraceId(this.spans.spans());
everyParentIdHasItsCorrespondingSpan(this.spans.spans());
}
@Test
@@ -138,25 +139,24 @@ public class TraceZuulIntegrationTests {
}
then(this.tracing.tracer().currentSpan()).isNull();
List<zipkin2.Span> spans = this.spanAccumulator.getSpans();
then(spans).isNotEmpty();
everySpanHasTheSameTraceId(spans);
everyParentIdHasItsCorrespondingSpan(spans);
then(this.spans).isNotEmpty();
everySpanHasTheSameTraceId(this.spans.spans());
everyParentIdHasItsCorrespondingSpan(this.spans.spans());
}
void everySpanHasTheSameTraceId(List<zipkin2.Span> actual) {
void everySpanHasTheSameTraceId(List<MutableSpan> actual) {
BDDAssertions.assertThat(actual).isNotNull();
List<String> traceIds = actual.stream().map(zipkin2.Span::traceId).distinct()
List<String> traceIds = actual.stream().map(MutableSpan::traceId).distinct()
.collect(toList());
log.info("Stored traceids " + traceIds);
assertThat(traceIds).hasSize(1);
}
void everyParentIdHasItsCorrespondingSpan(List<zipkin2.Span> actual) {
void everyParentIdHasItsCorrespondingSpan(List<MutableSpan> actual) {
BDDAssertions.assertThat(actual).isNotNull();
List<String> parentSpanIds = actual.stream().map(zipkin2.Span::parentId)
List<String> parentSpanIds = actual.stream().map(MutableSpan::parentId)
.filter(Objects::nonNull).collect(toList());
List<String> spanIds = actual.stream().map(zipkin2.Span::id).distinct()
List<String> spanIds = actual.stream().map(MutableSpan::id).distinct()
.collect(toList());
List<String> difference = new ArrayList<>(parentSpanIds);
difference.removeAll(spanIds);
@@ -192,8 +192,8 @@ class SampleZuulProxyApplication {
}
@Bean
ArrayListSpanReporter testSpanReporter() {
return new ArrayListSpanReporter();
SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
@Bean

Some files were not shown because too many files have changed in this diff Show More