diff --git a/pom.xml b/pom.xml index 1a1cd6622..3b0814023 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ org.springframework.cloud spring-cloud-build - 1.2.0.BUILD-SNAPSHOT + 1.3.0.BUILD-SNAPSHOT @@ -229,10 +229,10 @@ 1.8 2.19.1 2.17 - 1.2.0.BUILD-SNAPSHOT - 1.1.3.BUILD-SNAPSHOT + 1.3.0.BUILD-SNAPSHOT + 1.2.0.BUILD-SNAPSHOT Brooklyn.BUILD-SNAPSHOT - 1.2.0.BUILD-SNAPSHOT + 1.3.0.BUILD-SNAPSHOT diff --git a/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/TraceWebAutoConfiguration.java b/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/TraceWebAutoConfiguration.java index 0223ad4b4..447a6c300 100644 --- a/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/TraceWebAutoConfiguration.java +++ b/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/TraceWebAutoConfiguration.java @@ -15,6 +15,12 @@ */ package org.springframework.cloud.sleuth.instrument.web; +import static javax.servlet.DispatcherType.ASYNC; +import static javax.servlet.DispatcherType.ERROR; +import static javax.servlet.DispatcherType.FORWARD; +import static javax.servlet.DispatcherType.INCLUDE; +import static javax.servlet.DispatcherType.REQUEST; + import java.util.regex.Pattern; import org.springframework.beans.factory.BeanFactory; @@ -27,8 +33,8 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.cloud.sleuth.SpanNamer; import org.springframework.cloud.sleuth.SpanReporter; import org.springframework.cloud.sleuth.TraceKeys; @@ -40,15 +46,9 @@ import org.springframework.context.annotation.Import; import org.springframework.util.StringUtils; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import static javax.servlet.DispatcherType.ASYNC; -import static javax.servlet.DispatcherType.ERROR; -import static javax.servlet.DispatcherType.FORWARD; -import static javax.servlet.DispatcherType.INCLUDE; -import static javax.servlet.DispatcherType.REQUEST; - /** - * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration Auto-configuration} - * enables tracing to HTTP requests. + * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration + * Auto-configuration} enables tracing to HTTP requests. * * @author Tomasz Nurkewicz, 4financeIT * @author Michal Chmielarz, 4financeIT @@ -71,8 +71,8 @@ public class TraceWebAutoConfiguration { private String skipPattern; /** - * Nested config that configures Web MVC if it's present - * (without adding a runtime dependency to it) + * Nested config that configures Web MVC if it's present (without adding a runtime + * dependency to it) */ @Configuration @ConditionalOnClass(WebMvcConfigurerAdapter.class) @@ -81,26 +81,31 @@ public class TraceWebAutoConfiguration { } @Bean - public TraceWebAspect traceWebAspect(Tracer tracer, TraceKeys traceKeys, SpanNamer spanNamer) { + public TraceWebAspect traceWebAspect(Tracer tracer, TraceKeys traceKeys, + SpanNamer spanNamer) { return new TraceWebAspect(tracer, spanNamer, traceKeys); } @Bean @ConditionalOnClass(name = "org.springframework.data.rest.webmvc.support.DelegatingHandlerMapping") - public TraceSpringDataBeanPostProcessor traceSpringDataBeanPostProcessor(BeanFactory beanFactory) { + public TraceSpringDataBeanPostProcessor traceSpringDataBeanPostProcessor( + BeanFactory beanFactory) { return new TraceSpringDataBeanPostProcessor(beanFactory); } @Bean @ConditionalOnMissingBean - public HttpTraceKeysInjector httpTraceKeysInjector(Tracer tracer, TraceKeys traceKeys) { + public HttpTraceKeysInjector httpTraceKeysInjector(Tracer tracer, + TraceKeys traceKeys) { return new HttpTraceKeysInjector(tracer, traceKeys); } @Bean public FilterRegistrationBean traceWebFilter(TraceFilter traceFilter) { - FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(traceFilter); - filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, REQUEST); + FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean( + traceFilter); + filterRegistrationBean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, + REQUEST); filterRegistrationBean.setOrder(TraceFilter.ORDER); return filterRegistrationBean; } @@ -116,7 +121,8 @@ public class TraceWebAutoConfiguration { @Bean @ConditionalOnMissingBean - public HttpSpanExtractor httpSpanExtractor(@Value("${spring.sleuth.web.skipPattern:}") String skipPattern) { + public HttpSpanExtractor httpSpanExtractor( + @Value("${spring.sleuth.web.skipPattern:}") String skipPattern) { return new ZipkinHttpSpanExtractor(Pattern.compile(skipPattern)); } @@ -145,23 +151,27 @@ public class TraceWebAutoConfiguration { @Override public Pattern skipPattern() { return getPatternForManagementServerProperties( - managementServerProperties, SkipPatternProviderConfig.this.skipPattern); + managementServerProperties, + SkipPatternProviderConfig.this.skipPattern); } }; } /** - * Sets or appends {@link ManagementServerProperties#getContextPath()} to the - * skip pattern. If neither is available then sets the default one + * Sets or appends {@link ManagementServerProperties#getContextPath()} to the skip + * pattern. If neither is available then sets the default one */ static Pattern getPatternForManagementServerProperties( - ManagementServerProperties managementServerProperties, String skipPattern) { - if (StringUtils.hasText(skipPattern) && - StringUtils.hasText(managementServerProperties.getContextPath())) { - return Pattern.compile(skipPattern + "|" + - managementServerProperties.getContextPath() + ".*"); - } else if (StringUtils.hasText(managementServerProperties.getContextPath())) { - return Pattern.compile(managementServerProperties.getContextPath() + ".*"); + ManagementServerProperties managementServerProperties, + String skipPattern) { + if (StringUtils.hasText(skipPattern) + && StringUtils.hasText(managementServerProperties.getContextPath())) { + return Pattern.compile(skipPattern + "|" + + managementServerProperties.getContextPath() + ".*"); + } + else if (StringUtils.hasText(managementServerProperties.getContextPath())) { + return Pattern + .compile(managementServerProperties.getContextPath() + ".*"); } return defaultSkipPattern(skipPattern); } @@ -180,7 +190,8 @@ public class TraceWebAutoConfiguration { return defaultSkipPatternProvider(this.skipPattern); } - private static SkipPatternProvider defaultSkipPatternProvider(final String skipPattern) { + private static SkipPatternProvider defaultSkipPatternProvider( + final String skipPattern) { return new SkipPatternProvider() { @Override public Pattern skipPattern() { @@ -190,8 +201,7 @@ public class TraceWebAutoConfiguration { } private static Pattern defaultSkipPattern(String skipPattern) { - return StringUtils.hasText(skipPattern) ? - Pattern.compile(skipPattern) + return StringUtils.hasText(skipPattern) ? Pattern.compile(skipPattern) : Pattern.compile(TraceFilter.DEFAULT_SKIP_PATTERN); } diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/autoconfig/TraceAutoConfigurationTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/autoconfig/TraceAutoConfigurationTests.java index 65eca35d3..4afe8692c 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/autoconfig/TraceAutoConfigurationTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/autoconfig/TraceAutoConfigurationTests.java @@ -13,27 +13,29 @@ */ package org.springframework.cloud.sleuth.autoconfig; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.After; import org.junit.Test; import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; +import org.springframework.boot.test.util.EnvironmentTestUtils; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.Tracer; import org.springframework.cloud.sleuth.log.SleuthLogAutoConfiguration; import org.springframework.cloud.sleuth.sampler.NeverSampler; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.EnvironmentTestUtils.addEnvironment; - public class TraceAutoConfigurationTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - @After public void close() { + @After + public void close() { context.close(); } - @Test public void defaultsTo64BitTraceId() { + @Test + public void defaultsTo64BitTraceId() { context = new AnnotationConfigApplicationContext(); context.register(PropertyPlaceholderAutoConfiguration.class, SleuthLogAutoConfiguration.class, TraceAutoConfiguration.class); @@ -53,8 +55,9 @@ public class TraceAutoConfigurationTests { } } - @Test public void optInto128BitTraceId() { - addEnvironment(context, "spring.sleuth.traceId128:true"); + @Test + public void optInto128BitTraceId() { + EnvironmentTestUtils.addEnvironment(context, "spring.sleuth.traceId128:true"); context.register(PropertyPlaceholderAutoConfiguration.class, SleuthLogAutoConfiguration.class, TraceAutoConfiguration.class); context.refresh(); diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/async/issues/issue410/Issue410Tests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/async/issues/issue410/Issue410Tests.java index 48be0e194..2d4e618ce 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/async/issues/issue410/Issue410Tests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/async/issues/issue410/Issue410Tests.java @@ -16,6 +16,9 @@ package org.springframework.cloud.sleuth.instrument.async.issues.issue410; +import static org.assertj.core.api.BDDAssertions.then; +import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; + import java.lang.invoke.MethodHandles; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -31,8 +34,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.boot.test.WebIntegrationTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.Tracer; @@ -45,49 +48,54 @@ import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.jayway.awaitility.Awaitility; -import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; - /** * @author Marcin Grzejszczak */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = Application.class) -@WebIntegrationTest -@TestPropertySource(properties = {"ribbon.eureka.enabled=false", "feign.hystrix.enabled=false", "server.port=0"}) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, properties = { + "ribbon.eureka.enabled=false", "feign.hystrix.enabled=false" }) public class Issue410Tests { - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); + private static final Log log = LogFactory + .getLog(MethodHandles.lookup().lookupClass()); - @Autowired Environment environment; - @Autowired Tracer tracer; - @Autowired AsyncTask asyncTask; - @Autowired RestTemplate restTemplate; + @Autowired + Environment environment; + @Autowired + Tracer tracer; + @Autowired + AsyncTask asyncTask; + @Autowired + RestTemplate restTemplate; /** * Related to issue #445 */ - @Autowired Application.MyService executorService; + @Autowired + Application.MyService executorService; @Test public void should_pass_tracing_info_for_tasks_running_without_a_pool() { Span span = this.tracer.createSpan("foo"); log.info("Starting test"); try { - String response = this.restTemplate.getForObject("http://localhost:" + port() + "/without_pool", String.class); + String response = this.restTemplate.getForObject( + "http://localhost:" + port() + "/without_pool", String.class); then(response).isEqualTo(span.traceIdString()); Awaitility.await().until(() -> { then(this.asyncTask.getSpan().get()).isNotNull(); - then(this.asyncTask.getSpan().get().getTraceId()).isEqualTo(span.getTraceId()); + then(this.asyncTask.getSpan().get().getTraceId()) + .isEqualTo(span.getTraceId()); }); - } finally { + } + finally { this.tracer.close(span); } } @@ -97,14 +105,17 @@ public class Issue410Tests { Span span = this.tracer.createSpan("foo"); log.info("Starting test"); try { - String response = this.restTemplate.getForObject("http://localhost:" + port() + "/with_pool", String.class); + String response = this.restTemplate.getForObject( + "http://localhost:" + port() + "/with_pool", String.class); then(response).isEqualTo(span.traceIdString()); Awaitility.await().until(() -> { then(this.asyncTask.getSpan().get()).isNotNull(); - then(this.asyncTask.getSpan().get().getTraceId()).isEqualTo(span.getTraceId()); + then(this.asyncTask.getSpan().get().getTraceId()) + .isEqualTo(span.getTraceId()); }); - } finally { + } + finally { this.tracer.close(span); } } @@ -117,14 +128,17 @@ public class Issue410Tests { Span span = this.tracer.createSpan("foo"); log.info("Starting test"); try { - String response = this.restTemplate.getForObject("http://localhost:" + port() + "/completable", String.class); + String response = this.restTemplate.getForObject( + "http://localhost:" + port() + "/completable", String.class); then(response).isEqualTo(span.traceIdString()); Awaitility.await().until(() -> { then(this.asyncTask.getSpan().get()).isNotNull(); - then(this.asyncTask.getSpan().get().getTraceId()).isEqualTo(span.getTraceId()); + then(this.asyncTask.getSpan().get().getTraceId()) + .isEqualTo(span.getTraceId()); }); - } finally { + } + finally { this.tracer.close(span); } } @@ -137,14 +151,17 @@ public class Issue410Tests { Span span = this.tracer.createSpan("foo"); log.info("Starting test"); try { - String response = this.restTemplate.getForObject("http://localhost:" + port() + "/taskScheduler", String.class); + String response = this.restTemplate.getForObject( + "http://localhost:" + port() + "/taskScheduler", String.class); then(response).isEqualTo(span.traceIdString()); Awaitility.await().until(() -> { then(this.asyncTask.getSpan().get()).isNotNull(); - then(this.asyncTask.getSpan().get().getTraceId()).isEqualTo(span.getTraceId()); + then(this.asyncTask.getSpan().get().getTraceId()) + .isEqualTo(span.getTraceId()); }); - } finally { + } + finally { this.tracer.close(span); } } @@ -154,20 +171,22 @@ public class Issue410Tests { } } - @Configuration @EnableAsync class AppConfig { - @Bean public Sampler testSampler() { + @Bean + public Sampler testSampler() { return new AlwaysSampler(); } - @Bean public RestTemplate restTemplate() { + @Bean + public RestTemplate restTemplate() { return new RestTemplate(); } - @Bean public Executor poolTaskExecutor() { + @Bean + public Executor poolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.initialize(); return executor; @@ -182,10 +201,16 @@ class AsyncTask { private AtomicReference span = new AtomicReference<>(); - @Autowired Tracer tracer; - @Autowired @Qualifier("poolTaskExecutor") Executor executor; - @Autowired @Qualifier("taskScheduler") Executor taskScheduler; - @Autowired BeanFactory beanFactory; + @Autowired + Tracer tracer; + @Autowired + @Qualifier("poolTaskExecutor") + Executor executor; + @Autowired + @Qualifier("taskScheduler") + Executor taskScheduler; + @Autowired + BeanFactory beanFactory; @Async("poolTaskExecutor") public void runWithPool() { @@ -201,16 +226,14 @@ class AsyncTask { public Span completableFutures() throws ExecutionException, InterruptedException { log.info("This task is running with completable future"); - CompletableFuture span1 = CompletableFuture - .supplyAsync(() -> { - AsyncTask.log.info("First completable future"); - return AsyncTask.this.tracer.getCurrentSpan(); - }, AsyncTask.this.executor); - CompletableFuture span2 = CompletableFuture - .supplyAsync(() -> { - AsyncTask.log.info("Second completable future"); - return AsyncTask.this.tracer.getCurrentSpan(); - }, AsyncTask.this.executor); + CompletableFuture span1 = CompletableFuture.supplyAsync(() -> { + AsyncTask.log.info("First completable future"); + return AsyncTask.this.tracer.getCurrentSpan(); + }, AsyncTask.this.executor); + CompletableFuture span2 = CompletableFuture.supplyAsync(() -> { + AsyncTask.log.info("Second completable future"); + return AsyncTask.this.tracer.getCurrentSpan(); + }, AsyncTask.this.executor); CompletableFuture response = CompletableFuture.allOf(span1, span2) .thenApply(ignoredVoid -> { AsyncTask.log.info("Third completable future"); @@ -227,16 +250,16 @@ class AsyncTask { public Span taskScheduler() throws ExecutionException, InterruptedException { log.info("This task is running with completable future"); - CompletableFuture span1 = CompletableFuture - .supplyAsync(() -> { - AsyncTask.log.info("First completable future"); - return AsyncTask.this.tracer.getCurrentSpan(); - }, new LazyTraceExecutor(AsyncTask.this.beanFactory, AsyncTask.this.taskScheduler)); - CompletableFuture span2 = CompletableFuture - .supplyAsync(() -> { - AsyncTask.log.info("Second completable future"); - return AsyncTask.this.tracer.getCurrentSpan(); - }, new LazyTraceExecutor(AsyncTask.this.beanFactory, AsyncTask.this.taskScheduler)); + CompletableFuture span1 = CompletableFuture.supplyAsync(() -> { + AsyncTask.log.info("First completable future"); + return AsyncTask.this.tracer.getCurrentSpan(); + }, new LazyTraceExecutor(AsyncTask.this.beanFactory, + AsyncTask.this.taskScheduler)); + CompletableFuture span2 = CompletableFuture.supplyAsync(() -> { + AsyncTask.log.info("Second completable future"); + return AsyncTask.this.tracer.getCurrentSpan(); + }, new LazyTraceExecutor(AsyncTask.this.beanFactory, + AsyncTask.this.taskScheduler)); CompletableFuture response = CompletableFuture.allOf(span1, span2) .thenApply(ignoredVoid -> { AsyncTask.log.info("Third completable future"); @@ -262,8 +285,10 @@ class Application { private static final Log log = LogFactory.getLog(Application.class); - @Autowired AsyncTask asyncTask; - @Autowired Tracer tracer; + @Autowired + AsyncTask asyncTask; + @Autowired + Tracer tracer; @RequestMapping("/with_pool") public String withPool() { @@ -295,9 +320,11 @@ class Application { /** * Related to issue #445 */ - @Bean public MyService executorService() { + @Bean + public MyService executorService() { return new MyService() { - @Override public void execute(Runnable command) { + @Override + public void execute(Runnable command) { } }; diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/hystrix/HystrixAnnotationsIntegrationTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/hystrix/HystrixAnnotationsIntegrationTests.java index fe13cb34f..52f808eb2 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/hystrix/HystrixAnnotationsIntegrationTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/hystrix/HystrixAnnotationsIntegrationTests.java @@ -16,11 +16,11 @@ package org.springframework.cloud.sleuth.instrument.hystrix; -import java.util.concurrent.atomic.AtomicReference; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.BDDAssertions.then; +import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; -import com.jayway.awaitility.Awaitility; -import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; -import com.netflix.hystrix.strategy.HystrixPlugins; +import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.AfterClass; @@ -28,7 +28,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.Span; @@ -39,20 +39,21 @@ import org.springframework.cloud.sleuth.trace.TestSpanContextHolder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.assertj.core.api.BDDAssertions.then; -import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; +import com.jayway.awaitility.Awaitility; +import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; +import com.netflix.hystrix.strategy.HystrixPlugins; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = { - HystrixAnnotationsIntegrationTests.TestConfig.class }) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { HystrixAnnotationsIntegrationTests.TestConfig.class }) @DirtiesContext public class HystrixAnnotationsIntegrationTests { - @Autowired HystrixCommandInvocationSpanCatcher catcher; - @Autowired Tracer tracer; + @Autowired + HystrixCommandInvocationSpanCatcher catcher; + @Autowired + Tracer tracer; @BeforeClass @AfterClass @@ -109,8 +110,7 @@ public class HystrixAnnotationsIntegrationTests { @Override public void run() { then(HystrixAnnotationsIntegrationTests.this.catcher.getSpan()) - .nameStartsWith("hystrix") - .isALocalComponentSpan(); + .nameStartsWith("hystrix").isALocalComponentSpan(); } }); } @@ -153,8 +153,8 @@ public class HystrixAnnotationsIntegrationTests { public String getSpanName() { if (this.spanCaughtFromHystrixThread == null || (this.spanCaughtFromHystrixThread.get() != null - && this.spanCaughtFromHystrixThread.get() - .getName() == null)) { + && this.spanCaughtFromHystrixThread.get() + .getName() == null)) { return null; } return this.spanCaughtFromHystrixThread.get().getName(); diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/messaging/TraceContextPropagationChannelInterceptorTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/messaging/TraceContextPropagationChannelInterceptorTests.java index 357e4a115..da0946f80 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/messaging/TraceContextPropagationChannelInterceptorTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/messaging/TraceContextPropagationChannelInterceptorTests.java @@ -16,14 +16,17 @@ package org.springframework.cloud.sleuth.instrument.messaging; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.IntegrationTest; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.Tracer; @@ -39,16 +42,11 @@ import org.springframework.messaging.PollableChannel; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - /** * @author Spencer Gibb */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes=App.class) -@IntegrationTest +@SpringBootTest(classes = App.class) @DirtiesContext public class TraceContextPropagationChannelInterceptorTests { @@ -76,17 +74,17 @@ public class TraceContextPropagationChannelInterceptorTests { assertNotNull("message was null", message); - Long spanId = Span - .hexToId(message.getHeaders().get(TraceMessageHeaders.SPAN_ID_NAME, String.class)); - assertNotEquals("spanId was equal to parent's id", expectedSpanId, spanId); + Long spanId = Span.hexToId( + message.getHeaders().get(TraceMessageHeaders.SPAN_ID_NAME, String.class)); + assertNotEquals("spanId was equal to parent's id", expectedSpanId, spanId); - long traceId = Span - .hexToId(message.getHeaders().get(TraceMessageHeaders.TRACE_ID_NAME, String.class)); + long traceId = Span.hexToId(message.getHeaders() + .get(TraceMessageHeaders.TRACE_ID_NAME, String.class)); assertNotNull("traceId was null", traceId); - Long parentId = Span - .hexToId(message.getHeaders().get(TraceMessageHeaders.PARENT_ID_NAME, String.class)); - assertEquals("parentId was not equal to parent's id", expectedSpanId, parentId); + Long parentId = Span.hexToId(message.getHeaders() + .get(TraceMessageHeaders.PARENT_ID_NAME, String.class)); + assertEquals("parentId was not equal to parent's id", expectedSpanId, parentId); } diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/messaging/websocket/TraceWebSocketAutoConfigurationTest.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/messaging/websocket/TraceWebSocketAutoConfigurationTest.java index 9e9839e01..811c230ab 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/messaging/websocket/TraceWebSocketAutoConfigurationTest.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/messaging/websocket/TraceWebSocketAutoConfigurationTest.java @@ -16,30 +16,30 @@ package org.springframework.cloud.sleuth.instrument.messaging.websocket; +import static org.assertj.core.api.BDDAssertions.then; + 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.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.instrument.messaging.TraceChannelInterceptor; import org.springframework.cloud.sleuth.sampler.AlwaysSampler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; -import static org.assertj.core.api.BDDAssertions.then; - /** * @author Marcin Grzejszczak */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = TraceWebSocketAutoConfigurationTest.Config.class) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TraceWebSocketAutoConfigurationTest.Config.class) public class TraceWebSocketAutoConfigurationTest { @Autowired @@ -71,7 +71,8 @@ public class TraceWebSocketAutoConfigurationTest { registry.addEndpoint("/hello").withSockJS(); } - @Bean Sampler testSampler() { + @Bean + Sampler testSampler() { return new AlwaysSampler(); } } diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/rxjava/SleuthRxJavaTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/rxjava/SleuthRxJavaTests.java index 2518507f0..b029d7c92 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/rxjava/SleuthRxJavaTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/rxjava/SleuthRxJavaTests.java @@ -1,5 +1,10 @@ package org.springframework.cloud.sleuth.instrument.rxjava; +import static com.jayway.awaitility.Awaitility.await; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.BDDAssertions.then; +import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; + import java.util.ArrayList; import java.util.List; @@ -11,7 +16,7 @@ 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.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.SpanReporter; @@ -21,24 +26,22 @@ import org.springframework.cloud.sleuth.trace.TestSpanContextHolder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import rx.Observable; import rx.functions.Action0; import rx.plugins.RxJavaPlugins; import rx.schedulers.Schedulers; -import static com.jayway.awaitility.Awaitility.await; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = {SleuthRxJavaTests.TestConfig.class}) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { SleuthRxJavaTests.TestConfig.class }) @DirtiesContext public class SleuthRxJavaTests { - @Autowired Listener listener; - @Autowired Tracer tracer; + @Autowired + Listener listener; + @Autowired + Tracer tracer; StringBuffer caller = new StringBuffer(); @Before @@ -59,17 +62,20 @@ public class SleuthRxJavaTests { @Test public void should_create_new_span_when_rx_java_action_is_executed_and_there_was_no_span() { - Observable.defer(() -> Observable.just( - (Action0) () -> this.caller = new StringBuffer("actual_action") - )).subscribeOn(Schedulers.newThread()).toBlocking() - .subscribe(Action0::call); + Observable + .defer(() -> Observable.just( + (Action0) () -> this.caller = new StringBuffer("actual_action"))) + .subscribeOn(Schedulers.newThread()).toBlocking() + .subscribe(Action0::call); then(this.caller.toString()).isEqualTo("actual_action"); then(this.tracer.getCurrentSpan()).isNull(); - await().atMost(5, SECONDS).until(() -> then(this.listener.getEvents()).hasSize(1)); + await().atMost(5, SECONDS) + .until(() -> then(this.listener.getEvents()).hasSize(1)); then(this.listener.getEvents().get(0)).hasNameEqualTo("rxjava"); then(this.listener.getEvents().get(0)).isExportable(); - then(this.listener.getEvents().get(0)).hasATag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, "rxjava"); + then(this.listener.getEvents().get(0)).hasATag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, + "rxjava"); then(this.listener.getEvents().get(0)).isALocalComponentSpan(); } @@ -78,18 +84,20 @@ public class SleuthRxJavaTests { Span spanInCurrentThread = this.tracer.createSpan("current_span"); this.tracer.addTag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, "current_span"); - Observable.defer(() -> Observable.just( - (Action0) () -> this.caller = new StringBuffer("actual_action") - )).subscribeOn(Schedulers.newThread()).toBlocking() - .subscribe(Action0::call); + Observable + .defer(() -> Observable.just( + (Action0) () -> this.caller = new StringBuffer("actual_action"))) + .subscribeOn(Schedulers.newThread()).toBlocking() + .subscribe(Action0::call); then(this.caller.toString()).isEqualTo("actual_action"); then(this.tracer.getCurrentSpan()).isNotNull(); - //making sure here that no new spans were created or reported as closed + // making sure here that no new spans were created or reported as closed then(this.listener.getEvents()).isEmpty(); then(spanInCurrentThread).hasNameEqualTo(spanInCurrentThread.getName()); then(spanInCurrentThread).isExportable(); - then(spanInCurrentThread).hasATag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, "current_span"); + then(spanInCurrentThread).hasATag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, + "current_span"); then(spanInCurrentThread).isALocalComponentSpan(); } diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/scheduling/TracingOnScheduledTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/scheduling/TracingOnScheduledTests.java index 73844a044..557c0e58b 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/scheduling/TracingOnScheduledTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/scheduling/TracingOnScheduledTests.java @@ -16,13 +16,18 @@ package org.springframework.cloud.sleuth.instrument.scheduling; +import static com.jayway.awaitility.Awaitility.await; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.BDDAssertions.then; +import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; + import java.util.concurrent.atomic.AtomicBoolean; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.instrument.DefaultTestAutoConfiguration; import org.springframework.cloud.sleuth.sampler.AlwaysSampler; @@ -30,18 +35,16 @@ import org.springframework.cloud.sleuth.trace.TestSpanContextHolder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; -import static com.jayway.awaitility.Awaitility.await; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = {ScheduledTestConfiguration.class}) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { ScheduledTestConfiguration.class }) public class TracingOnScheduledTests { - @Autowired TestBeanWithScheduledMethod beanWithScheduledMethod; - @Autowired TestBeanWithScheduledMethodToBeIgnored beanWithScheduledMethodToBeIgnored; + @Autowired + TestBeanWithScheduledMethod beanWithScheduledMethod; + @Autowired + TestBeanWithScheduledMethodToBeIgnored beanWithScheduledMethodToBeIgnored; @Test public void should_have_span_set_after_scheduled_method_has_been_executed() { @@ -55,8 +58,10 @@ public class TracingOnScheduledTests { } @Test - public void should_not_span_in_the_scheduled_class_that_matches_skip_pattern() throws Exception { - await().atMost(5, SECONDS).untilAtomic(this.beanWithScheduledMethodToBeIgnored.isExecuted(), Matchers.is(true)); + public void should_not_span_in_the_scheduled_class_that_matches_skip_pattern() + throws Exception { + await().atMost(5, SECONDS).untilAtomic( + this.beanWithScheduledMethodToBeIgnored.isExecuted(), Matchers.is(true)); then(this.beanWithScheduledMethodToBeIgnored.getSpan()).isNull(); } @@ -64,7 +69,8 @@ public class TracingOnScheduledTests { return new Runnable() { @Override public void run() { - Span storedSpan = TracingOnScheduledTests.this.beanWithScheduledMethod.getSpan(); + Span storedSpan = TracingOnScheduledTests.this.beanWithScheduledMethod + .getSpan(); then(storedSpan).isNotNull(); then(storedSpan.getTraceId()).isNotNull(); then(storedSpan).hasATag("class", "TestBeanWithScheduledMethod"); @@ -77,7 +83,8 @@ public class TracingOnScheduledTests { return new Runnable() { @Override public void run() { - then(TracingOnScheduledTests.this.beanWithScheduledMethod.getSpan()).isNotEqualTo(spanToCompare); + then(TracingOnScheduledTests.this.beanWithScheduledMethod.getSpan()) + .isNotEqualTo(spanToCompare); } }; } @@ -88,11 +95,13 @@ public class TracingOnScheduledTests { @DefaultTestAutoConfiguration class ScheduledTestConfiguration { - @Bean TestBeanWithScheduledMethod testBeanWithScheduledMethod() { + @Bean + TestBeanWithScheduledMethod testBeanWithScheduledMethod() { return new TestBeanWithScheduledMethod(); } - @Bean TestBeanWithScheduledMethodToBeIgnored testBeanWithScheduledMethodToBeIgnored() { + @Bean + TestBeanWithScheduledMethodToBeIgnored testBeanWithScheduledMethodToBeIgnored() { return new TestBeanWithScheduledMethodToBeIgnored(); } diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/SpringDataInstrumentationTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/SpringDataInstrumentationTests.java index 4b603096f..923a82914 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/SpringDataInstrumentationTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/SpringDataInstrumentationTests.java @@ -16,22 +16,24 @@ package org.springframework.cloud.sleuth.instrument.web; -import javax.annotation.PostConstruct; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import static org.assertj.core.api.BDDAssertions.then; +import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; + import java.util.Collection; import java.util.stream.Collectors; import java.util.stream.Stream; -import com.jayway.awaitility.Awaitility; +import javax.annotation.PostConstruct; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; import org.junit.Before; 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.orm.jpa.EntityScan; +import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.Tracer; @@ -50,24 +52,27 @@ import org.springframework.hateoas.Resources; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; -import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; +import com.jayway.awaitility.Awaitility; /** * @author Marcin Grzejszczak */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = ReservationServiceApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ReservationServiceApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @DirtiesContext public class SpringDataInstrumentationTests { - @Autowired RestTemplate restTemplate; - @Autowired Environment environment; - @Autowired Tracer tracer; - @Autowired ArrayListSpanAccumulator arrayListSpanAccumulator; + @Autowired + RestTemplate restTemplate; + @Autowired + Environment environment; + @Autowired + Tracer tracer; + @Autowired + ArrayListSpanAccumulator arrayListSpanAccumulator; @Before public void setup() { @@ -80,30 +85,23 @@ public class SpringDataInstrumentationTests { then(names).isNotEmpty(); then(this.arrayListSpanAccumulator.getSpans()).isNotEmpty(); - Awaitility.await().until( () -> { - then(new ListOfSpans(this.arrayListSpanAccumulator.getSpans())).hasASpanWithName("http:/reservations") - .hasASpanWithTagKeyEqualTo("mvc.controller.class"); - }); + Awaitility.await().until(() -> { + then(new ListOfSpans(this.arrayListSpanAccumulator.getSpans())) + .hasASpanWithName("http:/reservations") + .hasASpanWithTagKeyEqualTo("mvc.controller.class"); + }); then(this.tracer.getCurrentSpan()).isNull(); then(ExceptionUtils.getLastException()).isNull(); } Collection names() { - ParameterizedTypeReference> ptr = - new ParameterizedTypeReference>() { - }; - ResponseEntity> responseEntity = - this.restTemplate.exchange("http://localhost:" + port() + "/reservations", - HttpMethod.GET, - null, - ptr - ); - return responseEntity - .getBody() - .getContent() - .stream() - .map(Reservation::getReservationName) - .collect(Collectors.toList()); + ParameterizedTypeReference> ptr = new ParameterizedTypeReference>() { + }; + ResponseEntity> responseEntity = this.restTemplate + .exchange("http://localhost:" + port() + "/reservations", HttpMethod.GET, + null, ptr); + return responseEntity.getBody().getContent().stream() + .map(Reservation::getReservationName).collect(Collectors.toList()); } private int port() { @@ -116,19 +114,23 @@ public class SpringDataInstrumentationTests { @EntityScan(basePackageClasses = Reservation.class) class ReservationServiceApplication { - @Bean RestTemplate restTemplate() { + @Bean + RestTemplate restTemplate() { return new RestTemplate(); } - @Bean SampleRecords sampleRecords(ReservationRepository reservationRepository) { + @Bean + SampleRecords sampleRecords(ReservationRepository reservationRepository) { return new SampleRecords(reservationRepository); } - @Bean ArrayListSpanAccumulator arrayListSpanAccumulator() { + @Bean + ArrayListSpanAccumulator arrayListSpanAccumulator() { return new ArrayListSpanAccumulator(); } - @Bean Sampler alwaysSampler() { + @Bean + Sampler alwaysSampler() { return new AlwaysSampler(); } } @@ -144,8 +146,8 @@ class SampleRecords { @PostConstruct public void create() throws Exception { - Stream.of("Josh", "Jungryeol", "Nosung", "Hyobeom", - "Soeun", "Seunghue", "Peter", "Jooyong") + Stream.of("Josh", "Jungryeol", "Nosung", "Hyobeom", "Soeun", "Seunghue", "Peter", + "Jooyong") .forEach(name -> reservationRepository.save(new Reservation(name))); reservationRepository.findAll().forEach(System.out::println); } @@ -160,9 +162,9 @@ class Reservation { @Id @GeneratedValue - private Long id; // id + private Long id; // id - private String reservationName; // reservation_name + private String reservationName; // reservation_name public Long getId() { return id; @@ -174,10 +176,8 @@ class Reservation { @Override public String toString() { - return "Reservation{" + - "id=" + id + - ", reservationName='" + reservationName + '\'' + - '}'; + return "Reservation{" + "id=" + id + ", reservationName='" + reservationName + + '\'' + '}'; } Reservation() {// why JPA why??? @@ -188,5 +188,3 @@ class Reservation { this.reservationName = reservationName; } } - - diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceAsyncIntegrationTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceAsyncIntegrationTests.java index ab7435380..fdbeb62b7 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceAsyncIntegrationTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceAsyncIntegrationTests.java @@ -1,14 +1,16 @@ package org.springframework.cloud.sleuth.instrument.web; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; + import java.util.concurrent.atomic.AtomicReference; -import com.jayway.awaitility.Awaitility; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.Tracer; @@ -19,18 +21,19 @@ 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.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; +import com.jayway.awaitility.Awaitility; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = { +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { TraceAsyncIntegrationTests.TraceAsyncITestConfiguration.class }) public class TraceAsyncIntegrationTests { - @Autowired ClassPerformingAsyncLogic classPerformingAsyncLogic; - @Autowired Tracer tracer; + @Autowired + ClassPerformingAsyncLogic classPerformingAsyncLogic; + @Autowired + Tracer tracer; @Test public void should_set_span_on_an_async_annotated_method() { diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterAlwaysSamplerIntegrationTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterAlwaysSamplerIntegrationTests.java index 3e799e838..7bb4abe2c 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterAlwaysSamplerIntegrationTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterAlwaysSamplerIntegrationTests.java @@ -9,7 +9,7 @@ import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.sleuth.NoOpSpanReporter; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.Tracer; @@ -19,7 +19,7 @@ import org.springframework.cloud.sleuth.sampler.AlwaysSampler; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -27,8 +27,8 @@ import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(TraceFilterAlwaysSamplerIntegrationTests.Config.class) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TraceFilterAlwaysSamplerIntegrationTests.Config.class) public class TraceFilterAlwaysSamplerIntegrationTests extends AbstractMvcIntegrationTest { private static Log logger = LogFactory @@ -46,7 +46,8 @@ public class TraceFilterAlwaysSamplerIntegrationTests extends AbstractMvcIntegra } @Test - public void when_not_sampling_header_present_span_is_not_exportable() throws Exception { + public void when_not_sampling_header_present_span_is_not_exportable() + throws Exception { Long expectedTraceId = new Random().nextLong(); MvcResult mvcResult = whenSentPingWithTraceIdAndNotSampling(expectedTraceId); @@ -57,8 +58,7 @@ public class TraceFilterAlwaysSamplerIntegrationTests extends AbstractMvcIntegra @Override protected void configureMockMvcBuilder(DefaultMockMvcBuilder mockMvcBuilder) { mockMvcBuilder.addFilters(new TraceFilter(this.tracer, this.traceKeys, - new NoOpSpanReporter(), this.spanExtractor, - this.httpTraceKeysInjector)); + new NoOpSpanReporter(), this.spanExtractor, this.httpTraceKeysInjector)); } private MvcResult whenSentPingWithTraceIdAndNotSampling(Long traceId) @@ -81,7 +81,8 @@ public class TraceFilterAlwaysSamplerIntegrationTests extends AbstractMvcIntegra .accept(MediaType.TEXT_PLAIN) .header(headerName, Span.idToHex(correlationId)) .header(Span.SPAN_ID_NAME, Span.idToHex(new Random().nextLong())); - request.header(Span.SAMPLED_NAME, sampling ? Span.SPAN_SAMPLED : Span.SPAN_NOT_SAMPLED); + request.header(Span.SAMPLED_NAME, + sampling ? Span.SPAN_SAMPLED : Span.SPAN_NOT_SAMPLED); return this.mockMvc.perform(request).andReturn(); } diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterIntegrationTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterIntegrationTests.java index a47d290d5..2e4685510 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterIntegrationTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterIntegrationTests.java @@ -1,5 +1,10 @@ package org.springframework.cloud.sleuth.instrument.web; +import static org.assertj.core.api.BDDAssertions.then; +import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import java.util.Optional; import java.util.Random; import java.util.concurrent.CompletableFuture; @@ -13,7 +18,7 @@ import org.junit.runner.RunWith; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.ManagementServerProperties; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.SpanReporter; @@ -27,7 +32,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; @@ -35,19 +40,16 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.async.DeferredResult; -import static org.assertj.core.api.BDDAssertions.then; -import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(TraceFilterIntegrationTests.Config.class) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TraceFilterIntegrationTests.Config.class) public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest { private static Log logger = LogFactory.getLog(TraceFilterIntegrationTests.class); - @Autowired TraceFilter traceFilter; - @Autowired ArrayListSpanAccumulator spanAccumulator; + @Autowired + TraceFilter traceFilter; + @Autowired + ArrayListSpanAccumulator spanAccumulator; private static Span span; @@ -61,8 +63,8 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest { public void should_create_and_return_trace_in_HTTP_header() throws Exception { whenSentPingWithoutTracingData(); - Span parentSpan = this.spanAccumulator.getSpans().stream().filter( - span -> span.getSpanId() == TraceFilterIntegrationTests.span.getParents().get(0)) + Span parentSpan = this.spanAccumulator.getSpans().stream().filter(span -> span + .getSpanId() == TraceFilterIntegrationTests.span.getParents().get(0)) .findFirst().get(); then(parentSpan).hasLoggedAnEvent(Span.SERVER_RECV) .hasLoggedAnEvent(Span.SERVER_SEND); @@ -105,20 +107,21 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest { Long expectedTraceId = new Random().nextLong(); MvcResult mvcResult = whenSentFutureWithTraceId(expectedTraceId); - this.mockMvc.perform(asyncDispatch(mvcResult)) - .andExpect(status().isOk()).andReturn(); + this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk()) + .andReturn(); then(this.tracer.getCurrentSpan()).isNull(); then(ExceptionUtils.getLastException()).isNull(); } @Test - public void should_add_a_custom_tag_to_the_span_created_in_controller() throws Exception { + public void should_add_a_custom_tag_to_the_span_created_in_controller() + throws Exception { Long expectedTraceId = new Random().nextLong(); MvcResult mvcResult = whenSentDeferredWithTraceId(expectedTraceId); - this.mockMvc.perform(asyncDispatch(mvcResult)) - .andExpect(status().isOk()).andReturn(); + this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk()) + .andReturn(); Optional taggedSpan = this.spanAccumulator.getSpans().stream() .filter(span -> span.tags().containsKey("tag")).findFirst(); @@ -130,7 +133,8 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest { } @Test - public void should_log_tracing_information_when_exception_was_thrown() throws Exception { + public void should_log_tracing_information_when_exception_was_thrown() + throws Exception { Long expectedTraceId = new Random().nextLong(); whenSentToNonExistentEndpointWithTraceId(expectedTraceId); @@ -140,14 +144,16 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest { } @Test - public void should_assume_that_a_request_without_span_and_with_trace_is_a_root_span() throws Exception { + public void should_assume_that_a_request_without_span_and_with_trace_is_a_root_span() + throws Exception { Long expectedTraceId = new Random().nextLong(); whenSentRequestWithTraceIdAndNoSpanId(expectedTraceId); whenSentRequestWithTraceIdAndNoSpanId(expectedTraceId); - then(this.spanAccumulator.getSpans().stream().filter(span -> - span.getSpanId() == span.getTraceId()).findAny().isPresent()).as("a root span exists").isTrue(); + then(this.spanAccumulator.getSpans().stream() + .filter(span -> span.getSpanId() == span.getTraceId()).findAny() + .isPresent()).as("a root span exists").isTrue(); then(this.tracer.getCurrentSpan()).isNull(); then(ExceptionUtils.getLastException()).isNull(); } @@ -180,8 +186,10 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest { return sendDeferredWithTraceId(Span.TRACE_ID_NAME, passedTraceId); } - private MvcResult whenSentToNonExistentEndpointWithTraceId(Long passedTraceId) throws Exception { - return sendRequestWithTraceId("/exception/nonExistent", Span.TRACE_ID_NAME, passedTraceId, HttpStatus.NOT_FOUND); + private MvcResult whenSentToNonExistentEndpointWithTraceId(Long passedTraceId) + throws Exception { + return sendRequestWithTraceId("/exception/nonExistent", Span.TRACE_ID_NAME, + passedTraceId, HttpStatus.NOT_FOUND); } private MvcResult sendPingWithTraceId(String headerName, Long traceId) @@ -198,8 +206,8 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest { throws Exception { return this.mockMvc .perform(MockMvcRequestBuilders.get(path).accept(MediaType.TEXT_PLAIN) - .header(headerName, Span.idToHex(traceId)) - .header(Span.SPAN_ID_NAME, Span.idToHex(new Random().nextLong()))) + .header(headerName, Span.idToHex(traceId)).header( + Span.SPAN_ID_NAME, Span.idToHex(new Random().nextLong()))) .andReturn(); } @@ -211,14 +219,13 @@ public class TraceFilterIntegrationTests extends AbstractMvcIntegrationTest { .andReturn(); } - private MvcResult sendRequestWithTraceId(String path, String headerName, Long traceId, HttpStatus status) - throws Exception { + private MvcResult sendRequestWithTraceId(String path, String headerName, Long traceId, + HttpStatus status) throws Exception { return this.mockMvc .perform(MockMvcRequestBuilders.get(path).accept(MediaType.TEXT_PLAIN) - .header(headerName, Span.idToHex(traceId)) - .header(Span.SPAN_ID_NAME, Span.idToHex(new Random().nextLong()))) - .andExpect(status().is(status.value())) - .andReturn(); + .header(headerName, Span.idToHex(traceId)).header( + Span.SPAN_ID_NAME, Span.idToHex(new Random().nextLong()))) + .andExpect(status().is(status.value())).andReturn(); } private boolean notSampledHeaderIsPresent(MvcResult mvcResult) { diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterWebIntegrationMultipleFiltersTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterWebIntegrationMultipleFiltersTests.java index e51800a45..af83fa927 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterWebIntegrationMultipleFiltersTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterWebIntegrationMultipleFiltersTests.java @@ -16,8 +16,12 @@ package org.springframework.cloud.sleuth.instrument.web; +import static org.assertj.core.api.BDDAssertions.then; +import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; + import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; + import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; @@ -29,9 +33,9 @@ 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.context.embedded.FilterRegistrationBean; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.boot.test.WebIntegrationTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.Tracer; @@ -42,25 +46,27 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.http.client.ClientHttpResponse; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.RestTemplate; import org.springframework.web.filter.GenericFilterBean; -import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; - /** * @author Marcin Grzejszczak */ -@RunWith(SpringJUnit4ClassRunner.class) -@WebIntegrationTest({ "server.port=0" }) -@SpringApplicationConfiguration(classes = { TraceFilterWebIntegrationMultipleFiltersTests.Config.class }) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { + TraceFilterWebIntegrationMultipleFiltersTests.Config.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public class TraceFilterWebIntegrationMultipleFiltersTests { - @Autowired Tracer tracer; - @Autowired RestTemplate restTemplate; - @Autowired Environment environment; - @Autowired MyFilter myFilter; + @Autowired + Tracer tracer; + @Autowired + RestTemplate restTemplate; + @Autowired + Environment environment; + @Autowired + MyFilter myFilter; @Before @After @@ -86,26 +92,29 @@ public class TraceFilterWebIntegrationMultipleFiltersTests { @Configuration public static class Config { - @Bean Sampler alwaysSampler() { + @Bean + Sampler alwaysSampler() { return new AlwaysSampler(); } - - @Bean RestTemplate restTemplate() { + @Bean + RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { - @Override public void handleError(ClientHttpResponse response) - throws IOException { + @Override + public void handleError(ClientHttpResponse response) throws IOException { } }); return restTemplate; } - @Bean MyFilter myFilter(Tracer tracer) { + @Bean + MyFilter myFilter(Tracer tracer) { return new MyFilter(tracer); } - @Bean FilterRegistrationBean registrationBean(MyFilter myFilter) { + @Bean + FilterRegistrationBean registrationBean(MyFilter myFilter) { FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(myFilter); bean.setOrder(0); @@ -123,7 +132,8 @@ public class TraceFilterWebIntegrationMultipleFiltersTests { this.tracer = tracer; } - @Override public void doFilter(ServletRequest request, ServletResponse response, + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Span currentSpan = tracer.getCurrentSpan(); this.span.set(currentSpan); diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceWebDisabledTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceWebDisabledTests.java index 73919b566..d5f006772 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceWebDisabledTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceWebDisabledTests.java @@ -3,17 +3,16 @@ package org.springframework.cloud.sleuth.instrument.web; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.IntegrationTest; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; /** * @author Marcin Grzejszczak */ -@RunWith(SpringJUnit4ClassRunner.class) -@IntegrationTest({ "spring.sleuth.web.enabled=true", "spring.sleuth.web.client.enabled=false"}) -@SpringApplicationConfiguration(classes = { TraceWebDisabledTests.Config.class }) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { TraceWebDisabledTests.Config.class }, properties = { + "spring.sleuth.web.enabled=true", "spring.sleuth.web.client.enabled=false" }) public class TraceWebDisabledTests { @Test @@ -23,5 +22,6 @@ public class TraceWebDisabledTests { @Configuration @EnableAutoConfiguration - public static class Config {} + public static class Config { + } } diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/client/feign/servererrors/FeignClientServerErrorTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/client/feign/servererrors/FeignClientServerErrorTests.java index 6848ff21d..eb5375814 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/client/feign/servererrors/FeignClientServerErrorTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/client/feign/servererrors/FeignClientServerErrorTests.java @@ -16,6 +16,9 @@ package org.springframework.cloud.sleuth.instrument.web.client.feign.servererrors; +import static org.assertj.core.api.BDDAssertions.then; +import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -27,8 +30,8 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.OutputCapture; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.rule.OutputCapture; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.cloud.netflix.feign.FeignClient; @@ -47,7 +50,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -63,23 +66,24 @@ import com.netflix.loadbalancer.Server; import feign.codec.Decoder; import feign.codec.ErrorDecoder; -import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; - /** * Related to https://github.com/spring-cloud/spring-cloud-sleuth/issues/257 * * @author ryarabori */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = FeignClientServerErrorTests.TestConfiguration.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = FeignClientServerErrorTests.TestConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource(properties = { "spring.application.name=fooservice" }) public class FeignClientServerErrorTests { - @Autowired TestFeignInterface feignInterface; - @Autowired TestFeignWithCustomConfInterface customConfFeignInterface; - @Autowired Listener listener; - @Rule public OutputCapture capture = new OutputCapture(); + @Autowired + TestFeignInterface feignInterface; + @Autowired + TestFeignWithCustomConfInterface customConfFeignInterface; + @Autowired + Listener listener; + @Rule + public OutputCapture capture = new OutputCapture(); @Before public void setup() { @@ -91,19 +95,19 @@ public class FeignClientServerErrorTests { public void shouldCloseSpanOnInternalServerError() throws InterruptedException { try { this.feignInterface.internalError(); - } catch (HystrixRuntimeException e) { + } + catch (HystrixRuntimeException e) { } Awaitility.await().until(() -> { then(this.capture.toString()) .doesNotContain("Tried to close span but it is not the current span"); then(ExceptionUtils.getLastException()).isNull(); + then(new ListOfSpans(this.listener.getEvents())).hasASpanWithTagEqualTo( + Span.SPAN_ERROR_TAG_NAME, + "Request processing failed; nested exception is java.lang.RuntimeException: Internal Error"); then(new ListOfSpans(this.listener.getEvents())) - .hasASpanWithTagEqualTo(Span.SPAN_ERROR_TAG_NAME, - "Request processing failed; nested exception is java.lang.RuntimeException: Internal Error"); - then(new ListOfSpans(this.listener.getEvents())) - .hasASpanWithTagEqualTo(Span.SPAN_ERROR_TAG_NAME, - "Internal Error"); + .hasASpanWithTagEqualTo(Span.SPAN_ERROR_TAG_NAME, "Internal Error"); }); } @@ -111,7 +115,8 @@ public class FeignClientServerErrorTests { public void shouldCloseSpanOnNotFound() throws InterruptedException { try { this.feignInterface.notFound(); - } catch (HystrixRuntimeException e) { + } + catch (HystrixRuntimeException e) { } Awaitility.await().until(() -> { @@ -125,37 +130,45 @@ public class FeignClientServerErrorTests { public void shouldCloseSpanOnOk() throws InterruptedException { try { this.feignInterface.ok(); - } catch (HystrixRuntimeException e) { + } + catch (HystrixRuntimeException e) { } Awaitility.await().until(() -> { - then(this.capture.toString()).doesNotContain("Tried to close span but it is not the current span"); + then(this.capture.toString()) + .doesNotContain("Tried to close span but it is not the current span"); then(ExceptionUtils.getLastException()).isNull(); }); } @Test - public void shouldCloseSpanOnOkWithCustomFeignConfiguration() throws InterruptedException { + public void shouldCloseSpanOnOkWithCustomFeignConfiguration() + throws InterruptedException { try { this.customConfFeignInterface.ok(); - } catch (HystrixRuntimeException e) { + } + catch (HystrixRuntimeException e) { } Awaitility.await().until(() -> { - then(this.capture.toString()).doesNotContain("Tried to close span but it is not the current span"); + then(this.capture.toString()) + .doesNotContain("Tried to close span but it is not the current span"); then(ExceptionUtils.getLastException()).isNull(); }); } @Test - public void shouldCloseSpanOnNotFoundWithCustomFeignConfiguration() throws InterruptedException { + public void shouldCloseSpanOnNotFoundWithCustomFeignConfiguration() + throws InterruptedException { try { this.customConfFeignInterface.notFound(); - } catch (HystrixRuntimeException e) { + } + catch (HystrixRuntimeException e) { } Awaitility.await().until(() -> { - then(this.capture.toString()).doesNotContain("Tried to close span but it is not the current span"); + then(this.capture.toString()) + .doesNotContain("Tried to close span but it is not the current span"); then(ExceptionUtils.getLastException()).isNull(); }); } @@ -163,10 +176,9 @@ public class FeignClientServerErrorTests { @Configuration @EnableAutoConfiguration @EnableFeignClients - @RibbonClients({@RibbonClient(value = "fooservice", - configuration = SimpleRibbonClientConfiguration.class), - @RibbonClient(value = "customConfFooService", - configuration = SimpleRibbonClientConfiguration.class)}) + @RibbonClients({ + @RibbonClient(value = "fooservice", configuration = SimpleRibbonClientConfiguration.class), + @RibbonClient(value = "customConfFooService", configuration = SimpleRibbonClientConfiguration.class) }) public static class TestConfiguration { @Bean @@ -185,7 +197,8 @@ public class FeignClientServerErrorTests { return new RestTemplate(); } - @Bean Sampler testSampler() { + @Bean + Sampler testSampler() { return new AlwaysSampler(); } @@ -214,7 +227,6 @@ public class FeignClientServerErrorTests { ResponseEntity ok(); } - @Configuration public static class CustomFeignClientConfiguration { @Bean diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/zuul/TraceZuulIntegrationTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/zuul/TraceZuulIntegrationTests.java index df168fe7d..b5c06a962 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/zuul/TraceZuulIntegrationTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/zuul/TraceZuulIntegrationTests.java @@ -1,13 +1,12 @@ package org.springframework.cloud.sleuth.instrument.zuul; +import static org.assertj.core.api.BDDAssertions.then; +import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; + import java.io.IOException; import java.lang.invoke.MethodHandles; import java.util.HashMap; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ServerList; -import com.netflix.zuul.context.RequestContext; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.After; @@ -17,8 +16,8 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.IntegrationTest; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.cloud.netflix.ribbon.StaticServerList; @@ -44,29 +43,33 @@ import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.RestTemplate; -import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ServerList; +import com.netflix.zuul.context.RequestContext; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleZuulProxyApplication.class) -@WebAppConfiguration -@IntegrationTest({ "server.port: 0", "zuul.routes.simple: /simple/**" }) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleZuulProxyApplication.class, properties = { + "zuul.routes.simple: /simple/**" }, webEnvironment = WebEnvironment.RANDOM_PORT) @DirtiesContext public class TraceZuulIntegrationTests { - private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); + private static final Log log = LogFactory + .getLog(MethodHandles.lookup().lookupClass()); @Value("${local.server.port}") private int port; - @Autowired Tracer tracer; - @Autowired ArrayListSpanAccumulator spanAccumulator; - @Autowired RestTemplate restTemplate; + @Autowired + Tracer tracer; + @Autowired + ArrayListSpanAccumulator spanAccumulator; + @Autowired + RestTemplate restTemplate; @Before @After @@ -91,10 +94,10 @@ public class TraceZuulIntegrationTests { then(this.tracer.getCurrentSpan()).isNull(); then(new ListOfSpans(this.spanAccumulator.getSpans())) .everyParentIdHasItsCorrespondingSpan() - .clientSideSpanWithNameHasTags("http:/simple/foo", TestTag.tag() - .tag("http.method", "GET") - .tag("http.status_code", "200") - .tag("http.path", "/simple/foo")); + .clientSideSpanWithNameHasTags("http:/simple/foo", + TestTag.tag().tag("http.method", "GET") + .tag("http.status_code", "200") + .tag("http.path", "/simple/foo")); then(ExceptionUtils.getLastException()).isNull(); } @@ -103,8 +106,8 @@ public class TraceZuulIntegrationTests { Span span = this.tracer.createSpan("new_span"); log.info("Started span " + span); ResponseEntity result = this.restTemplate.exchange( - "http://localhost:" + this.port + "/simple/nonExistentUrl", HttpMethod.GET, - new HttpEntity<>((Void) null), String.class); + "http://localhost:" + this.port + "/simple/nonExistentUrl", + HttpMethod.GET, new HttpEntity<>((Void) null), String.class); this.tracer.close(span); @@ -112,10 +115,10 @@ public class TraceZuulIntegrationTests { then(this.tracer.getCurrentSpan()).isNull(); then(new ListOfSpans(this.spanAccumulator.getSpans())) .everyParentIdHasItsCorrespondingSpan() - .clientSideSpanWithNameHasTags("http:/simple/nonExistentUrl", TestTag.tag() - .tag("http.method", "GET") - .tag("http.status_code", "404") - .tag("http.path", "/simple/nonExistentUrl")); + .clientSideSpanWithNameHasTags("http:/simple/nonExistentUrl", + TestTag.tag().tag("http.method", "GET") + .tag("http.status_code", "404") + .tag("http.path", "/simple/nonExistentUrl")); then(ExceptionUtils.getLastException()).isNull(); } @@ -140,7 +143,6 @@ public class TraceZuulIntegrationTests { @RibbonClient(name = "simple", configuration = SimpleRibbonClientConfiguration.class) class SampleZuulProxyApplication { - @RequestMapping("/foo") public String home() { return "Hello world"; @@ -151,35 +153,41 @@ class SampleZuulProxyApplication { throw new RuntimeException(); } - @Bean RouteLocator routeLocator(DiscoveryClient discoveryClient, ZuulProperties zuulProperties) { + @Bean + RouteLocator routeLocator(DiscoveryClient discoveryClient, + ZuulProperties zuulProperties) { return new MyRouteLocator("/", discoveryClient, zuulProperties); } - @Bean SpanReporter testSpanReporter() { + @Bean + SpanReporter testSpanReporter() { return new ArrayListSpanAccumulator(); } - @Bean RestTemplate restTemplate() { + @Bean + RestTemplate restTemplate() { HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setReadTimeout(5000); RestTemplate restTemplate = new RestTemplate(factory); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { - @Override public void handleError(ClientHttpResponse response) - throws IOException { + @Override + public void handleError(ClientHttpResponse response) throws IOException { } }); return restTemplate; } - @Bean Sampler alwaysSampler() { + @Bean + Sampler alwaysSampler() { return new AlwaysSampler(); } } class MyRouteLocator extends DiscoveryClientRouteLocator { - public MyRouteLocator(String servletPath, DiscoveryClient discovery, ZuulProperties properties) { + public MyRouteLocator(String servletPath, DiscoveryClient discovery, + ZuulProperties properties) { super(servletPath, discovery, properties); } } @@ -188,9 +196,11 @@ class MyRouteLocator extends DiscoveryClientRouteLocator { @Configuration class SimpleRibbonClientConfiguration { - @Value("${local.server.port}") private int port; + @Value("${local.server.port}") + private int port; - @Bean public ServerList ribbonServerList() { + @Bean + public ServerList ribbonServerList() { return new StaticServerList<>(new Server("localhost", this.port)); } } diff --git a/spring-cloud-sleuth-dependencies/pom.xml b/spring-cloud-sleuth-dependencies/pom.xml index 8f6a9d4b9..da198227f 100644 --- a/spring-cloud-sleuth-dependencies/pom.xml +++ b/spring-cloud-sleuth-dependencies/pom.xml @@ -5,7 +5,7 @@ spring-cloud-dependencies-parent org.springframework.cloud - 1.2.0.BUILD-SNAPSHOT + 1.3.0.BUILD-SNAPSHOT spring-cloud-sleuth-dependencies diff --git a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-feign/src/test/java/sample/SampleFeignApplicationTests.java b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-feign/src/test/java/sample/SampleFeignApplicationTests.java index 523356062..81c6a31e6 100644 --- a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-feign/src/test/java/sample/SampleFeignApplicationTests.java +++ b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-feign/src/test/java/sample/SampleFeignApplicationTests.java @@ -2,15 +2,13 @@ package sample; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.context.junit4.SpringRunner; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleFeignApplication.class) -@WebAppConfiguration -@TestPropertySource(properties="sample.zipkin.enabled=false") +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleFeignApplication.class) +@TestPropertySource(properties = "sample.zipkin.enabled=false") public class SampleFeignApplicationTests { @Test diff --git a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-messaging/src/test/java/sample/SampleMessagingApplicationTests.java b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-messaging/src/test/java/sample/SampleMessagingApplicationTests.java index 013cec9d2..d09731e89 100644 --- a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-messaging/src/test/java/sample/SampleMessagingApplicationTests.java +++ b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-messaging/src/test/java/sample/SampleMessagingApplicationTests.java @@ -2,15 +2,13 @@ package sample; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.context.junit4.SpringRunner; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleMessagingApplication.class) -@WebAppConfiguration -@TestPropertySource(properties="sample.zipkin.enabled=false") +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleMessagingApplication.class) +@TestPropertySource(properties = "sample.zipkin.enabled=false") public class SampleMessagingApplicationTests { @Test diff --git a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-ribbon/src/test/java/sample/SampleRibbonApplicationTests.java b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-ribbon/src/test/java/sample/SampleRibbonApplicationTests.java index d18c8fcc0..5db49fb40 100644 --- a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-ribbon/src/test/java/sample/SampleRibbonApplicationTests.java +++ b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-ribbon/src/test/java/sample/SampleRibbonApplicationTests.java @@ -2,15 +2,15 @@ package sample; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleRibbonApplication.class) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleRibbonApplication.class) @WebAppConfiguration -@TestPropertySource(properties="sample.zipkin.enabled=false") +@TestPropertySource(properties = "sample.zipkin.enabled=false") public class SampleRibbonApplicationTests { @Test diff --git a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-stream/src/test/java/sample/SampleSleuthApplicationTests.java b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-stream/src/test/java/sample/SampleSleuthApplicationTests.java index 0b9c935b1..fde9576c4 100644 --- a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-stream/src/test/java/sample/SampleSleuthApplicationTests.java +++ b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-stream/src/test/java/sample/SampleSleuthApplicationTests.java @@ -2,12 +2,12 @@ package sample; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleSleuthApplication.class) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleSleuthApplication.class) @WebAppConfiguration public class SampleSleuthApplicationTests { diff --git a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-websocket/src/test/java/sample/SampleWebsocketApplicationTests.java b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-websocket/src/test/java/sample/SampleWebsocketApplicationTests.java index 53d68bfe2..7bb75d121 100644 --- a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-websocket/src/test/java/sample/SampleWebsocketApplicationTests.java +++ b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-websocket/src/test/java/sample/SampleWebsocketApplicationTests.java @@ -2,15 +2,15 @@ package sample; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleWebsocketApplication.class) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleWebsocketApplication.class) @WebAppConfiguration -@TestPropertySource(properties="sample.zipkin.enabled=false") +@TestPropertySource(properties = "sample.zipkin.enabled=false") public class SampleWebsocketApplicationTests { @Test diff --git a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-zipkin-stream/src/test/java/example/ZipkinServerApplicationTests.java b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-zipkin-stream/src/test/java/example/ZipkinServerApplicationTests.java index c87052e13..d68df5973 100644 --- a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-zipkin-stream/src/test/java/example/ZipkinServerApplicationTests.java +++ b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-zipkin-stream/src/test/java/example/ZipkinServerApplicationTests.java @@ -1,19 +1,20 @@ package example; +import static org.junit.Assert.assertEquals; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.IntegrationTest; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; + import zipkin.storage.StorageComponent; -import static org.junit.Assert.assertEquals; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = ZipkinStreamServerApplication.class) -@IntegrationTest({ "server.port=0", "spring.datasource.initialize=true" }) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ZipkinStreamServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, properties = { + "spring.datasource.initialize=true" }) @ActiveProfiles("test") public class ZipkinServerApplicationTests { diff --git a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-zipkin/src/test/java/sample/SampleSleuthApplicationTests.java b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-zipkin/src/test/java/sample/SampleSleuthApplicationTests.java index e7efa95d8..7f861044c 100644 --- a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-zipkin/src/test/java/sample/SampleSleuthApplicationTests.java +++ b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-zipkin/src/test/java/sample/SampleSleuthApplicationTests.java @@ -2,15 +2,15 @@ package sample; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleZipkinApplication.class) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleZipkinApplication.class) @WebAppConfiguration -@TestPropertySource(properties="sample.zipkin.enabled=false") +@TestPropertySource(properties = "sample.zipkin.enabled=false") public class SampleSleuthApplicationTests { @Test diff --git a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample/src/test/java/sample/SampleSleuthApplicationTests.java b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample/src/test/java/sample/SampleSleuthApplicationTests.java index 0b9c935b1..3ede06782 100644 --- a/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample/src/test/java/sample/SampleSleuthApplicationTests.java +++ b/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample/src/test/java/sample/SampleSleuthApplicationTests.java @@ -2,13 +2,11 @@ package sample; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; -@RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = SampleSleuthApplication.class) -@WebAppConfiguration +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SampleSleuthApplication.class) public class SampleSleuthApplicationTests { @Test diff --git a/spring-cloud-sleuth-stream/src/test/java/org/springframework/cloud/sleuth/stream/StreamEnvironmentPostProcessorTests.java b/spring-cloud-sleuth-stream/src/test/java/org/springframework/cloud/sleuth/stream/StreamEnvironmentPostProcessorTests.java index c90c78591..1df742b50 100644 --- a/spring-cloud-sleuth-stream/src/test/java/org/springframework/cloud/sleuth/stream/StreamEnvironmentPostProcessorTests.java +++ b/spring-cloud-sleuth-stream/src/test/java/org/springframework/cloud/sleuth/stream/StreamEnvironmentPostProcessorTests.java @@ -16,19 +16,19 @@ package org.springframework.cloud.sleuth.stream; +import static org.assertj.core.api.Assertions.assertThat; + import java.util.Collection; import java.util.Map; import java.util.stream.Collectors; import org.junit.Test; import org.springframework.boot.SpringApplication; -import org.springframework.boot.test.EnvironmentTestUtils; +import org.springframework.boot.test.util.EnvironmentTestUtils; import org.springframework.cloud.sleuth.Span; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; -import static org.assertj.core.api.Assertions.assertThat; - /** * @author Dave Syer * @@ -41,17 +41,20 @@ public class StreamEnvironmentPostProcessorTests { @Test public void should_append_tracing_headers() { postProcess(); - assertThat(this.environment.getProperty("spring.cloud.stream.test.binder.headers[0]")) - .isEqualTo(Span.SPAN_ID_NAME); + assertThat(this.environment + .getProperty("spring.cloud.stream.test.binder.headers[0]")) + .isEqualTo(Span.SPAN_ID_NAME); } @Test public void should_append_tracing_headers_to_existing_ones() { - EnvironmentTestUtils.addEnvironment(this.environment, "spring.cloud.stream.test.binder.headers[0]=X-Custom", + EnvironmentTestUtils.addEnvironment(this.environment, + "spring.cloud.stream.test.binder.headers[0]=X-Custom", "spring.cloud.stream.test.binder.headers[1]=X-Mine"); postProcess(); - assertThat(this.environment.getProperty("spring.cloud.stream.test.binder.headers[2]")) - .isEqualTo(Span.SPAN_ID_NAME); + assertThat(this.environment + .getProperty("spring.cloud.stream.test.binder.headers[2]")) + .isEqualTo(Span.SPAN_ID_NAME); } @Test @@ -63,11 +66,14 @@ public class StreamEnvironmentPostProcessorTests { Collection headerValues = defaultPropertiesSource().values(); Collection traceIds = headerValues.stream() - .filter(input -> input.contains(Span.TRACE_ID_NAME)).collect(Collectors.toList()); + .filter(input -> input.contains(Span.TRACE_ID_NAME)) + .collect(Collectors.toList()); assertThat(traceIds).hasSize(1); assertThat(defaultPropertiesSource().keySet().stream() - .filter(input -> input.startsWith("spring.cloud.stream.test.binder.headers")) - .collect(Collectors.toList())).hasSize(StreamEnvironmentPostProcessor.headers.length); + .filter(input -> input + .startsWith("spring.cloud.stream.test.binder.headers")) + .collect(Collectors.toList())) + .hasSize(StreamEnvironmentPostProcessor.headers.length); } private void postProcess() { @@ -76,7 +82,8 @@ public class StreamEnvironmentPostProcessorTests { } private Map defaultPropertiesSource() { - return (Map) this.environment.getPropertySources().get("defaultProperties").getSource(); + return (Map) this.environment.getPropertySources() + .get("defaultProperties").getSource(); } } diff --git a/spring-cloud-sleuth-zipkin-stream/src/test/java/org/springframework/cloud/sleuth/zipkin/stream/ZipkinServerApplicationTests.java b/spring-cloud-sleuth-zipkin-stream/src/test/java/org/springframework/cloud/sleuth/zipkin/stream/ZipkinServerApplicationTests.java index 90b2f6a99..ddbe38bfb 100644 --- a/spring-cloud-sleuth-zipkin-stream/src/test/java/org/springframework/cloud/sleuth/zipkin/stream/ZipkinServerApplicationTests.java +++ b/spring-cloud-sleuth-zipkin-stream/src/test/java/org/springframework/cloud/sleuth/zipkin/stream/ZipkinServerApplicationTests.java @@ -7,8 +7,8 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.test.IntegrationTest; -import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.sleuth.zipkin.stream.ZipkinServerApplicationTests.ZipkinStreamServerApplication; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -16,8 +16,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import zipkin.storage.StorageComponent; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = ZipkinStreamServerApplication.class) -@IntegrationTest({ "server.port=0", "spring.datasource.initialize=true" }) +@SpringBootTest(classes = ZipkinStreamServerApplication.class, properties = { + "spring.datasource.initialize=true" }, webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") public class ZipkinServerApplicationTests { diff --git a/spring-cloud-sleuth-zipkin/src/test/java/org/springframework/cloud/sleuth/zipkin/ZipkinSpanListenerTests.java b/spring-cloud-sleuth-zipkin/src/test/java/org/springframework/cloud/sleuth/zipkin/ZipkinSpanListenerTests.java index 239754a49..8c6a62d76 100644 --- a/spring-cloud-sleuth-zipkin/src/test/java/org/springframework/cloud/sleuth/zipkin/ZipkinSpanListenerTests.java +++ b/spring-cloud-sleuth-zipkin/src/test/java/org/springframework/cloud/sleuth/zipkin/ZipkinSpanListenerTests.java @@ -16,16 +16,19 @@ package org.springframework.cloud.sleuth.zipkin; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + import java.util.ArrayList; -import java.util.Collections; import java.util.List; + import javax.annotation.PostConstruct; 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.SpringApplicationConfiguration; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.sleuth.Sampler; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.SpanReporter; @@ -35,25 +38,26 @@ import org.springframework.cloud.sleuth.zipkin.ZipkinSpanListenerTests.TestConfi import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import zipkin.Constants; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; - /** * @author Dave Syer * */ -@SpringApplicationConfiguration(classes = TestConfiguration.class) -@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = TestConfiguration.class) +@RunWith(SpringRunner.class) public class ZipkinSpanListenerTests { - @Autowired Tracer tracer; - @Autowired ApplicationContext application; - @Autowired TestConfiguration test; - @Autowired ZipkinSpanListener spanReporter; + @Autowired + Tracer tracer; + @Autowired + ApplicationContext application; + @Autowired + TestConfiguration test; + @Autowired + ZipkinSpanListener spanReporter; @PostConstruct public void init() { @@ -72,10 +76,8 @@ public class ZipkinSpanListenerTests { zipkin.Span result = this.spanReporter.convert(span); - assertThat(result.timestamp) - .isEqualTo(span.getBegin() * 1000); - assertThat(result.duration) - .isEqualTo(span.getAccumulatedMicros()); + assertThat(result.timestamp).isEqualTo(span.getBegin() * 1000); + assertThat(result.duration).isEqualTo(span.getAccumulatedMicros()); assertThat(result.annotations.get(0).timestamp) .isGreaterThanOrEqualTo(start * 1000) .isLessThanOrEqualTo(System.currentTimeMillis() * 1000); @@ -93,14 +95,14 @@ public class ZipkinSpanListenerTests { zipkin.Span result = this.spanReporter.convert(span); - assertThat(result.timestamp) - .isEqualTo(span.getBegin() * 1000); - long clientSendTimestamp = span.logs().stream().filter(log -> Span.CLIENT_SEND.equals(log.getEvent())) - .findFirst().get().getTimestamp(); - long clientRecvTimestamp = span.logs().stream().filter(log -> Span.CLIENT_RECV.equals(log.getEvent())) - .findFirst().get().getTimestamp(); - assertThat(result.duration) - .isNotEqualTo(span.getAccumulatedMicros()) + assertThat(result.timestamp).isEqualTo(span.getBegin() * 1000); + long clientSendTimestamp = span.logs().stream() + .filter(log -> Span.CLIENT_SEND.equals(log.getEvent())).findFirst().get() + .getTimestamp(); + long clientRecvTimestamp = span.logs().stream() + .filter(log -> Span.CLIENT_RECV.equals(log.getEvent())).findFirst().get() + .getTimestamp(); + assertThat(result.duration).isNotEqualTo(span.getAccumulatedMicros()) .isEqualTo((clientRecvTimestamp - clientSendTimestamp) * 1000); } @@ -110,27 +112,23 @@ public class ZipkinSpanListenerTests { Span span = Span.builder().traceId(1L).name("http:api").build(); zipkin.Span result = this.spanReporter.convert(span); - assertThat(result.timestamp) - .isGreaterThan(0); // sanity check it did start - assertThat(result.duration) - .isNull(); + assertThat(result.timestamp).isGreaterThan(0); // sanity check it did start + assertThat(result.duration).isNull(); } /** - * In the RPC span model, the client owns the timestamp and duration of the span. If we - * were propagated an id, we can assume that we shouldn't report timestamp or duration, - * rather let the client do that. Worst case we were propagated an unreported ID and - * Zipkin backfills timestamp and duration. + * In the RPC span model, the client owns the timestamp and duration of the span. If + * we were propagated an id, we can assume that we shouldn't report timestamp or + * duration, rather let the client do that. Worst case we were propagated an + * unreported ID and Zipkin backfills timestamp and duration. */ @Test public void doesntSetTimestampOrDurationWhenRemote() { this.parent.stop(); zipkin.Span result = this.spanReporter.convert(this.parent); - assertThat(result.timestamp) - .isNull(); - assertThat(result.duration) - .isNull(); + assertThat(result.timestamp).isNull(); + assertThat(result.duration).isNull(); } /** Sleuth host corresponds to annotation/binaryAnnotation.host in zipkin. */ @@ -150,14 +148,13 @@ public class ZipkinSpanListenerTests { /** zipkin's Endpoint.serviceName should never be null. */ @Test public void localEndpointIncludesServiceName() { - assertThat(this.spanReporter.endpointLocator.local().serviceName) - .isNotEmpty(); + assertThat(this.spanReporter.endpointLocator.local().serviceName).isNotEmpty(); } /** - * In zipkin, the service context is attached to annotations. Sleuth spans - * that have no annotations will get an "lc" one, which allows them to be - * queryable in zipkin by service name. + * In zipkin, the service context is attached to annotations. Sleuth spans that have + * no annotations will get an "lc" one, which allows them to be queryable in zipkin by + * service name. */ @Test public void spanWithoutAnnotationsLogsComponent() { @@ -165,7 +162,9 @@ public class ZipkinSpanListenerTests { this.tracer.close(context); assertEquals(1, this.test.zipkinSpans.size()); assertThat(this.test.zipkinSpans.get(0).binaryAnnotations.get(0).value) - .isEqualTo("unknown".getBytes()); // TODO: "unknown" bc process id, documented as not nullable, is null. + .isEqualTo("unknown".getBytes()); // TODO: "unknown" bc process id, + // documented as not nullable, is + // null. } @Test @@ -198,8 +197,7 @@ public class ZipkinSpanListenerTests { zipkin.Span result = this.spanReporter.convert(this.parent); - assertThat(result.binaryAnnotations) - .extracting(input -> input.key) + assertThat(result.binaryAnnotations).extracting(input -> input.key) .contains(Constants.LOCAL_COMPONENT); } @@ -210,14 +208,14 @@ public class ZipkinSpanListenerTests { zipkin.Span result = this.spanReporter.convert(this.parent); - assertThat(result.binaryAnnotations) - .filteredOn("key", Constants.SERVER_ADDR) + assertThat(result.binaryAnnotations).filteredOn("key", Constants.SERVER_ADDR) .isNotEmpty(); } @Test public void converts128BitTraceId() { - Span span = Span.builder().traceIdHigh(1L).traceId(2L).spanId(3L).name("foo").build(); + Span span = Span.builder().traceIdHigh(1L).traceId(2L).spanId(3L).name("foo") + .build(); zipkin.Span result = this.spanReporter.convert(span); @@ -233,8 +231,7 @@ public class ZipkinSpanListenerTests { zipkin.Span result = this.spanReporter.convert(this.parent); - assertThat(result.binaryAnnotations) - .filteredOn("key", Constants.SERVER_ADDR) + assertThat(result.binaryAnnotations).filteredOn("key", Constants.SERVER_ADDR) .extracting(input -> input.endpoint.serviceName) .containsOnly("fooservice"); }