pull/11528/merge
Andy Wilkinson 7 years ago
parent 8941dc746e
commit 927003e0b7

@ -28,6 +28,7 @@ import org.springframework.cache.Cache;
* @author Stephane Nicoll * @author Stephane Nicoll
* @since 2.0.0 * @since 2.0.0
*/ */
@FunctionalInterface
public interface CacheMeterBinderProvider<C extends Cache> { public interface CacheMeterBinderProvider<C extends Cache> {
/** /**

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -24,6 +24,7 @@ import org.neo4j.ogm.session.SessionFactory;
import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.actuate.health.HealthIndicator;
/** /**
@ -59,8 +60,8 @@ public class Neo4jHealthIndicator extends AbstractHealthIndicator {
} }
/** /**
* Provide health details using the specified {@link Session} and * Provide health details using the specified {@link Session} and {@link Builder
* {@link Health.Builder Builder}. * Builder}.
* @param session the session to use to execute a cypher statement * @param session the session to use to execute a cypher statement
* @param builder the builder to add details to * @param builder the builder to add details to
* @throws Exception if getting health details failed * @throws Exception if getting health details failed

@ -93,11 +93,9 @@ public class MetricsEndpointTests {
this.registry.counter("cache", "host", "1", "region", "east", "result", "miss"); this.registry.counter("cache", "host", "1", "region", "east", "result", "miss");
MetricsEndpoint.MetricResponse response = this.endpoint.metric("cache", MetricsEndpoint.MetricResponse response = this.endpoint.metric("cache",
Collections.singletonList("host:1")); Collections.singletonList("host:1"));
assertThat(response.getAvailableTags() assertThat(response.getAvailableTags().stream()
.stream() .filter((t) -> t.getTag().equals("region"))
.filter(t -> t.getTag().equals("region")) .flatMap((t) -> t.getValues().stream())).containsExactly("east");
.flatMap(t -> t.getValues().stream()))
.containsExactly("east");
} }
@Test @Test

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -84,7 +84,7 @@ public class MongoClientFactory {
String host = this.properties.getHost() == null ? "localhost" String host = this.properties.getHost() == null ? "localhost"
: this.properties.getHost(); : this.properties.getHost();
return new MongoClient(Collections.singletonList(new ServerAddress(host, port)), return new MongoClient(Collections.singletonList(new ServerAddress(host, port)),
Collections.emptyList(), options); options);
} }
private MongoClient createNetworkMongoClient(MongoClientOptions options) { private MongoClient createNetworkMongoClient(MongoClientOptions options) {
@ -96,12 +96,13 @@ public class MongoClientFactory {
if (options == null) { if (options == null) {
options = MongoClientOptions.builder().build(); options = MongoClientOptions.builder().build();
} }
List<MongoCredential> credentials = getCredentials(properties); MongoCredential credentials = getCredentials(properties);
String host = getValue(properties.getHost(), "localhost"); String host = getValue(properties.getHost(), "localhost");
int port = getValue(properties.getPort(), MongoProperties.DEFAULT_PORT); int port = getValue(properties.getPort(), MongoProperties.DEFAULT_PORT);
List<ServerAddress> seeds = Collections List<ServerAddress> seeds = Collections
.singletonList(new ServerAddress(host, port)); .singletonList(new ServerAddress(host, port));
return new MongoClient(seeds, credentials, options); return credentials == null ? new MongoClient(seeds, options)
: new MongoClient(seeds, credentials, options);
} }
return createMongoClient(MongoProperties.DEFAULT_URI, options); return createMongoClient(MongoProperties.DEFAULT_URI, options);
} }
@ -118,16 +119,15 @@ public class MongoClientFactory {
return this.properties.getHost() != null || this.properties.getPort() != null; return this.properties.getHost() != null || this.properties.getPort() != null;
} }
private List<MongoCredential> getCredentials(MongoProperties properties) { private MongoCredential getCredentials(MongoProperties properties) {
if (!hasCustomCredentials()) { if (!hasCustomCredentials()) {
return Collections.emptyList(); return null;
} }
String username = properties.getUsername(); String username = properties.getUsername();
String database = getValue(properties.getAuthenticationDatabase(), String database = getValue(properties.getAuthenticationDatabase(),
properties.getMongoClientDatabase()); properties.getMongoClientDatabase());
char[] password = properties.getPassword(); char[] password = properties.getPassword();
return Collections.singletonList( return MongoCredential.createCredential(username, database, password);
MongoCredential.createCredential(username, database, password));
} }
private boolean hasCustomCredentials() { private boolean hasCustomCredentials() {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,7 +16,6 @@
package org.springframework.boot.autoconfigure.mongo; package org.springframework.boot.autoconfigure.mongo;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -120,13 +119,12 @@ public class ReactiveMongoClientFactory {
} }
private void applyCredentials(Builder builder) { private void applyCredentials(Builder builder) {
List<MongoCredential> credentials = new ArrayList<>();
String database = this.properties.getAuthenticationDatabase() == null String database = this.properties.getAuthenticationDatabase() == null
? this.properties.getMongoClientDatabase() ? this.properties.getMongoClientDatabase()
: this.properties.getAuthenticationDatabase(); : this.properties.getAuthenticationDatabase();
credentials.add(MongoCredential.createCredential(this.properties.getUsername(), builder.credential((MongoCredential.createCredential(
database, this.properties.getPassword())); this.properties.getUsername(), database, this.properties.getPassword())));
builder.credentialList(credentials);
} }
private <T> T getOrDefault(T value, T defaultValue) { private <T> T getOrDefault(T value, T defaultValue) {
@ -144,7 +142,7 @@ public class ReactiveMongoClientFactory {
builder.clusterSettings(getClusterSettings(connection)); builder.clusterSettings(getClusterSettings(connection));
builder.connectionPoolSettings(getConnectionPoolSettings(connection)); builder.connectionPoolSettings(getConnectionPoolSettings(connection));
builder.serverSettings(getServerSettings(connection)); builder.serverSettings(getServerSettings(connection));
builder.credentialList(connection.getCredentialList()); builder.credential(connection.getCredential());
builder.sslSettings(getSslSettings(connection)); builder.sslSettings(getSslSettings(connection));
builder.socketSettings(getSocketSettings(connection)); builder.socketSettings(getSocketSettings(connection));
if (connection.getReadPreference() != null) { if (connection.getReadPreference() != null) {

@ -106,7 +106,7 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration {
this.physicalNamingStrategy = physicalNamingStrategy.getIfAvailable(); this.physicalNamingStrategy = physicalNamingStrategy.getIfAvailable();
this.implicitNamingStrategy = implicitNamingStrategy.getIfAvailable(); this.implicitNamingStrategy = implicitNamingStrategy.getIfAvailable();
this.hibernatePropertiesCustomizers = hibernatePropertiesCustomizers this.hibernatePropertiesCustomizers = hibernatePropertiesCustomizers
.getIfAvailable(() -> Collections.EMPTY_LIST); .getIfAvailable(() -> Collections.emptyList());
} }
@Override @Override
@ -122,7 +122,8 @@ class HibernateJpaConfiguration extends JpaBaseConfiguration {
.getHibernateProperties(new HibernateSettings().ddlAuto(defaultDdlMode) .getHibernateProperties(new HibernateSettings().ddlAuto(defaultDdlMode)
.implicitNamingStrategy(this.implicitNamingStrategy) .implicitNamingStrategy(this.implicitNamingStrategy)
.physicalNamingStrategy(this.physicalNamingStrategy) .physicalNamingStrategy(this.physicalNamingStrategy)
.hibernatePropertiesCustomizers(this.hibernatePropertiesCustomizers))); .hibernatePropertiesCustomizers(
this.hibernatePropertiesCustomizers)));
} }
@Override @Override

@ -26,12 +26,13 @@ import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.GenericContainer;
/** /**
* {@link TestRule} for working with an optional Docker environment. Spins up a {@link GenericContainer} * {@link TestRule} for working with an optional Docker environment. Spins up a
* if a valid docker environment is found. * {@link GenericContainer} if a valid docker environment is found.
* *
* @param <T> the type of the container
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class DockerTestContainer<T extends GenericContainer> implements TestRule { public class DockerTestContainer<T extends GenericContainer<?>> implements TestRule {
private Supplier<T> containerSupplier; private Supplier<T> containerSupplier;
@ -60,4 +61,3 @@ public class DockerTestContainer<T extends GenericContainer> implements TestRule
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,7 +18,6 @@ package org.springframework.boot.autoconfigure.data.cassandra;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session; import com.datastax.driver.core.Session;
@ -29,7 +28,6 @@ import org.junit.Test;
import org.rnorth.ducttape.TimeoutException; import org.rnorth.ducttape.TimeoutException;
import org.rnorth.ducttape.unreliables.Unreliables; import org.rnorth.ducttape.unreliables.Unreliables;
import org.testcontainers.containers.FixedHostPortGenericContainer; import org.testcontainers.containers.FixedHostPortGenericContainer;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.HostPortWaitStrategy; import org.testcontainers.containers.wait.HostPortWaitStrategy;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
@ -52,11 +50,11 @@ import static org.assertj.core.api.Assertions.assertThat;
public class CassandraDataAutoConfigurationIntegrationTests { public class CassandraDataAutoConfigurationIntegrationTests {
@ClassRule @ClassRule
public static DockerTestContainer<GenericContainer> genericContainer = new DockerTestContainer<>((Supplier<GenericContainer>) () -> new FixedHostPortGenericContainer("cassandra:latest") public static DockerTestContainer<FixedHostPortGenericContainer<?>> cassandra = new DockerTestContainer<>(
() -> new FixedHostPortGenericContainer<>("cassandra:latest")
.withFixedExposedPort(9042, 9042) .withFixedExposedPort(9042, 9042)
.waitingFor(new ConnectionVerifyingWaitStrategy())); .waitingFor(new ConnectionVerifyingWaitStrategy()));
private AnnotationConfigApplicationContext context; private AnnotationConfigApplicationContext context;
@After @After
@ -113,8 +111,8 @@ public class CassandraDataAutoConfigurationIntegrationTests {
super.waitUntilReady(); super.waitUntilReady();
Cluster cluster = Cluster.builder().addContactPoint("localhost").build(); Cluster cluster = Cluster.builder().addContactPoint("localhost").build();
try { try {
Unreliables.retryUntilTrue((int) startupTimeout.getSeconds(), TimeUnit.SECONDS, Unreliables.retryUntilTrue((int) this.startupTimeout.getSeconds(),
checkConnection(cluster)); TimeUnit.SECONDS, checkConnection(cluster));
} }
catch (TimeoutException e) { catch (TimeoutException e) {
throw new IllegalStateException(); throw new IllegalStateException();

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -42,8 +42,8 @@ import static org.assertj.core.api.Assertions.assertThat;
public class RedisRepositoriesAutoConfigurationTests { public class RedisRepositoriesAutoConfigurationTests {
@ClassRule @ClassRule
public static DockerTestContainer<FixedHostPortGenericContainer> genericContainer = new DockerTestContainer<>(() -> public static DockerTestContainer<FixedHostPortGenericContainer<?>> redis = new DockerTestContainer<>(
new FixedHostPortGenericContainer("redis:latest") () -> new FixedHostPortGenericContainer<>("redis:latest")
.withFixedExposedPort(6379, 6379)); .withFixedExposedPort(6379, 6379));
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -47,7 +47,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests {
@Test @Test
public void defaultConfiguration() { public void defaultConfiguration() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
assertThat(context.getBean(FreeMarkerViewResolver.class)).isNotNull(); assertThat(context.getBean(FreeMarkerViewResolver.class)).isNotNull();
assertThat(context.getBean(FreeMarkerConfigurer.class)).isNotNull(); assertThat(context.getBean(FreeMarkerConfigurer.class)).isNotNull();
assertThat(context.getBean(FreeMarkerConfig.class)).isNotNull(); assertThat(context.getBean(FreeMarkerConfig.class)).isNotNull();
@ -58,7 +58,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests {
@Test @Test
public void defaultViewResolution() { public void defaultViewResolution() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
MockServerWebExchange exchange = render(context, "home"); MockServerWebExchange exchange = render(context, "home");
String result = exchange.getResponse().getBodyAsString().block(); String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("home"); assertThat(result).contains("home");
@ -70,7 +70,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests {
@Test @Test
public void customPrefix() { public void customPrefix() {
this.contextRunner.withPropertyValues("spring.freemarker.prefix:prefix/") this.contextRunner.withPropertyValues("spring.freemarker.prefix:prefix/")
.run(context -> { .run((context) -> {
MockServerWebExchange exchange = render(context, "prefixed"); MockServerWebExchange exchange = render(context, "prefixed");
String result = exchange.getResponse().getBodyAsString().block(); String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("prefixed"); assertThat(result).contains("prefixed");
@ -80,7 +80,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests {
@Test @Test
public void customSuffix() { public void customSuffix() {
this.contextRunner.withPropertyValues("spring.freemarker.suffix:.freemarker") this.contextRunner.withPropertyValues("spring.freemarker.suffix:.freemarker")
.run(context -> { .run((context) -> {
MockServerWebExchange exchange = render(context, "suffixed"); MockServerWebExchange exchange = render(context, "suffixed");
String result = exchange.getResponse().getBodyAsString().block(); String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("suffixed"); assertThat(result).contains("suffixed");
@ -92,7 +92,7 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests {
this.contextRunner this.contextRunner
.withPropertyValues( .withPropertyValues(
"spring.freemarker.templateLoaderPath:classpath:/custom-templates/") "spring.freemarker.templateLoaderPath:classpath:/custom-templates/")
.run(context -> { .run((context) -> {
MockServerWebExchange exchange = render(context, "custom"); MockServerWebExchange exchange = render(context, "custom");
String result = exchange.getResponse().getBodyAsString().block(); String result = exchange.getResponse().getBodyAsString().block();
assertThat(result).contains("custom"); assertThat(result).contains("custom");
@ -104,14 +104,14 @@ public class FreeMarkerAutoConfigurationReactiveIntegrationTests {
public void customFreeMarkerSettings() { public void customFreeMarkerSettings() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope") .withPropertyValues("spring.freemarker.settings.boolean_format:yup,nope")
.run(context -> assertThat(context.getBean(FreeMarkerConfigurer.class) .run((context) -> assertThat(context.getBean(FreeMarkerConfigurer.class)
.getConfiguration().getSetting("boolean_format")) .getConfiguration().getSetting("boolean_format"))
.isEqualTo("yup,nope")); .isEqualTo("yup,nope"));
} }
@Test @Test
public void renderTemplate() { public void renderTemplate() {
this.contextRunner.withPropertyValues().run(context -> { this.contextRunner.withPropertyValues().run((context) -> {
FreeMarkerConfigurer freemarker = context.getBean(FreeMarkerConfigurer.class); FreeMarkerConfigurer freemarker = context.getBean(FreeMarkerConfigurer.class);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
freemarker.getConfiguration().getTemplate("message.ftl").process(this, freemarker.getConfiguration().getTemplate("message.ftl").process(this,

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -45,7 +45,7 @@ public class FreeMarkerAutoConfigurationTests {
@Test @Test
public void renderNonWebAppTemplate() { public void renderNonWebAppTemplate() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
freemarker.template.Configuration freemarker = context freemarker.template.Configuration freemarker = context
.getBean(freemarker.template.Configuration.class); .getBean(freemarker.template.Configuration.class);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
@ -63,7 +63,7 @@ public class FreeMarkerAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues("spring.freemarker.templateLoaderPath:" .withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/does-not-exist/,classpath:/also-does-not-exist") + "classpath:/does-not-exist/,classpath:/also-does-not-exist")
.run(context -> this.output .run((context) -> this.output
.expect(containsString("Cannot find template location"))); .expect(containsString("Cannot find template location")));
} }
@ -71,7 +71,7 @@ public class FreeMarkerAutoConfigurationTests {
public void emptyTemplateLocation() { public void emptyTemplateLocation() {
new File("target/test-classes/templates/empty-directory").mkdir(); new File("target/test-classes/templates/empty-directory").mkdir();
this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:" this.contextRunner.withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/templates/empty-directory/").run(context -> { + "classpath:/templates/empty-directory/").run((context) -> {
}); });
} }
@ -81,7 +81,7 @@ public class FreeMarkerAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues("spring.freemarker.templateLoaderPath:" .withPropertyValues("spring.freemarker.templateLoaderPath:"
+ "classpath:/does-not-exist/,classpath:/templates/empty-directory/") + "classpath:/does-not-exist/,classpath:/templates/empty-directory/")
.run(context -> { .run((context) -> {
}); });
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -82,7 +82,7 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void registersJodaModuleAutomatically() { public void registersJodaModuleAutomatically() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
ObjectMapper objectMapper = context.getBean(ObjectMapper.class); ObjectMapper objectMapper = context.getBean(ObjectMapper.class);
assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue(); assertThat(objectMapper.canSerialize(LocalDateTime.class)).isTrue();
}); });
@ -93,7 +93,7 @@ public class JacksonAutoConfigurationTests {
this.contextRunner.withUserConfiguration(DoubleModulesConfig.class) this.contextRunner.withUserConfiguration(DoubleModulesConfig.class)
.withConfiguration(AutoConfigurations .withConfiguration(AutoConfigurations
.of(HttpMessageConvertersAutoConfiguration.class)) .of(HttpMessageConvertersAutoConfiguration.class))
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.writeValueAsString(new Foo())) assertThat(mapper.writeValueAsString(new Foo()))
.isEqualTo("{\"foo\":\"bar\"}"); .isEqualTo("{\"foo\":\"bar\"}");
@ -108,7 +108,7 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void noCustomDateFormat() { public void noCustomDateFormat() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getDateFormat()).isInstanceOf(StdDateFormat.class); assertThat(mapper.getDateFormat()).isInstanceOf(StdDateFormat.class);
}); });
@ -117,7 +117,7 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void customDateFormat() { public void customDateFormat() {
this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss") this.contextRunner.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
DateFormat dateFormat = mapper.getDateFormat(); DateFormat dateFormat = mapper.getDateFormat();
assertThat(dateFormat).isInstanceOf(SimpleDateFormat.class); assertThat(dateFormat).isInstanceOf(SimpleDateFormat.class);
@ -131,7 +131,7 @@ public class JacksonAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss", .withPropertyValues("spring.jackson.date-format:yyyyMMddHHmmss",
"spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss") "spring.jackson.joda-date-time-format:yyyy-MM-dd HH:mm:ss")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTime dateTime = new DateTime(1988, 6, 25, 20, 30,
DateTimeZone.UTC); DateTimeZone.UTC);
@ -148,7 +148,7 @@ public class JacksonAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues( .withPropertyValues(
"spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat") "spring.jackson.date-format:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationTests.MyDateFormat")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class);
}); });
@ -156,7 +156,7 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void noCustomPropertyNamingStrategy() { public void noCustomPropertyNamingStrategy() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getPropertyNamingStrategy()).isNull(); assertThat(mapper.getPropertyNamingStrategy()).isNull();
}); });
@ -166,7 +166,7 @@ public class JacksonAutoConfigurationTests {
public void customPropertyNamingStrategyField() { public void customPropertyNamingStrategyField() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.jackson.property-naming-strategy:SNAKE_CASE") .withPropertyValues("spring.jackson.property-naming-strategy:SNAKE_CASE")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getPropertyNamingStrategy()) assertThat(mapper.getPropertyNamingStrategy())
.isInstanceOf(SnakeCaseStrategy.class); .isInstanceOf(SnakeCaseStrategy.class);
@ -178,7 +178,7 @@ public class JacksonAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues( .withPropertyValues(
"spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy") "spring.jackson.property-naming-strategy:com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getPropertyNamingStrategy()) assertThat(mapper.getPropertyNamingStrategy())
.isInstanceOf(SnakeCaseStrategy.class); .isInstanceOf(SnakeCaseStrategy.class);
@ -189,7 +189,7 @@ public class JacksonAutoConfigurationTests {
public void enableSerializationFeature() { public void enableSerializationFeature() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.jackson.serialization.indent_output:true") .withPropertyValues("spring.jackson.serialization.indent_output:true")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault()) assertThat(SerializationFeature.INDENT_OUTPUT.enabledByDefault())
.isFalse(); .isFalse();
@ -203,7 +203,7 @@ public class JacksonAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues( .withPropertyValues(
"spring.jackson.serialization.write_dates_as_timestamps:false") "spring.jackson.serialization.write_dates_as_timestamps:false")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS assertThat(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
.enabledByDefault()).isTrue(); .enabledByDefault()).isTrue();
@ -218,7 +218,7 @@ public class JacksonAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues( .withPropertyValues(
"spring.jackson.deserialization.use_big_decimal_for_floats:true") "spring.jackson.deserialization.use_big_decimal_for_floats:true")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS assertThat(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS
.enabledByDefault()).isFalse(); .enabledByDefault()).isFalse();
@ -234,7 +234,7 @@ public class JacksonAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues( .withPropertyValues(
"spring.jackson.deserialization.fail-on-unknown-properties:false") "spring.jackson.deserialization.fail-on-unknown-properties:false")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES assertThat(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
.enabledByDefault()).isTrue(); .enabledByDefault()).isTrue();
@ -250,7 +250,7 @@ public class JacksonAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues( .withPropertyValues(
"spring.jackson.mapper.require_setters_for_getters:true") "spring.jackson.mapper.require_setters_for_getters:true")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat( assertThat(
MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault()) MapperFeature.REQUIRE_SETTERS_FOR_GETTERS.enabledByDefault())
@ -268,7 +268,7 @@ public class JacksonAutoConfigurationTests {
public void disableMapperFeature() { public void disableMapperFeature() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.jackson.mapper.use_annotations:false") .withPropertyValues("spring.jackson.mapper.use_annotations:false")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue(); assertThat(MapperFeature.USE_ANNOTATIONS.enabledByDefault()).isTrue();
assertThat(mapper.getDeserializationConfig() assertThat(mapper.getDeserializationConfig()
@ -284,7 +284,7 @@ public class JacksonAutoConfigurationTests {
public void enableParserFeature() { public void enableParserFeature() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.jackson.parser.allow_single_quotes:true") .withPropertyValues("spring.jackson.parser.allow_single_quotes:true")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault()) assertThat(JsonParser.Feature.ALLOW_SINGLE_QUOTES.enabledByDefault())
.isFalse(); .isFalse();
@ -297,7 +297,7 @@ public class JacksonAutoConfigurationTests {
public void disableParserFeature() { public void disableParserFeature() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.jackson.parser.auto_close_source:false") .withPropertyValues("spring.jackson.parser.auto_close_source:false")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault()) assertThat(JsonParser.Feature.AUTO_CLOSE_SOURCE.enabledByDefault())
.isTrue(); .isTrue();
@ -311,7 +311,7 @@ public class JacksonAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues( .withPropertyValues(
"spring.jackson.generator.write_numbers_as_strings:true") "spring.jackson.generator.write_numbers_as_strings:true")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS assertThat(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS
.enabledByDefault()).isFalse(); .enabledByDefault()).isFalse();
@ -325,7 +325,7 @@ public class JacksonAutoConfigurationTests {
public void disableGeneratorFeature() { public void disableGeneratorFeature() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.jackson.generator.auto_close_target:false") .withPropertyValues("spring.jackson.generator.auto_close_target:false")
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault()) assertThat(JsonGenerator.Feature.AUTO_CLOSE_TARGET.enabledByDefault())
.isTrue(); .isTrue();
@ -337,7 +337,7 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void defaultObjectMapperBuilder() { public void defaultObjectMapperBuilder() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
Jackson2ObjectMapperBuilder builder = context Jackson2ObjectMapperBuilder builder = context
.getBean(Jackson2ObjectMapperBuilder.class); .getBean(Jackson2ObjectMapperBuilder.class);
ObjectMapper mapper = builder.build(); ObjectMapper mapper = builder.build();
@ -360,7 +360,7 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void moduleBeansAndWellKnownModulesAreRegisteredWithTheObjectMapperBuilder() { public void moduleBeansAndWellKnownModulesAreRegisteredWithTheObjectMapperBuilder() {
this.contextRunner.withUserConfiguration(ModuleConfig.class).run(context -> { this.contextRunner.withUserConfiguration(ModuleConfig.class).run((context) -> {
ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class) ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class)
.build(); .build();
assertThat(context.getBean(CustomModule.class).getOwners()) assertThat(context.getBean(CustomModule.class).getOwners())
@ -372,7 +372,7 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void defaultSerializationInclusion() { public void defaultSerializationInclusion() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class) ObjectMapper objectMapper = context.getBean(Jackson2ObjectMapperBuilder.class)
.build(); .build();
assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion() assertThat(objectMapper.getSerializationConfig().getDefaultPropertyInclusion()
@ -384,7 +384,7 @@ public class JacksonAutoConfigurationTests {
public void customSerializationInclusion() { public void customSerializationInclusion() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.jackson.default-property-inclusion:non_null") .withPropertyValues("spring.jackson.default-property-inclusion:non_null")
.run(context -> { .run((context) -> {
ObjectMapper objectMapper = context ObjectMapper objectMapper = context
.getBean(Jackson2ObjectMapperBuilder.class).build(); .getBean(Jackson2ObjectMapperBuilder.class).build();
assertThat(objectMapper.getSerializationConfig() assertThat(objectMapper.getSerializationConfig()
@ -398,7 +398,7 @@ public class JacksonAutoConfigurationTests {
this.contextRunner this.contextRunner
.withPropertyValues("spring.jackson.time-zone:America/Los_Angeles", .withPropertyValues("spring.jackson.time-zone:America/Los_Angeles",
"spring.jackson.date-format:zzzz", "spring.jackson.locale:en") "spring.jackson.date-format:zzzz", "spring.jackson.locale:en")
.run(context -> { .run((context) -> {
ObjectMapper objectMapper = context ObjectMapper objectMapper = context
.getBean(Jackson2ObjectMapperBuilder.class).build(); .getBean(Jackson2ObjectMapperBuilder.class).build();
DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC); DateTime dateTime = new DateTime(1436966242231L, DateTimeZone.UTC);
@ -410,7 +410,7 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void customTimeZoneFormattingADate() throws JsonProcessingException { public void customTimeZoneFormattingADate() throws JsonProcessingException {
this.contextRunner.withPropertyValues("spring.jackson.time-zone:GMT+10", this.contextRunner.withPropertyValues("spring.jackson.time-zone:GMT+10",
"spring.jackson.date-format:z").run(context -> { "spring.jackson.date-format:z").run((context) -> {
ObjectMapper objectMapper = context ObjectMapper objectMapper = context
.getBean(Jackson2ObjectMapperBuilder.class).build(); .getBean(Jackson2ObjectMapperBuilder.class).build();
Date date = new Date(1436966242231L); Date date = new Date(1436966242231L);
@ -425,7 +425,7 @@ public class JacksonAutoConfigurationTests {
.withPropertyValues("spring.jackson.locale:de_DE", .withPropertyValues("spring.jackson.locale:de_DE",
"spring.jackson.date-format:zzzz", "spring.jackson.date-format:zzzz",
"spring.jackson.serialization.write-dates-with-zone-id:true") "spring.jackson.serialization.write-dates-with-zone-id:true")
.run(context -> { .run((context) -> {
ObjectMapper objectMapper = context.getBean(ObjectMapper.class); ObjectMapper objectMapper = context.getBean(ObjectMapper.class);
DateTime jodaTime = new DateTime(1478424650000L, DateTime jodaTime = new DateTime(1478424650000L,
DateTimeZone.forID("Europe/Rome")); DateTimeZone.forID("Europe/Rome"));
@ -437,7 +437,7 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void additionalJacksonBuilderCustomization() { public void additionalJacksonBuilderCustomization() {
this.contextRunner.withUserConfiguration(ObjectMapperBuilderCustomConfig.class) this.contextRunner.withUserConfiguration(ObjectMapperBuilderCustomConfig.class)
.run(context -> { .run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class); assertThat(mapper.getDateFormat()).isInstanceOf(MyDateFormat.class);
}); });
@ -457,7 +457,7 @@ public class JacksonAutoConfigurationTests {
@Test @Test
public void writeDatesAsTimestampsDefault() { public void writeDatesAsTimestampsDefault() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
ObjectMapper mapper = context.getBean(ObjectMapper.class); ObjectMapper mapper = context.getBean(ObjectMapper.class);
DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC); DateTime dateTime = new DateTime(1988, 6, 25, 20, 30, DateTimeZone.UTC);
String expected = FormatConfig.DEFAULT_DATETIME_PRINTER.rawFormatter() String expected = FormatConfig.DEFAULT_DATETIME_PRINTER.rawFormatter()
@ -469,7 +469,7 @@ public class JacksonAutoConfigurationTests {
private void assertParameterNamesModuleCreatorBinding(Mode expectedMode, private void assertParameterNamesModuleCreatorBinding(Mode expectedMode,
Class<?>... configClasses) { Class<?>... configClasses) {
this.contextRunner.withUserConfiguration(configClasses).run(context -> { this.contextRunner.withUserConfiguration(configClasses).run((context) -> {
DeserializationConfig deserializationConfig = context DeserializationConfig deserializationConfig = context
.getBean(ObjectMapper.class).getDeserializationConfig(); .getBean(ObjectMapper.class).getDeserializationConfig();
AnnotationIntrospector annotationIntrospector = deserializationConfig AnnotationIntrospector annotationIntrospector = deserializationConfig

@ -47,20 +47,21 @@ import static org.mockito.Mockito.mock;
public class MongoReactiveAutoConfigurationTests { public class MongoReactiveAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of( .withConfiguration(
MongoReactiveAutoConfiguration.class)); AutoConfigurations.of(MongoReactiveAutoConfiguration.class));
@Test @Test
public void clientExists() { public void clientExists() {
this.contextRunner.run((context) -> this.contextRunner
assertThat(context).hasSingleBean(MongoClient.class)); .run((context) -> assertThat(context).hasSingleBean(MongoClient.class));
} }
@Test @Test
public void optionsAdded() { public void optionsAdded() {
this.contextRunner.withPropertyValues("spring.data.mongodb.host:localhost") this.contextRunner.withPropertyValues("spring.data.mongodb.host:localhost")
.withUserConfiguration(OptionsConfig.class).run((context) -> .withUserConfiguration(OptionsConfig.class)
assertThat(context.getBean(MongoClient.class).getSettings() .run((context) -> assertThat(
context.getBean(MongoClient.class).getSettings()
.getSocketSettings().getReadTimeout(TimeUnit.SECONDS)) .getSocketSettings().getReadTimeout(TimeUnit.SECONDS))
.isEqualTo(300)); .isEqualTo(300));
} }
@ -69,9 +70,10 @@ public class MongoReactiveAutoConfigurationTests {
public void optionsAddedButNoHost() { public void optionsAddedButNoHost() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test") .withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test")
.withUserConfiguration(OptionsConfig.class).run((context) -> .withUserConfiguration(OptionsConfig.class)
assertThat(context.getBean(MongoClient.class).getSettings() .run((context) -> assertThat(context.getBean(MongoClient.class)
.getReadPreference()).isEqualTo(ReadPreference.nearest())); .getSettings().getReadPreference())
.isEqualTo(ReadPreference.nearest()));
} }
@Test @Test
@ -101,7 +103,8 @@ public class MongoReactiveAutoConfigurationTests {
@Test @Test
public void customizerOverridesAutoConfig() { public void customizerOverridesAutoConfig() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.data.mongodb.uri:mongodb://localhost/test?appname=auto-config") .withPropertyValues(
"spring.data.mongodb.uri:mongodb://localhost/test?appname=auto-config")
.withUserConfiguration(SimpleCustomizerConfig.class).run((context) -> { .withUserConfiguration(SimpleCustomizerConfig.class).run((context) -> {
assertThat(context).hasSingleBean(MongoClient.class); assertThat(context).hasSingleBean(MongoClient.class);
MongoClient client = context.getBean(MongoClient.class); MongoClient client = context.getBean(MongoClient.class);
@ -147,8 +150,8 @@ public class MongoReactiveAutoConfigurationTests {
@Configuration @Configuration
static class SimpleCustomizerConfig { static class SimpleCustomizerConfig {
private static final StreamFactoryFactory streamFactoryFactory = private static final StreamFactoryFactory streamFactoryFactory = new AsynchronousSocketChannelStreamFactoryFactory.Builder()
new AsynchronousSocketChannelStreamFactoryFactory(); .build();
@Bean @Bean
public MongoClientSettingsBuilderCustomizer customizer() { public MongoClientSettingsBuilderCustomizer customizer() {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -75,8 +75,7 @@ public class ReactiveMongoClientFactoryTests {
properties.setUsername("user"); properties.setUsername("user");
properties.setPassword("secret".toCharArray()); properties.setPassword("secret".toCharArray());
MongoClient client = createMongoClient(properties); MongoClient client = createMongoClient(properties);
assertMongoCredential(extractMongoCredentials(client).get(0), "user", "secret", assertMongoCredential(extractMongoCredentials(client), "user", "secret", "test");
"test");
} }
@Test @Test
@ -86,8 +85,7 @@ public class ReactiveMongoClientFactoryTests {
properties.setUsername("user"); properties.setUsername("user");
properties.setPassword("secret".toCharArray()); properties.setPassword("secret".toCharArray());
MongoClient client = createMongoClient(properties); MongoClient client = createMongoClient(properties);
assertMongoCredential(extractMongoCredentials(client).get(0), "user", "secret", assertMongoCredential(extractMongoCredentials(client), "user", "secret", "foo");
"foo");
} }
@Test @Test
@ -97,8 +95,7 @@ public class ReactiveMongoClientFactoryTests {
properties.setUsername("user"); properties.setUsername("user");
properties.setPassword("secret".toCharArray()); properties.setPassword("secret".toCharArray());
MongoClient client = createMongoClient(properties); MongoClient client = createMongoClient(properties);
assertMongoCredential(extractMongoCredentials(client).get(0), "user", "secret", assertMongoCredential(extractMongoCredentials(client), "user", "secret", "foo");
"foo");
} }
@Test @Test
@ -111,9 +108,8 @@ public class ReactiveMongoClientFactoryTests {
assertThat(allAddresses).hasSize(2); assertThat(allAddresses).hasSize(2);
assertServerAddress(allAddresses.get(0), "mongo1.example.com", 12345); assertServerAddress(allAddresses.get(0), "mongo1.example.com", 12345);
assertServerAddress(allAddresses.get(1), "mongo2.example.com", 23456); assertServerAddress(allAddresses.get(1), "mongo2.example.com", 23456);
List<MongoCredential> credentialsList = extractMongoCredentials(client); MongoCredential credential = extractMongoCredentials(client);
assertThat(credentialsList).hasSize(1); assertMongoCredential(credential, "user", "secret", "test");
assertMongoCredential(credentialsList.get(0), "user", "secret", "test");
} }
@Test @Test
@ -197,9 +193,9 @@ public class ReactiveMongoClientFactoryTests {
return clusterSettings.getHosts(); return clusterSettings.getHosts();
} }
private List<MongoCredential> extractMongoCredentials(MongoClient client) { private MongoCredential extractMongoCredentials(MongoClient client) {
MongoClientSettings settings = client.getSettings(); MongoClientSettings settings = client.getSettings();
return settings.getCredentialList(); return settings.getCredential();
} }
private void assertServerAddress(ServerAddress serverAddress, String expectedHost, private void assertServerAddress(ServerAddress serverAddress, String expectedHost,

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -42,7 +42,7 @@ public class AuthenticationManagerConfigurationTests {
@Test @Test
public void userDetailsServiceWhenPasswordEncoderAbsentAndDefaultPassword() { public void userDetailsServiceWhenPasswordEncoderAbsentAndDefaultPassword() {
this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class, this.contextRunner.withUserConfiguration(TestSecurityConfiguration.class,
AuthenticationManagerConfiguration.class).run((context -> { AuthenticationManagerConfiguration.class).run(((context) -> {
InMemoryUserDetailsManager userDetailsService = context InMemoryUserDetailsManager userDetailsService = context
.getBean(InMemoryUserDetailsManager.class); .getBean(InMemoryUserDetailsManager.class);
String password = userDetailsService.loadUserByUsername("user") String password = userDetailsService.loadUserByUsername("user")
@ -73,7 +73,7 @@ public class AuthenticationManagerConfigurationTests {
.withUserConfiguration(configClass, .withUserConfiguration(configClass,
AuthenticationManagerConfiguration.class) AuthenticationManagerConfiguration.class)
.withPropertyValues("spring.security.user.password=" + providedPassword) .withPropertyValues("spring.security.user.password=" + providedPassword)
.run((context -> { .run(((context) -> {
InMemoryUserDetailsManager userDetailsService = context InMemoryUserDetailsManager userDetailsService = context
.getBean(InMemoryUserDetailsManager.class); .getBean(InMemoryUserDetailsManager.class);
String password = userDetailsService.loadUserByUsername("user") String password = userDetailsService.loadUserByUsername("user")

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -45,7 +45,7 @@ public class ReactiveAuthenticationManagerConfigurationTests {
this.contextRunner this.contextRunner
.withUserConfiguration(TestSecurityConfiguration.class, .withUserConfiguration(TestSecurityConfiguration.class,
ReactiveAuthenticationManagerConfiguration.class) ReactiveAuthenticationManagerConfiguration.class)
.run((context -> { .run(((context) -> {
MapReactiveUserDetailsService userDetailsService = context MapReactiveUserDetailsService userDetailsService = context
.getBean(MapReactiveUserDetailsService.class); .getBean(MapReactiveUserDetailsService.class);
String password = userDetailsService.findByUsername("user").block() String password = userDetailsService.findByUsername("user").block()
@ -76,7 +76,7 @@ public class ReactiveAuthenticationManagerConfigurationTests {
.withUserConfiguration(configClass, .withUserConfiguration(configClass,
ReactiveAuthenticationManagerConfiguration.class) ReactiveAuthenticationManagerConfiguration.class)
.withPropertyValues("spring.security.user.password=" + providedPassword) .withPropertyValues("spring.security.user.password=" + providedPassword)
.run((context -> { .run(((context) -> {
MapReactiveUserDetailsService userDetailsService = context MapReactiveUserDetailsService userDetailsService = context
.getBean(MapReactiveUserDetailsService.class); .getBean(MapReactiveUserDetailsService.class);
String password = userDetailsService.findByUsername("user").block() String password = userDetailsService.findByUsername("user").block()

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -46,8 +46,8 @@ public class ReactiveSessionAutoConfigurationRedisTests
extends AbstractSessionAutoConfigurationTests { extends AbstractSessionAutoConfigurationTests {
@ClassRule @ClassRule
public static DockerTestContainer<FixedHostPortGenericContainer> redis = new DockerTestContainer<>(() -> public static DockerTestContainer<FixedHostPortGenericContainer<?>> redis = new DockerTestContainer<>(
new FixedHostPortGenericContainer("redis:latest") () -> new FixedHostPortGenericContainer<>("redis:latest")
.withFixedExposedPort(6379, 6379)); .withFixedExposedPort(6379, 6379));
protected final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() protected final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -47,8 +47,8 @@ public class SessionAutoConfigurationRedisTests
extends AbstractSessionAutoConfigurationTests { extends AbstractSessionAutoConfigurationTests {
@ClassRule @ClassRule
public static DockerTestContainer<FixedHostPortGenericContainer> redis = new DockerTestContainer<>(() -> public static DockerTestContainer<FixedHostPortGenericContainer<?>> redis = new DockerTestContainer<>(
new FixedHostPortGenericContainer("redis:latest") () -> new FixedHostPortGenericContainer<>("redis:latest")
.withFixedExposedPort(6379, 6379)); .withFixedExposedPort(6379, 6379));
protected final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() protected final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -78,7 +78,7 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void shouldNotProcessIfExistingWebReactiveConfiguration() { public void shouldNotProcessIfExistingWebReactiveConfiguration() {
this.contextRunner.withUserConfiguration(WebFluxConfigurationSupport.class) this.contextRunner.withUserConfiguration(WebFluxConfigurationSupport.class)
.run(context -> { .run((context) -> {
assertThat(context).getBeans(RequestMappingHandlerMapping.class) assertThat(context).getBeans(RequestMappingHandlerMapping.class)
.hasSize(1); .hasSize(1);
assertThat(context).getBeans(RequestMappingHandlerAdapter.class) assertThat(context).getBeans(RequestMappingHandlerAdapter.class)
@ -88,7 +88,7 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void shouldCreateDefaultBeans() { public void shouldCreateDefaultBeans() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
assertThat(context).getBeans(RequestMappingHandlerMapping.class).hasSize(1); assertThat(context).getBeans(RequestMappingHandlerMapping.class).hasSize(1);
assertThat(context).getBeans(RequestMappingHandlerAdapter.class).hasSize(1); assertThat(context).getBeans(RequestMappingHandlerAdapter.class).hasSize(1);
assertThat(context).getBeans(RequestedContentTypeResolver.class).hasSize(1); assertThat(context).getBeans(RequestedContentTypeResolver.class).hasSize(1);
@ -101,7 +101,7 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void shouldRegisterCustomHandlerMethodArgumentResolver() { public void shouldRegisterCustomHandlerMethodArgumentResolver() {
this.contextRunner.withUserConfiguration(CustomArgumentResolvers.class) this.contextRunner.withUserConfiguration(CustomArgumentResolvers.class)
.run(context -> { .run((context) -> {
RequestMappingHandlerAdapter adapter = context RequestMappingHandlerAdapter adapter = context
.getBean(RequestMappingHandlerAdapter.class); .getBean(RequestMappingHandlerAdapter.class);
List<HandlerMethodArgumentResolver> customResolvers = (List<HandlerMethodArgumentResolver>) ReflectionTestUtils List<HandlerMethodArgumentResolver> customResolvers = (List<HandlerMethodArgumentResolver>) ReflectionTestUtils
@ -118,7 +118,7 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void shouldCustomizeCodecs() { public void shouldCustomizeCodecs() {
this.contextRunner.withUserConfiguration(CustomCodecCustomizers.class) this.contextRunner.withUserConfiguration(CustomCodecCustomizers.class)
.run(context -> { .run((context) -> {
CodecCustomizer codecCustomizer = context CodecCustomizer codecCustomizer = context
.getBean("firstCodecCustomizer", CodecCustomizer.class); .getBean("firstCodecCustomizer", CodecCustomizer.class);
assertThat(codecCustomizer).isNotNull(); assertThat(codecCustomizer).isNotNull();
@ -128,7 +128,7 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void shouldRegisterResourceHandlerMapping() { public void shouldRegisterResourceHandlerMapping() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping",
SimpleUrlHandlerMapping.class); SimpleUrlHandlerMapping.class);
assertThat(hm.getUrlMap().get("/**")).isInstanceOf(ResourceWebHandler.class); assertThat(hm.getUrlMap().get("/**")).isInstanceOf(ResourceWebHandler.class);
@ -149,7 +149,7 @@ public class WebFluxAutoConfigurationTests {
public void shouldMapResourcesToCustomPath() { public void shouldMapResourcesToCustomPath() {
this.contextRunner this.contextRunner
.withPropertyValues("spring.webflux.static-path-pattern:/static/**") .withPropertyValues("spring.webflux.static-path-pattern:/static/**")
.run(context -> { .run((context) -> {
SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping",
SimpleUrlHandlerMapping.class); SimpleUrlHandlerMapping.class);
assertThat(hm.getUrlMap().get("/static/**")) assertThat(hm.getUrlMap().get("/static/**"))
@ -163,16 +163,14 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void shouldNotMapResourcesWhenDisabled() { public void shouldNotMapResourcesWhenDisabled() {
this.contextRunner.withPropertyValues("spring.resources.add-mappings:false") this.contextRunner.withPropertyValues("spring.resources.add-mappings:false")
.run(context -> { .run((context) -> assertThat(context.getBean("resourceHandlerMapping"))
assertThat(context.getBean("resourceHandlerMapping")) .isNotInstanceOf(SimpleUrlHandlerMapping.class));
.isNotInstanceOf(SimpleUrlHandlerMapping.class);
});
} }
@Test @Test
public void resourceHandlerChainEnabled() { public void resourceHandlerChainEnabled() {
this.contextRunner.withPropertyValues("spring.resources.chain.enabled:true") this.contextRunner.withPropertyValues("spring.resources.chain.enabled:true")
.run(context -> { .run((context) -> {
SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping hm = context.getBean("resourceHandlerMapping",
SimpleUrlHandlerMapping.class); SimpleUrlHandlerMapping.class);
assertThat(hm.getUrlMap().get("/**")) assertThat(hm.getUrlMap().get("/**"))
@ -191,7 +189,7 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void shouldRegisterViewResolvers() { public void shouldRegisterViewResolvers() {
this.contextRunner.withUserConfiguration(ViewResolvers.class).run(context -> { this.contextRunner.withUserConfiguration(ViewResolvers.class).run((context) -> {
ViewResolutionResultHandler resultHandler = context ViewResolutionResultHandler resultHandler = context
.getBean(ViewResolutionResultHandler.class); .getBean(ViewResolutionResultHandler.class);
assertThat(resultHandler.getViewResolvers()).containsExactly( assertThat(resultHandler.getViewResolvers()).containsExactly(
@ -226,7 +224,7 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void validatorWhenNoValidatorShouldUseDefault() { public void validatorWhenNoValidatorShouldUseDefault() {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(ValidatorFactory.class);
assertThat(context).doesNotHaveBean(javax.validation.Validator.class); assertThat(context).doesNotHaveBean(javax.validation.Validator.class);
assertThat(context).getBeanNames(Validator.class) assertThat(context).getBeanNames(Validator.class)
@ -239,7 +237,7 @@ public class WebFluxAutoConfigurationTests {
this.contextRunner this.contextRunner
.withConfiguration( .withConfiguration(
AutoConfigurations.of(ValidationAutoConfiguration.class)) AutoConfigurations.of(ValidationAutoConfiguration.class))
.run(context -> { .run((context) -> {
assertThat(context).getBeanNames(javax.validation.Validator.class) assertThat(context).getBeanNames(javax.validation.Validator.class)
.containsExactly("defaultValidator"); .containsExactly("defaultValidator");
assertThat(context).getBeanNames(Validator.class) assertThat(context).getBeanNames(Validator.class)
@ -261,7 +259,7 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void validatorWithConfigurerShouldUseSpringValidator() { public void validatorWithConfigurerShouldUseSpringValidator() {
this.contextRunner.withUserConfiguration(ValidatorWebFluxConfigurer.class) this.contextRunner.withUserConfiguration(ValidatorWebFluxConfigurer.class)
.run(context -> { .run((context) -> {
assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(ValidatorFactory.class);
assertThat(context).doesNotHaveBean(javax.validation.Validator.class); assertThat(context).doesNotHaveBean(javax.validation.Validator.class);
assertThat(context).getBeanNames(Validator.class) assertThat(context).getBeanNames(Validator.class)
@ -274,7 +272,7 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void validatorWithConfigurerDoesNotExposeJsr303() { public void validatorWithConfigurerDoesNotExposeJsr303() {
this.contextRunner.withUserConfiguration(ValidatorJsr303WebFluxConfigurer.class) this.contextRunner.withUserConfiguration(ValidatorJsr303WebFluxConfigurer.class)
.run(context -> { .run((context) -> {
assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(ValidatorFactory.class);
assertThat(context).doesNotHaveBean(javax.validation.Validator.class); assertThat(context).doesNotHaveBean(javax.validation.Validator.class);
assertThat(context).getBeanNames(Validator.class) assertThat(context).getBeanNames(Validator.class)
@ -293,7 +291,8 @@ public class WebFluxAutoConfigurationTests {
this.contextRunner this.contextRunner
.withConfiguration( .withConfiguration(
AutoConfigurations.of(ValidationAutoConfiguration.class)) AutoConfigurations.of(ValidationAutoConfiguration.class))
.withUserConfiguration(ValidatorWebFluxConfigurer.class).run(context -> { .withUserConfiguration(ValidatorWebFluxConfigurer.class)
.run((context) -> {
assertThat(context).getBeans(ValidatorFactory.class).hasSize(1); assertThat(context).getBeans(ValidatorFactory.class).hasSize(1);
assertThat(context).getBeans(javax.validation.Validator.class) assertThat(context).getBeans(javax.validation.Validator.class)
.hasSize(1); .hasSize(1);
@ -315,7 +314,7 @@ public class WebFluxAutoConfigurationTests {
this.contextRunner this.contextRunner
.withConfiguration( .withConfiguration(
AutoConfigurations.of(ValidationAutoConfiguration.class)) AutoConfigurations.of(ValidationAutoConfiguration.class))
.withUserConfiguration(CustomSpringValidator.class).run(context -> { .withUserConfiguration(CustomSpringValidator.class).run((context) -> {
assertThat(context).getBeanNames(javax.validation.Validator.class) assertThat(context).getBeanNames(javax.validation.Validator.class)
.containsExactly("defaultValidator"); .containsExactly("defaultValidator");
assertThat(context).getBeanNames(Validator.class) assertThat(context).getBeanNames(Validator.class)
@ -337,7 +336,7 @@ public class WebFluxAutoConfigurationTests {
@Test @Test
public void validatorWithCustomJsr303ValidatorExposedAsSpringValidator() { public void validatorWithCustomJsr303ValidatorExposedAsSpringValidator() {
this.contextRunner.withUserConfiguration(CustomJsr303Validator.class) this.contextRunner.withUserConfiguration(CustomJsr303Validator.class)
.run(context -> { .run((context) -> {
assertThat(context).doesNotHaveBean(ValidatorFactory.class); assertThat(context).doesNotHaveBean(ValidatorFactory.class);
assertThat(context).getBeanNames(javax.validation.Validator.class) assertThat(context).getBeanNames(javax.validation.Validator.class)
.containsExactly("customValidator"); .containsExactly("customValidator");

@ -57,11 +57,14 @@ import static org.hamcrest.Matchers.not;
public class DefaultErrorWebExceptionHandlerIntegrationTests { public class DefaultErrorWebExceptionHandlerIntegrationTests {
private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ReactiveWebServerAutoConfiguration.class, .withConfiguration(AutoConfigurations.of(
ReactiveWebServerAutoConfiguration.class,
HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class,
ErrorWebFluxAutoConfiguration.class, ErrorWebFluxAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, MustacheAutoConfiguration.class)) PropertyPlaceholderAutoConfiguration.class,
.withPropertyValues("spring.main.web-application-type=reactive", "server.port=0") MustacheAutoConfiguration.class))
.withPropertyValues("spring.main.web-application-type=reactive",
"server.port=0")
.withUserConfiguration(Application.class); .withUserConfiguration(Application.class);
@Rule @Rule
@ -72,8 +75,9 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
@Test @Test
public void jsonError() throws Exception { public void jsonError() throws Exception {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); WebTestClient client = WebTestClient.bindToApplicationContext(context)
.build();
client.get().uri("/").exchange().expectStatus() client.get().uri("/").exchange().expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody()
.jsonPath("status").isEqualTo("500").jsonPath("error") .jsonPath("status").isEqualTo("500").jsonPath("error")
@ -88,8 +92,9 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
@Test @Test
public void notFound() throws Exception { public void notFound() throws Exception {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); WebTestClient client = WebTestClient.bindToApplicationContext(context)
.build();
client.get().uri("/notFound").exchange().expectStatus() client.get().uri("/notFound").exchange().expectStatus()
.isEqualTo(HttpStatus.NOT_FOUND).expectBody().jsonPath("status") .isEqualTo(HttpStatus.NOT_FOUND).expectBody().jsonPath("status")
.isEqualTo("404").jsonPath("error") .isEqualTo("404").jsonPath("error")
@ -100,12 +105,13 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
@Test @Test
public void htmlError() throws Exception { public void htmlError() throws Exception {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); WebTestClient client = WebTestClient.bindToApplicationContext(context)
String body = client.get().uri("/").accept(MediaType.TEXT_HTML) .build();
.exchange().expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange()
.expectHeader().contentType(MediaType.TEXT_HTML).expectBody(String.class) .expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
.returnResult().getResponseBody(); .expectHeader().contentType(MediaType.TEXT_HTML)
.expectBody(String.class).returnResult().getResponseBody();
assertThat(body).contains("status: 500").contains("message: Expected!"); assertThat(body).contains("status: 500").contains("message: Expected!");
this.output.expect(allOf(containsString("Failed to handle request [GET /]"), this.output.expect(allOf(containsString("Failed to handle request [GET /]"),
containsString("IllegalStateException"))); containsString("IllegalStateException")));
@ -114,8 +120,9 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
@Test @Test
public void bindingResultError() throws Exception { public void bindingResultError() throws Exception {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); WebTestClient client = WebTestClient.bindToApplicationContext(context)
.build();
client.post().uri("/bind").contentType(MediaType.APPLICATION_JSON) client.post().uri("/bind").contentType(MediaType.APPLICATION_JSON)
.syncBody("{}").exchange().expectStatus() .syncBody("{}").exchange().expectStatus()
.isEqualTo(HttpStatus.BAD_REQUEST).expectBody().jsonPath("status") .isEqualTo(HttpStatus.BAD_REQUEST).expectBody().jsonPath("status")
@ -131,45 +138,47 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
this.contextRunner this.contextRunner
.withPropertyValues("server.error.include-exception=true", .withPropertyValues("server.error.include-exception=true",
"server.error.include-stacktrace=on-trace-param") "server.error.include-stacktrace=on-trace-param")
.run(context -> { .run((context) -> {
WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); WebTestClient client = WebTestClient.bindToApplicationContext(context)
.build();
client.get().uri("/?trace=true").exchange().expectStatus() client.get().uri("/?trace=true").exchange().expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody()
.jsonPath("status").isEqualTo("500").jsonPath("error") .jsonPath("status").isEqualTo("500").jsonPath("error")
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
.jsonPath("exception").isEqualTo(IllegalStateException.class.getName()) .jsonPath("exception")
.isEqualTo(IllegalStateException.class.getName())
.jsonPath("trace").exists(); .jsonPath("trace").exists();
}); });
} }
@Test @Test
public void alwaysIncludeStackTrace() throws Exception { public void alwaysIncludeStackTrace() throws Exception {
this.contextRunner this.contextRunner.withPropertyValues("server.error.include-exception=true",
.withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=always").run((context) -> {
"server.error.include-stacktrace=always") WebTestClient client = WebTestClient.bindToApplicationContext(context)
.run(context -> { .build();
WebTestClient client = WebTestClient.bindToApplicationContext(context).build();
client.get().uri("/?trace=false").exchange().expectStatus() client.get().uri("/?trace=false").exchange().expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody()
.jsonPath("status").isEqualTo("500").jsonPath("error") .jsonPath("status").isEqualTo("500").jsonPath("error")
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
.jsonPath("exception").isEqualTo(IllegalStateException.class.getName()) .jsonPath("exception")
.isEqualTo(IllegalStateException.class.getName())
.jsonPath("trace").exists(); .jsonPath("trace").exists();
}); });
} }
@Test @Test
public void neverIncludeStackTrace() throws Exception { public void neverIncludeStackTrace() throws Exception {
this.contextRunner this.contextRunner.withPropertyValues("server.error.include-exception=true",
.withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=never").run((context) -> {
"server.error.include-stacktrace=never") WebTestClient client = WebTestClient.bindToApplicationContext(context)
.run(context -> { .build();
WebTestClient client = WebTestClient.bindToApplicationContext(context).build();
client.get().uri("/?trace=true").exchange().expectStatus() client.get().uri("/?trace=true").exchange().expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody()
.jsonPath("status").isEqualTo("500").jsonPath("error") .jsonPath("status").isEqualTo("500").jsonPath("error")
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()) .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
.jsonPath("exception").isEqualTo(IllegalStateException.class.getName()) .jsonPath("exception")
.isEqualTo(IllegalStateException.class.getName())
.jsonPath("trace").doesNotExist(); .jsonPath("trace").doesNotExist();
}); });
@ -177,14 +186,15 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
@Test @Test
public void statusException() throws Exception { public void statusException() throws Exception {
this.contextRunner this.contextRunner.withPropertyValues("server.error.include-exception=true")
.withPropertyValues("server.error.include-exception=true") .run((context) -> {
.run(context -> { WebTestClient client = WebTestClient.bindToApplicationContext(context)
WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); .build();
client.get().uri("/badRequest").exchange().expectStatus() client.get().uri("/badRequest").exchange().expectStatus()
.isEqualTo(HttpStatus.BAD_REQUEST).expectBody().jsonPath("status") .isEqualTo(HttpStatus.BAD_REQUEST).expectBody()
.isEqualTo("400").jsonPath("error") .jsonPath("status").isEqualTo("400").jsonPath("error")
.isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()).jsonPath("exception") .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase())
.jsonPath("exception")
.isEqualTo(ResponseStatusException.class.getName()); .isEqualTo(ResponseStatusException.class.getName());
this.output.expect(not(containsString("ResponseStatusException"))); this.output.expect(not(containsString("ResponseStatusException")));
}); });
@ -194,27 +204,31 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests {
public void defaultErrorView() throws Exception { public void defaultErrorView() throws Exception {
this.contextRunner this.contextRunner
.withPropertyValues("spring.mustache.prefix=classpath:/unknown/") .withPropertyValues("spring.mustache.prefix=classpath:/unknown/")
.run(context -> { .run((context) -> {
WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); WebTestClient client = WebTestClient.bindToApplicationContext(context)
.build();
String body = client.get().uri("/").accept(MediaType.TEXT_HTML) String body = client.get().uri("/").accept(MediaType.TEXT_HTML)
.exchange().expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR) .exchange().expectStatus()
.expectHeader().contentType(MediaType.TEXT_HTML).expectBody(String.class) .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader()
.contentType(MediaType.TEXT_HTML).expectBody(String.class)
.returnResult().getResponseBody(); .returnResult().getResponseBody();
assertThat(body).contains("Whitelabel Error Page") assertThat(body).contains("Whitelabel Error Page")
.contains("<div>Expected!</div>"); .contains("<div>Expected!</div>");
this.output.expect(allOf(containsString("Failed to handle request [GET /]"), this.output.expect(
allOf(containsString("Failed to handle request [GET /]"),
containsString("IllegalStateException"))); containsString("IllegalStateException")));
}); });
} }
@Test @Test
public void responseCommitted() throws Exception { public void responseCommitted() throws Exception {
this.contextRunner.run(context -> { this.contextRunner.run((context) -> {
WebTestClient client = WebTestClient.bindToApplicationContext(context).build(); WebTestClient client = WebTestClient.bindToApplicationContext(context)
.build();
this.thrown.expectCause(instanceOf(IllegalStateException.class)); this.thrown.expectCause(instanceOf(IllegalStateException.class));
this.thrown.expectMessage("already committed!"); this.thrown.expectMessage("already committed!");
client.get().uri("/commit").exchange().expectStatus() client.get().uri("/commit").exchange().expectStatus().isEqualTo(HttpStatus.OK)
.isEqualTo(HttpStatus.OK).expectBody().isEmpty(); .expectBody().isEmpty();
}); });
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -40,11 +40,9 @@ public class UserServiceAutoConfigurationTests {
// tag::test-env[] // tag::test-env[]
@Test @Test
public void serviceNameCanBeConfigured() { public void serviceNameCanBeConfigured() {
this.contextRunner.withPropertyValues("user.name=test123") this.contextRunner.withPropertyValues("user.name=test123").run((context) -> {
.run((context) -> {
assertThat(context).hasSingleBean(UserService.class); assertThat(context).hasSingleBean(UserService.class);
assertThat(context.getBean(UserService.class).getName()) assertThat(context.getBean(UserService.class).getName()).isEqualTo("test123");
.isEqualTo("test123");
}); });
} }
// end::test-env[] // end::test-env[]
@ -53,13 +51,10 @@ public class UserServiceAutoConfigurationTests {
@Test @Test
public void serviceIsIgnoredIfLibraryIsNotPresent() { public void serviceIsIgnoredIfLibraryIsNotPresent() {
this.contextRunner.withClassLoader(new FilteredClassLoader(UserService.class)) this.contextRunner.withClassLoader(new FilteredClassLoader(UserService.class))
.run((context) -> { .run((context) -> assertThat(context).doesNotHaveBean("userService"));
assertThat(context).doesNotHaveBean("userService");
});
} }
// end::test-classloader[] // end::test-classloader[]
// tag::test-user-config[] // tag::test-user-config[]
@Test @Test
public void defaultServiceBacksOff() { public void defaultServiceBacksOff() {

@ -26,12 +26,13 @@ import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.GenericContainer;
/** /**
* {@link TestRule} for working with an optional Docker environment. Spins up a {@link GenericContainer} * {@link TestRule} for working with an optional Docker environment. Spins up a
* if a valid docker environment is found. * {@link GenericContainer} if a valid docker environment is found.
* *
* @param <T> the type of the container
* @author Madhura Bhave * @author Madhura Bhave
*/ */
public class DockerTestContainer<T extends GenericContainer> implements TestRule { public class DockerTestContainer<T extends GenericContainer<?>> implements TestRule {
private Supplier<T> containerSupplier; private Supplier<T> containerSupplier;
@ -60,4 +61,3 @@ public class DockerTestContainer<T extends GenericContainer> implements TestRule
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,7 +18,6 @@ package org.springframework.boot.test.autoconfigure.data.neo4j;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.junit.ClassRule; import org.junit.ClassRule;
import org.junit.Rule; import org.junit.Rule;
@ -31,7 +30,6 @@ import org.neo4j.ogm.session.SessionFactory;
import org.rnorth.ducttape.TimeoutException; import org.rnorth.ducttape.TimeoutException;
import org.rnorth.ducttape.unreliables.Unreliables; import org.rnorth.ducttape.unreliables.Unreliables;
import org.testcontainers.containers.FixedHostPortGenericContainer; import org.testcontainers.containers.FixedHostPortGenericContainer;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.HostPortWaitStrategy; import org.testcontainers.containers.wait.HostPortWaitStrategy;
import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoSuchBeanDefinitionException;
@ -53,10 +51,11 @@ import static org.assertj.core.api.Assertions.assertThat;
public class DataNeo4jTestIntegrationTests { public class DataNeo4jTestIntegrationTests {
@ClassRule @ClassRule
public static DockerTestContainer<GenericContainer> genericContainer = new DockerTestContainer<>((Supplier<GenericContainer>) () -> new FixedHostPortGenericContainer("neo4j:latest") public static DockerTestContainer<FixedHostPortGenericContainer<?>> neo4j = new DockerTestContainer<>(
() -> new FixedHostPortGenericContainer<>("neo4j:latest")
.withFixedExposedPort(7687, 7687) .withFixedExposedPort(7687, 7687)
.waitingFor(new ConnectionVerifyingWaitStrategy()).withEnv("NEO4J_AUTH", "none")); .waitingFor(new ConnectionVerifyingWaitStrategy())
.withEnv("NEO4J_AUTH", "none"));
@Rule @Rule
public ExpectedException thrown = ExpectedException.none(); public ExpectedException thrown = ExpectedException.none();
@ -96,8 +95,8 @@ public class DataNeo4jTestIntegrationTests {
SessionFactory sessionFactory = new SessionFactory(configuration, SessionFactory sessionFactory = new SessionFactory(configuration,
"org.springframework.boot.test.autoconfigure.data.neo4j"); "org.springframework.boot.test.autoconfigure.data.neo4j");
try { try {
Unreliables.retryUntilTrue((int) startupTimeout.getSeconds(), TimeUnit.SECONDS, Unreliables.retryUntilTrue((int) this.startupTimeout.getSeconds(),
checkConnection(sessionFactory)); TimeUnit.SECONDS, checkConnection(sessionFactory));
} }
catch (TimeoutException e) { catch (TimeoutException e) {
throw new IllegalStateException(); throw new IllegalStateException();

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,13 +16,10 @@
package org.springframework.boot.test.autoconfigure.data.neo4j; package org.springframework.boot.test.autoconfigure.data.neo4j;
import java.util.function.Supplier;
import org.junit.ClassRule; import org.junit.ClassRule;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.testcontainers.containers.FixedHostPortGenericContainer; import org.testcontainers.containers.FixedHostPortGenericContainer;
import org.testcontainers.containers.GenericContainer;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.DockerTestContainer; import org.springframework.boot.test.autoconfigure.DockerTestContainer;
@ -42,9 +39,12 @@ import static org.assertj.core.api.Assertions.assertThat;
public class DataNeo4jTestWithIncludeFilterIntegrationTests { public class DataNeo4jTestWithIncludeFilterIntegrationTests {
@ClassRule @ClassRule
public static DockerTestContainer<GenericContainer> genericContainer = new DockerTestContainer<>((Supplier<GenericContainer>) () -> new FixedHostPortGenericContainer("neo4j:latest") public static DockerTestContainer<FixedHostPortGenericContainer<?>> neo4j = new DockerTestContainer<>(
() -> new FixedHostPortGenericContainer<>("neo4j:latest")
.withFixedExposedPort(7687, 7687) .withFixedExposedPort(7687, 7687)
.waitingFor(new DataNeo4jTestIntegrationTests.ConnectionVerifyingWaitStrategy()).withEnv("NEO4J_AUTH", "none")); .waitingFor(
new DataNeo4jTestIntegrationTests.ConnectionVerifyingWaitStrategy())
.withEnv("NEO4J_AUTH", "none"));
@Autowired @Autowired
private ExampleService service; private ExampleService service;

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -46,8 +46,8 @@ import static org.assertj.core.api.Assertions.assertThat;
public class DataRedisTestIntegrationTests { public class DataRedisTestIntegrationTests {
@ClassRule @ClassRule
public static DockerTestContainer<FixedHostPortGenericContainer> redis = new DockerTestContainer<>(() -> public static DockerTestContainer<FixedHostPortGenericContainer<?>> redis = new DockerTestContainer<>(
new FixedHostPortGenericContainer("redis:latest") () -> new FixedHostPortGenericContainer<>("redis:latest")
.withFixedExposedPort(6379, 6379)); .withFixedExposedPort(6379, 6379));
@Rule @Rule

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -39,8 +39,8 @@ import static org.assertj.core.api.Assertions.assertThat;
public class DataRedisTestWithIncludeFilterIntegrationTests { public class DataRedisTestWithIncludeFilterIntegrationTests {
@ClassRule @ClassRule
public static DockerTestContainer<FixedHostPortGenericContainer> redis = new DockerTestContainer<>(() -> public static DockerTestContainer<FixedHostPortGenericContainer<?>> redis = new DockerTestContainer<>(
new FixedHostPortGenericContainer("redis:latest") () -> new FixedHostPortGenericContainer<>("redis:latest")
.withFixedExposedPort(6379, 6379)); .withFixedExposedPort(6379, 6379));
@Autowired @Autowired

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2017 the original author or authors. * Copyright 2012-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -422,8 +422,9 @@ public class ConfigFileApplicationListener
} }
private boolean canLoadFileExtension(PropertySourceLoader loader, String name) { private boolean canLoadFileExtension(PropertySourceLoader loader, String name) {
return Arrays.stream(loader.getFileExtensions()).anyMatch( return Arrays.stream(loader.getFileExtensions())
fileExtension -> StringUtils.endsWithIgnoreCase(name, fileExtension)); .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name,
fileExtension));
} }
private void loadForFileExtension(PropertySourceLoader loader, Profile profile, private void loadForFileExtension(PropertySourceLoader loader, Profile profile,

Loading…
Cancel
Save