This commit is contained in:
Andy Wilkinson
2017-09-27 16:37:24 +01:00
parent bd1bd6bf64
commit 7e2d7dcd1d
16 changed files with 474 additions and 405 deletions

View File

@@ -115,7 +115,8 @@ public class EnvironmentEndpoint {
Map<String, PropertyValueDescriptor> descriptors) {
List<PropertySourceEntryDescriptor> result = new ArrayList<>();
for (Map.Entry<String, PropertyValueDescriptor> entry : descriptors.entrySet()) {
result.add(new PropertySourceEntryDescriptor(entry.getKey(), entry.getValue()));
result.add(
new PropertySourceEntryDescriptor(entry.getKey(), entry.getValue()));
}
return result;
}
@@ -135,9 +136,11 @@ public class EnvironmentEndpoint {
String propertyName) {
Map<String, PropertyValueDescriptor> propertySources = new LinkedHashMap<>();
PlaceholdersResolver resolver = getResolver();
getPropertySourcesAsMap().forEach((sourceName, source) ->
propertySources.put(sourceName, source.containsProperty(propertyName) ?
describeValueOf(propertyName, source, resolver) : null));
getPropertySourcesAsMap()
.forEach((sourceName, source) -> propertySources.put(sourceName,
source.containsProperty(propertyName)
? describeValueOf(propertyName, source, resolver)
: null));
return propertySources;
}
@@ -150,8 +153,8 @@ public class EnvironmentEndpoint {
return new PropertySourceDescriptor(sourceName, properties);
}
private PropertyValueDescriptor describeValueOf(String name,
PropertySource<?> source, PlaceholdersResolver resolver) {
private PropertyValueDescriptor describeValueOf(String name, PropertySource<?> source,
PlaceholdersResolver resolver) {
Object resolved = resolver.resolvePlaceholders(source.getProperty(name));
@SuppressWarnings("unchecked")
String origin = (source instanceof OriginLookup)
@@ -160,8 +163,8 @@ public class EnvironmentEndpoint {
}
private PlaceholdersResolver getResolver() {
return new PropertySourcesPlaceholdersSanitizingResolver(
getPropertySources(), this.sanitizer);
return new PropertySourcesPlaceholdersSanitizingResolver(getPropertySources(),
this.sanitizer);
}
private Map<String, PropertySource<?>> getPropertySourcesAsMap() {
@@ -211,20 +214,20 @@ public class EnvironmentEndpoint {
private final Sanitizer sanitizer;
PropertySourcesPlaceholdersSanitizingResolver(
Iterable<PropertySource<?>> sources, Sanitizer sanitizer) {
super(sources, new PropertyPlaceholderHelper(
SystemPropertyUtils.PLACEHOLDER_PREFIX,
SystemPropertyUtils.PLACEHOLDER_SUFFIX,
SystemPropertyUtils.VALUE_SEPARATOR, true));
PropertySourcesPlaceholdersSanitizingResolver(Iterable<PropertySource<?>> sources,
Sanitizer sanitizer) {
super(sources,
new PropertyPlaceholderHelper(SystemPropertyUtils.PLACEHOLDER_PREFIX,
SystemPropertyUtils.PLACEHOLDER_SUFFIX,
SystemPropertyUtils.VALUE_SEPARATOR, true));
this.sanitizer = sanitizer;
}
@Override
protected String resolvePlaceholder(String placeholder) {
String value = super.resolvePlaceholder(placeholder);
return (value != null ?
(String) this.sanitizer.sanitize(placeholder, value) : null);
return (value != null ? (String) this.sanitizer.sanitize(placeholder, value)
: null);
}
}

View File

@@ -60,10 +60,10 @@ public class EnvironmentEndpointTests {
@Test
public void basicResponse() {
ConfigurableEnvironment environment = emptyEnvironment();
environment.getPropertySources().addLast(
singleKeyPropertySource("one", "my.key", "first"));
environment.getPropertySources().addLast(
singleKeyPropertySource("two", "my.key", "second"));
environment.getPropertySources()
.addLast(singleKeyPropertySource("one", "my.key", "first"));
environment.getPropertySources()
.addLast(singleKeyPropertySource("two", "my.key", "second"));
EnvironmentDescriptor descriptor = new EnvironmentEndpoint(environment)
.environment(null);
assertThat(descriptor.getActiveProfiles()).isEmpty();
@@ -94,20 +94,26 @@ public class EnvironmentEndpointTests {
@Test
public void sensitiveKeysHaveTheirValuesSanitized() {
TestPropertyValues.of("dbPassword=123456", "apiKey=123456", "mySecret=123456",
"myCredentials=123456", "VCAP_SERVICES=123456"
).applyToSystemProperties(() -> {
EnvironmentDescriptor descriptor = new EnvironmentEndpoint(
new StandardEnvironment()).environment(null);
Map<String, PropertyValueDescriptor> systemProperties = propertySources(
descriptor).get("systemProperties").getProperties();
assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo("******");
assertThat(systemProperties.get("apiKey").getValue()).isEqualTo("******");
assertThat(systemProperties.get("mySecret").getValue()).isEqualTo("******");
assertThat(systemProperties.get("myCredentials").getValue()).isEqualTo("******");
assertThat(systemProperties.get("VCAP_SERVICES").getValue()).isEqualTo("******");
return null;
});
TestPropertyValues
.of("dbPassword=123456", "apiKey=123456", "mySecret=123456",
"myCredentials=123456", "VCAP_SERVICES=123456")
.applyToSystemProperties(() -> {
EnvironmentDescriptor descriptor = new EnvironmentEndpoint(
new StandardEnvironment()).environment(null);
Map<String, PropertyValueDescriptor> systemProperties = propertySources(
descriptor).get("systemProperties").getProperties();
assertThat(systemProperties.get("dbPassword").getValue())
.isEqualTo("******");
assertThat(systemProperties.get("apiKey").getValue())
.isEqualTo("******");
assertThat(systemProperties.get("mySecret").getValue())
.isEqualTo("******");
assertThat(systemProperties.get("myCredentials").getValue())
.isEqualTo("******");
assertThat(systemProperties.get("VCAP_SERVICES").getValue())
.isEqualTo("******");
return null;
});
}
@Test
@@ -116,52 +122,59 @@ public class EnvironmentEndpointTests {
"credentials.http_api_uri=123456",
"my.services.cleardb-free.credentials=123456",
"foo.mycredentials.uri=123456").applyToSystemProperties(() -> {
EnvironmentDescriptor descriptor = new EnvironmentEndpoint(
new StandardEnvironment()).environment(null);
Map<String, PropertyValueDescriptor> systemProperties = propertySources(
descriptor).get("systemProperties").getProperties();
assertThat(
systemProperties.get("my.services.amqp-free.credentials.uri").getValue())
.isEqualTo("******");
assertThat(systemProperties.get("credentials.http_api_uri").getValue())
.isEqualTo("******");
assertThat(
systemProperties.get("my.services.cleardb-free.credentials").getValue())
.isEqualTo("******");
assertThat(systemProperties.get("foo.mycredentials.uri").getValue())
.isEqualTo("******");
return null;
});
EnvironmentDescriptor descriptor = new EnvironmentEndpoint(
new StandardEnvironment()).environment(null);
Map<String, PropertyValueDescriptor> systemProperties = propertySources(
descriptor).get("systemProperties").getProperties();
assertThat(systemProperties
.get("my.services.amqp-free.credentials.uri").getValue())
.isEqualTo("******");
assertThat(
systemProperties.get("credentials.http_api_uri").getValue())
.isEqualTo("******");
assertThat(systemProperties
.get("my.services.cleardb-free.credentials").getValue())
.isEqualTo("******");
assertThat(systemProperties.get("foo.mycredentials.uri").getValue())
.isEqualTo("******");
return null;
});
}
@Test
public void sensitiveKeysMatchingCustomNameHaveTheirValuesSanitized() {
TestPropertyValues.of("dbPassword=123456",
"apiKey=123456").applyToSystemProperties(() -> {
EnvironmentEndpoint endpoint = new EnvironmentEndpoint(new StandardEnvironment());
endpoint.setKeysToSanitize("key");
EnvironmentDescriptor descriptor = endpoint.environment(null);
Map<String, PropertyValueDescriptor> systemProperties = propertySources(
descriptor).get("systemProperties").getProperties();
assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo("123456");
assertThat(systemProperties.get("apiKey").getValue()).isEqualTo("******");
return null;
});
TestPropertyValues.of("dbPassword=123456", "apiKey=123456")
.applyToSystemProperties(() -> {
EnvironmentEndpoint endpoint = new EnvironmentEndpoint(
new StandardEnvironment());
endpoint.setKeysToSanitize("key");
EnvironmentDescriptor descriptor = endpoint.environment(null);
Map<String, PropertyValueDescriptor> systemProperties = propertySources(
descriptor).get("systemProperties").getProperties();
assertThat(systemProperties.get("dbPassword").getValue())
.isEqualTo("123456");
assertThat(systemProperties.get("apiKey").getValue())
.isEqualTo("******");
return null;
});
}
@Test
public void sensitiveKeysMatchingCustomPatternHaveTheirValuesSanitized() {
TestPropertyValues.of("dbPassword=123456",
"apiKey=123456").applyToSystemProperties(() -> {
EnvironmentEndpoint endpoint = new EnvironmentEndpoint(new StandardEnvironment());
endpoint.setKeysToSanitize(".*pass.*");
EnvironmentDescriptor descriptor = endpoint.environment(null);
Map<String, PropertyValueDescriptor> systemProperties = propertySources(
descriptor).get("systemProperties").getProperties();
assertThat(systemProperties.get("dbPassword").getValue()).isEqualTo("******");
assertThat(systemProperties.get("apiKey").getValue()).isEqualTo("123456");
return null;
});
TestPropertyValues.of("dbPassword=123456", "apiKey=123456")
.applyToSystemProperties(() -> {
EnvironmentEndpoint endpoint = new EnvironmentEndpoint(
new StandardEnvironment());
endpoint.setKeysToSanitize(".*pass.*");
EnvironmentDescriptor descriptor = endpoint.environment(null);
Map<String, PropertyValueDescriptor> systemProperties = propertySources(
descriptor).get("systemProperties").getProperties();
assertThat(systemProperties.get("dbPassword").getValue())
.isEqualTo("******");
assertThat(systemProperties.get("apiKey").getValue())
.isEqualTo("123456");
return null;
});
}
@Test
@@ -233,12 +246,15 @@ public class EnvironmentEndpointTests {
assertThat(descriptor.getProperty()).isNotNull();
assertThat(descriptor.getProperty().getSource()).isEqualTo("test");
assertThat(descriptor.getProperty().getValue()).isEqualTo("bar");
Map<String, PropertySourceEntryDescriptor> sources = propertySources(descriptor);
assertThat(sources.keySet()).containsExactly(
"test", "systemProperties", "systemEnvironment");
Map<String, PropertySourceEntryDescriptor> sources = propertySources(
descriptor);
assertThat(sources.keySet()).containsExactly("test", "systemProperties",
"systemEnvironment");
assertPropertySourceEntryDescriptor(sources.get("test"), "bar", null);
assertPropertySourceEntryDescriptor(sources.get("systemProperties"), "another", null);
assertPropertySourceEntryDescriptor(sources.get("systemEnvironment"), null, null);
assertPropertySourceEntryDescriptor(sources.get("systemProperties"),
"another", null);
assertPropertySourceEntryDescriptor(sources.get("systemEnvironment"), null,
null);
return null;
});
}
@@ -246,42 +262,42 @@ public class EnvironmentEndpointTests {
@Test
public void propertyEntryNotFound() {
ConfigurableEnvironment environment = emptyEnvironment();
environment.getPropertySources().addFirst(
singleKeyPropertySource("test", "foo", "bar"));
environment.getPropertySources()
.addFirst(singleKeyPropertySource("test", "foo", "bar"));
EnvironmentEntryDescriptor descriptor = new EnvironmentEndpoint(environment)
.environmentEntry("does.not.exist");
assertThat(descriptor).isNotNull();
assertThat(descriptor.getProperty()).isNull();
Map<String, PropertySourceEntryDescriptor> sources = propertySources(descriptor);
assertThat(sources.keySet()).containsExactly(
"test");
assertThat(sources.keySet()).containsExactly("test");
assertPropertySourceEntryDescriptor(sources.get("test"), null, null);
}
private static ConfigurableEnvironment emptyEnvironment() {
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().remove(
StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
environment.getPropertySources().remove(
StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
environment.getPropertySources()
.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
environment.getPropertySources()
.remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
return environment;
}
private MapPropertySource singleKeyPropertySource(String name, String key, Object value) {
private MapPropertySource singleKeyPropertySource(String name, String key,
Object value) {
return new MapPropertySource(name, Collections.singletonMap(key, value));
}
private Map<String, PropertySourceDescriptor> propertySources(
EnvironmentDescriptor descriptor) {
Map<String, PropertySourceDescriptor> sources = new LinkedHashMap<>();
descriptor.getPropertySources().forEach(d -> sources.put(d.getName(), d));
descriptor.getPropertySources().forEach((d) -> sources.put(d.getName(), d));
return sources;
}
private Map<String, PropertySourceEntryDescriptor> propertySources(
EnvironmentEntryDescriptor descriptor) {
Map<String, PropertySourceEntryDescriptor> sources = new LinkedHashMap<>();
descriptor.getPropertySources().forEach(d -> sources.put(d.getName(), d));
descriptor.getPropertySources().forEach((d) -> sources.put(d.getName(), d));
return sources;
}

View File

@@ -53,8 +53,7 @@ public class EnvironmentEndpointWebIntegrationTests {
@Test
public void sub() throws Exception {
client.get().uri("/application/env/foo").exchange().expectStatus().isOk()
.expectBody()
.jsonPath("property.source").isEqualTo("test")
.expectBody().jsonPath("property.source").isEqualTo("test")
.jsonPath("property.value").isEqualTo("bar");
}
@@ -77,10 +76,9 @@ public class EnvironmentEndpointWebIntegrationTests {
context.getEnvironment().getPropertySources()
.addFirst(new MapPropertySource("unresolved-placeholder", map));
client.get().uri("/application/env/my.foo").exchange().expectStatus().isOk()
.expectBody()
.jsonPath("property.value").isEqualTo("${my.bar}")
.jsonPath(forPropertyEntry(
"unresolved-placeholder")).isEqualTo("${my.bar}");
.expectBody().jsonPath("property.value").isEqualTo("${my.bar}")
.jsonPath(forPropertyEntry("unresolved-placeholder"))
.isEqualTo("${my.bar}");
}
@Test
@@ -91,17 +89,14 @@ public class EnvironmentEndpointWebIntegrationTests {
context.getEnvironment().getPropertySources()
.addFirst(new MapPropertySource("placeholder", map));
client.get().uri("/application/env/my.foo").exchange().expectStatus().isOk()
.expectBody()
.jsonPath("property.value").isEqualTo("******")
.expectBody().jsonPath("property.value").isEqualTo("******")
.jsonPath(forPropertyEntry("placeholder")).isEqualTo("******");
}
@Test
public void nestedPathForUnknownKeyShouldReturn404AndBody() throws Exception {
client.get().uri("/application/env/this.does.not.exist").exchange().expectStatus()
.isNotFound()
.expectBody()
.jsonPath("property").doesNotExist()
.isNotFound().expectBody().jsonPath("property").doesNotExist()
.jsonPath("propertySources[?(@.name=='test')]").exists()
.jsonPath("propertySources[?(@.name=='systemProperties')]").exists()
.jsonPath("propertySources[?(@.name=='systemEnvironment')]").exists();

View File

@@ -33,17 +33,18 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsRepository;
/**
* Default user {@link Configuration} for a reactive web application.
* Configures a {@link UserDetailsRepository} with a default user and generated password.
* This backs-off completely if there is a bean of type {@link UserDetailsRepository}
* or {@link ReactiveAuthenticationManager}.
* Default user {@link Configuration} for a reactive web application. Configures a
* {@link UserDetailsRepository} with a default user and generated password. This
* backs-off completely if there is a bean of type {@link UserDetailsRepository} or
* {@link ReactiveAuthenticationManager}.
*
* @author Madhura Bhave
* @since 2.0.0
*/
@Configuration
@ConditionalOnClass({ReactiveAuthenticationManager.class})
@ConditionalOnMissingBean({ReactiveAuthenticationManager.class, UserDetailsRepository.class })
@ConditionalOnClass({ ReactiveAuthenticationManager.class })
@ConditionalOnMissingBean({ ReactiveAuthenticationManager.class,
UserDetailsRepository.class })
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class ReactiveAuthenticationManagerConfiguration {
@@ -53,12 +54,8 @@ public class ReactiveAuthenticationManagerConfiguration {
@Bean
public MapUserDetailsRepository userDetailsRepository() {
String password = UUID.randomUUID().toString();
logger.info(
String.format("%n%nUsing default security password: %s%n", password));
UserDetails user = User.withUsername("user")
.password(password)
.roles()
.build();
logger.info(String.format("%n%nUsing default security password: %s%n", password));
UserDetails user = User.withUsername("user").password(password).roles().build();
return new MapUserDetailsRepository(user);
}
}

View File

@@ -24,16 +24,17 @@ import org.springframework.security.config.annotation.web.reactive.EnableWebFlux
import org.springframework.security.web.reactive.result.method.annotation.AuthenticationPrincipalArgumentResolver;
/**
* {@link EnableAutoConfiguration Auto-configuration} for Spring Security in a
* reactive application. This auto-configuration adds {@link EnableWebFluxSecurity}
* and delegates to Spring Security's content-negotiation mechanism for authentication.
* In a webapp this configuration also secures all web endpoints.
* {@link EnableAutoConfiguration Auto-configuration} for Spring Security in a reactive
* application. This auto-configuration adds {@link EnableWebFluxSecurity} and delegates
* to Spring Security's content-negotiation mechanism for authentication. In a webapp this
* configuration also secures all web endpoints.
*
* @author Madhura Bhave
* @since 2.0.0
*/
@Configuration
@ConditionalOnClass({EnableWebFluxSecurity.class, AuthenticationPrincipalArgumentResolver.class})
@ConditionalOnClass({ EnableWebFluxSecurity.class,
AuthenticationPrincipalArgumentResolver.class })
@Import({ WebfluxSecurityConfiguration.class,
ReactiveAuthenticationManagerConfiguration.class })
public class ReactiveSecurityAutoConfiguration {

View File

@@ -23,8 +23,8 @@ import org.springframework.security.config.annotation.web.reactive.EnableWebFlux
import org.springframework.security.config.annotation.web.reactive.WebFluxSecurityConfiguration;
/**
* Switches on {@link EnableWebFluxSecurity} for a reactive web application
* if this annotation has not been added by the user.
* Switches on {@link EnableWebFluxSecurity} for a reactive web application if this
* annotation has not been added by the user.
*
* @author Madhura Bhave
* @since 2.0.0

View File

@@ -120,7 +120,8 @@ public class WebServicesAutoConfiguration {
Bindable.listOf(String.class))
.orElse(Collections.emptyList());
for (String wsdlLocation : wsdlLocations) {
registerBeans(wsdlLocation, "*.wsdl", SimpleWsdl11Definition.class, registry);
registerBeans(wsdlLocation, "*.wsdl", SimpleWsdl11Definition.class,
registry);
registerBeans(wsdlLocation, "*.xsd", SimpleXsdSchema.class, registry);
}
}

View File

@@ -70,59 +70,62 @@ public class FlywayAutoConfigurationTests {
@Test
public void noDataSource() {
this.contextRunner.run((context) ->
assertThat(context).doesNotHaveBean(Flyway.class));
this.contextRunner
.run((context) -> assertThat(context).doesNotHaveBean(Flyway.class));
}
@Test
public void createDataSource() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues(
"spring.flyway.url:jdbc:hsqldb:mem:flywaytest",
"spring.flyway.user:sa").run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
assertThat(context.getBean(Flyway.class).getDataSource()).isNotNull();
});
.withPropertyValues("spring.flyway.url:jdbc:hsqldb:mem:flywaytest",
"spring.flyway.user:sa")
.run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
assertThat(context.getBean(Flyway.class).getDataSource()).isNotNull();
});
}
@Test
public void flywayDataSource() {
this.contextRunner.withUserConfiguration(FlywayDataSourceConfiguration.class,
EmbeddedDataSourceConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
assertThat(context.getBean(Flyway.class).getDataSource())
.isEqualTo(context.getBean("flywayDataSource"));
});
assertThat(context).hasSingleBean(Flyway.class);
assertThat(context.getBean(Flyway.class).getDataSource())
.isEqualTo(context.getBean("flywayDataSource"));
});
}
@Test
public void schemaManagementProviderDetectsDataSource() {
this.contextRunner.withUserConfiguration(FlywayDataSourceConfiguration.class,
EmbeddedDataSourceConfiguration.class).run((context) -> {
FlywaySchemaManagementProvider schemaManagementProvider = context
.getBean(FlywaySchemaManagementProvider.class);
assertThat(schemaManagementProvider.getSchemaManagement(context.getBean(
DataSource.class))).isEqualTo(SchemaManagement.UNMANAGED);
assertThat(schemaManagementProvider.getSchemaManagement(context.getBean(
"flywayDataSource", DataSource.class))).isEqualTo(
SchemaManagement.MANAGED);
});
FlywaySchemaManagementProvider schemaManagementProvider = context
.getBean(FlywaySchemaManagementProvider.class);
assertThat(schemaManagementProvider
.getSchemaManagement(context.getBean(DataSource.class)))
.isEqualTo(SchemaManagement.UNMANAGED);
assertThat(schemaManagementProvider.getSchemaManagement(
context.getBean("flywayDataSource", DataSource.class)))
.isEqualTo(SchemaManagement.MANAGED);
});
}
@Test
public void defaultFlyway() {
this.contextRunner.withUserConfiguration(
EmbeddedDataSourceConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
assertThat(flyway.getLocations()).containsExactly("classpath:db/migration");
});
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
assertThat(flyway.getLocations())
.containsExactly("classpath:db/migration");
});
}
@Test
public void overrideLocations() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.flyway.locations:classpath:db/changelog,classpath:db/migration")
.withPropertyValues(
"spring.flyway.locations:classpath:db/changelog,classpath:db/migration")
.run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
@@ -140,8 +143,7 @@ public class FlywayAutoConfigurationTests {
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
assertThat(flyway.getLocations()).containsExactly(
"classpath:db/changelog",
"classpath:db/migration");
"classpath:db/changelog", "classpath:db/migration");
});
}
@@ -149,11 +151,11 @@ public class FlywayAutoConfigurationTests {
public void overrideSchemas() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.flyway.schemas:public").run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
assertThat(Arrays.asList(flyway.getSchemas()).toString())
.isEqualTo("[public]");
});
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
assertThat(Arrays.asList(flyway.getSchemas()).toString())
.isEqualTo("[public]");
});
}
@Test
@@ -172,13 +174,14 @@ public class FlywayAutoConfigurationTests {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues(
"spring.flyway.locations:classpath:db/missing1,classpath:db/migration2",
"spring.flyway.check-location:true").run((context) -> {
assertThat(context).hasFailed();
assertThat(context).getFailure()
.isInstanceOf(BeanCreationException.class);
assertThat(context).getFailure()
.hasMessageContaining("Cannot find migrations location in");
});
"spring.flyway.check-location:true")
.run((context) -> {
assertThat(context).hasFailed();
assertThat(context).getFailure()
.isInstanceOf(BeanCreationException.class);
assertThat(context).getFailure()
.hasMessageContaining("Cannot find migrations location in");
});
}
@Test
@@ -186,43 +189,43 @@ public class FlywayAutoConfigurationTests {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues(
"spring.flyway.locations:classpath:db/changelog,classpath:db/migration",
"spring.flyway.check-location:true").run((context) -> {
assertThat(context).hasNotFailed();
});
"spring.flyway.check-location:true")
.run((context) -> assertThat(context).hasNotFailed());
}
@Test
public void customFlywayMigrationStrategy() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class,
MockFlywayMigrationStrategy.class).run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
context.getBean(MockFlywayMigrationStrategy.class).assertCalled();
});
assertThat(context).hasSingleBean(Flyway.class);
context.getBean(MockFlywayMigrationStrategy.class).assertCalled();
});
}
@Test
public void customFlywayMigrationInitializer() throws Exception {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class,
CustomFlywayMigrationInitializer.class).run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
FlywayMigrationInitializer initializer = context.getBean(
FlywayMigrationInitializer.class);
assertThat(initializer.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE);
});
assertThat(context).hasSingleBean(Flyway.class);
FlywayMigrationInitializer initializer = context
.getBean(FlywayMigrationInitializer.class);
assertThat(initializer.getOrder())
.isEqualTo(Ordered.HIGHEST_PRECEDENCE);
});
}
@Test
public void customFlywayWithJpa() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class,
CustomFlywayWithJpaConfiguration.class).run((context) ->
assertThat(context).hasNotFailed());
this.contextRunner
.withUserConfiguration(EmbeddedDataSourceConfiguration.class,
CustomFlywayWithJpaConfiguration.class)
.run((context) -> assertThat(context).hasNotFailed());
}
@Test
public void overrideBaselineVersionString() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.flyway.baseline-version=0")
.run((context) -> {
.withPropertyValues("spring.flyway.baseline-version=0").run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
assertThat(flyway.getBaselineVersion())
@@ -233,8 +236,7 @@ public class FlywayAutoConfigurationTests {
@Test
public void overrideBaselineVersionNumber() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.flyway.baseline-version=1")
.run((context) -> {
.withPropertyValues("spring.flyway.baseline-version=1").run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
assertThat(flyway.getBaselineVersion())
@@ -245,7 +247,8 @@ public class FlywayAutoConfigurationTests {
@Test
public void useVendorDirectory() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog")
.withPropertyValues(
"spring.flyway.locations=classpath:db/vendors/{vendor},classpath:db/changelog")
.run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
@@ -258,19 +261,23 @@ public class FlywayAutoConfigurationTests {
public void callbacksAreConfiguredAndOrdered() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class,
CallbackConfiguration.class).run((context) -> {
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
FlywayCallback callbackOne = context.getBean("callbackOne",
FlywayCallback.class);
FlywayCallback callbackTwo = context.getBean("callbackTwo",
FlywayCallback.class);
assertThat(flyway.getCallbacks()).hasSize(3);
assertThat(flyway.getCallbacks()).startsWith(callbackTwo, callbackOne);
assertThat(flyway.getCallbacks()[2]).isInstanceOf(SqlScriptFlywayCallback.class);
InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo);
orderedCallbacks.verify(callbackTwo).beforeMigrate(any(Connection.class));
orderedCallbacks.verify(callbackOne).beforeMigrate(any(Connection.class));
});
assertThat(context).hasSingleBean(Flyway.class);
Flyway flyway = context.getBean(Flyway.class);
FlywayCallback callbackOne = context.getBean("callbackOne",
FlywayCallback.class);
FlywayCallback callbackTwo = context.getBean("callbackTwo",
FlywayCallback.class);
assertThat(flyway.getCallbacks()).hasSize(3);
assertThat(flyway.getCallbacks()).startsWith(callbackTwo,
callbackOne);
assertThat(flyway.getCallbacks()[2])
.isInstanceOf(SqlScriptFlywayCallback.class);
InOrder orderedCallbacks = inOrder(callbackOne, callbackTwo);
orderedCallbacks.verify(callbackTwo)
.beforeMigrate(any(Connection.class));
orderedCallbacks.verify(callbackOne)
.beforeMigrate(any(Connection.class));
});
}
@Configuration

View File

@@ -67,207 +67,232 @@ public class DataSourceInitializerTests {
@Test
public void defaultDataSourceDoesNotExists() {
this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(
DataSource.class));
this.contextRunner
.run((context) -> assertThat(context).doesNotHaveBean(DataSource.class));
}
@Test
public void twoDataSources() {
this.contextRunner.withUserConfiguration(TwoDataSources.class)
.withPropertyValues("datasource.one.url=jdbc:hsqldb:mem:/one",
"datasource.two.url=jdbc:hsqldb:mem:/two").run((context) ->
assertThat(context.getBeanNamesForType(DataSource.class)).hasSize(2));
"datasource.two.url=jdbc:hsqldb:mem:/two")
.run((context) -> assertThat(
context.getBeanNamesForType(DataSource.class)).hasSize(2));
}
@Test
public void dataSourceInitialized() {
this.contextRunner.withConfiguration(AutoConfigurations.of(
DataSourceAutoConfiguration.class)
).withPropertyValues("spring.datasource.initialize:true").run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class))
.isEqualTo(1);
});
this.contextRunner
.withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.initialize:true")
.run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
assertThat(template.queryForObject("SELECT COUNT(*) from BAR",
Integer.class)).isEqualTo(1);
});
}
@Test
public void dataSourceInitializedWithExplicitScript() {
this.contextRunner.withConfiguration(AutoConfigurations.of(
DataSourceAutoConfiguration.class)
).withPropertyValues(
"spring.datasource.initialize:true",
"spring.datasource.schema:" + getRelativeLocationFor("schema.sql"),
"spring.datasource.data:" + getRelativeLocationFor("data.sql")
).run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class))
.isEqualTo(1);
});
this.contextRunner
.withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.schema:"
+ getRelativeLocationFor("schema.sql"),
"spring.datasource.data:" + getRelativeLocationFor("data.sql"))
.run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
assertThat(template.queryForObject("SELECT COUNT(*) from FOO",
Integer.class)).isEqualTo(1);
});
}
@Test
public void dataSourceInitializedWithMultipleScripts() {
this.contextRunner.withConfiguration(AutoConfigurations.of(
DataSourceAutoConfiguration.class)
).withPropertyValues(
"spring.datasource.initialize:true",
"spring.datasource.schema:" + getRelativeLocationFor("schema.sql") + ","
+ getRelativeLocationFor("another.sql"),
"spring.datasource.data:" + getRelativeLocationFor("data.sql")
).run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class))
.isEqualTo(1);
assertThat(template.queryForObject("SELECT COUNT(*) from SPAM", Integer.class))
.isEqualTo(0);
});
this.contextRunner
.withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.schema:" + getRelativeLocationFor("schema.sql")
+ "," + getRelativeLocationFor("another.sql"),
"spring.datasource.data:" + getRelativeLocationFor("data.sql"))
.run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
assertThat(template.queryForObject("SELECT COUNT(*) from FOO",
Integer.class)).isEqualTo(1);
assertThat(template.queryForObject("SELECT COUNT(*) from SPAM",
Integer.class)).isEqualTo(0);
});
}
@Test
public void dataSourceInitializedWithExplicitSqlScriptEncoding() {
this.contextRunner.withConfiguration(AutoConfigurations.of(
DataSourceAutoConfiguration.class)
).withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.sqlScriptEncoding:UTF-8",
"spring.datasource.schema:" + getRelativeLocationFor("encoding-schema.sql"),
"spring.datasource.data:" + getRelativeLocationFor("encoding-data.sql")
).run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class))
.isEqualTo(2);
assertThat(template.queryForObject(
"SELECT name from BAR WHERE id=1", String.class)).isEqualTo("bar");
assertThat(template.queryForObject(
"SELECT name from BAR WHERE id=2", String.class)).isEqualTo("ばー");
});
this.contextRunner
.withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.sqlScriptEncoding:UTF-8",
"spring.datasource.schema:"
+ getRelativeLocationFor("encoding-schema.sql"),
"spring.datasource.data:"
+ getRelativeLocationFor("encoding-data.sql"))
.run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
assertThat(template.queryForObject("SELECT COUNT(*) from BAR",
Integer.class)).isEqualTo(2);
assertThat(template.queryForObject("SELECT name from BAR WHERE id=1",
String.class)).isEqualTo("bar");
assertThat(template.queryForObject("SELECT name from BAR WHERE id=2",
String.class)).isEqualTo("ばー");
});
}
@Test
public void initializationDisabled() {
this.contextRunner.withConfiguration(AutoConfigurations.of(
DataSourceAutoConfiguration.class)).run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
context.publishEvent(new DataSourceInitializedEvent(dataSource));
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
try {
template.queryForObject("SELECT COUNT(*) from BAR", Integer.class);
fail("Query should have failed as BAR table does not exist");
}
catch (BadSqlGrammarException ex) {
SQLException sqlException = ex.getSQLException();
int expectedCode = -5501; // user lacks privilege or object not found
assertThat(sqlException.getErrorCode()).isEqualTo(expectedCode);
}
});
this.contextRunner
.withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class))
.run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
context.publishEvent(new DataSourceInitializedEvent(dataSource));
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
try {
template.queryForObject("SELECT COUNT(*) from BAR",
Integer.class);
fail("Query should have failed as BAR table does not exist");
}
catch (BadSqlGrammarException ex) {
SQLException sqlException = ex.getSQLException();
int expectedCode = -5501; // user lacks privilege or object not
// found
assertThat(sqlException.getErrorCode()).isEqualTo(expectedCode);
}
});
}
@Test
public void dataSourceInitializedWithSchemaCredentials() {
this.contextRunner.withConfiguration(AutoConfigurations.of(
DataSourceAutoConfiguration.class)
).withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.sqlScriptEncoding:UTF-8",
"spring.datasource.schema:" + getRelativeLocationFor("encoding-schema.sql"),
"spring.datasource.data:" + getRelativeLocationFor("encoding-data.sql"),
"spring.datasource.schema-username:admin",
"spring.datasource.schema-password:admin").run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class);
});
this.contextRunner
.withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.sqlScriptEncoding:UTF-8",
"spring.datasource.schema:"
+ getRelativeLocationFor("encoding-schema.sql"),
"spring.datasource.data:"
+ getRelativeLocationFor("encoding-data.sql"),
"spring.datasource.schema-username:admin",
"spring.datasource.schema-password:admin")
.run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(BeanCreationException.class);
});
}
@Test
public void dataSourceInitializedWithDataCredentials() {
this.contextRunner.withConfiguration(AutoConfigurations.of(
DataSourceAutoConfiguration.class)
).withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.sqlScriptEncoding:UTF-8",
"spring.datasource.schema:" + getRelativeLocationFor("encoding-schema.sql"),
"spring.datasource.data:" + getRelativeLocationFor("encoding-data.sql"),
"spring.datasource.data-username:admin",
"spring.datasource.data-password:admin").run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure()).isInstanceOf(BeanCreationException.class);
});
this.contextRunner
.withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.sqlScriptEncoding:UTF-8",
"spring.datasource.schema:"
+ getRelativeLocationFor("encoding-schema.sql"),
"spring.datasource.data:"
+ getRelativeLocationFor("encoding-data.sql"),
"spring.datasource.data-username:admin",
"spring.datasource.data-password:admin")
.run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(BeanCreationException.class);
});
}
@Test
public void multipleScriptsAppliedInLexicalOrder() {
new ApplicationContextRunner(() -> {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.setResourceLoader(new ReverseOrderResourceLoader(new DefaultResourceLoader()));
context.setResourceLoader(
new ReverseOrderResourceLoader(new DefaultResourceLoader()));
return context;
}
).withUserConfiguration(BasicConfiguration.class).withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class)
).withPropertyValues("spring.datasource.initialize=false",
"spring.datasource.url:jdbc:hsqldb:mem:testdb-"
+ new Random().nextInt(),
"spring.datasource.initialize:true",
"spring.datasource.schema:" + getRelativeLocationFor("lexical-schema-*.sql"),
"spring.datasource.data:" + getRelativeLocationFor("data.sql")
).run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
assertThat(template.queryForObject("SELECT COUNT(*) from FOO", Integer.class))
.isEqualTo(1);
});
}).withUserConfiguration(BasicConfiguration.class)
.withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.initialize=false",
"spring.datasource.url:jdbc:hsqldb:mem:testdb-"
+ new Random().nextInt(),
"spring.datasource.initialize:true",
"spring.datasource.schema:"
+ getRelativeLocationFor("lexical-schema-*.sql"),
"spring.datasource.data:" + getRelativeLocationFor("data.sql"))
.run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource).isInstanceOf(HikariDataSource.class);
assertThat(dataSource).isNotNull();
JdbcOperations template = new JdbcTemplate(dataSource);
assertThat(template.queryForObject("SELECT COUNT(*) from FOO",
Integer.class)).isEqualTo(1);
});
}
@Test
public void testDataSourceInitializedWithInvalidSchemaResource() {
this.contextRunner.withConfiguration(AutoConfigurations.of(
DataSourceAutoConfiguration.class)).withPropertyValues(
"spring.datasource.initialize:true",
"spring.datasource.schema:classpath:does/not/exist.sql"
).run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(BeanCreationException.class);
assertThat(context.getStartupFailure())
.hasMessageContaining("does/not/exist.sql");
assertThat(context.getStartupFailure())
.hasMessageContaining("spring.datasource.schema");
});
this.contextRunner
.withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.schema:classpath:does/not/exist.sql")
.run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(BeanCreationException.class);
assertThat(context.getStartupFailure())
.hasMessageContaining("does/not/exist.sql");
assertThat(context.getStartupFailure())
.hasMessageContaining("spring.datasource.schema");
});
}
@Test
public void dataSourceInitializedWithInvalidDataResource() {
this.contextRunner.withConfiguration(AutoConfigurations.of(
DataSourceAutoConfiguration.class)
).withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.schema:" + getRelativeLocationFor("schema.sql"),
"spring.datasource.data:classpath:does/not/exist.sql").run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(BeanCreationException.class);
assertThat(context.getStartupFailure())
.hasMessageContaining("does/not/exist.sql");
assertThat(context.getStartupFailure())
.hasMessageContaining("spring.datasource.data");
});
this.contextRunner
.withConfiguration(
AutoConfigurations.of(DataSourceAutoConfiguration.class))
.withPropertyValues("spring.datasource.initialize:true",
"spring.datasource.schema:"
+ getRelativeLocationFor("schema.sql"),
"spring.datasource.data:classpath:does/not/exist.sql")
.run((context) -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(BeanCreationException.class);
assertThat(context.getStartupFailure())
.hasMessageContaining("does/not/exist.sql");
assertThat(context.getStartupFailure())
.hasMessageContaining("spring.datasource.data");
});
}
private String getRelativeLocationFor(String resource) {
return ClassUtils
.addResourcePathToPackagePath(getClass(), resource);
return ClassUtils.addResourcePathToPackagePath(getClass(), resource);
}
@Configuration

View File

@@ -76,7 +76,8 @@ public class KafkaAutoConfigurationIntegrationTests {
assertThat(listener.key).isEqualTo("foo");
assertThat(listener.received).isEqualTo("bar");
DefaultKafkaProducerFactory producerFactory = this.context.getBean(DefaultKafkaProducerFactory.class);
DefaultKafkaProducerFactory producerFactory = this.context
.getBean(DefaultKafkaProducerFactory.class);
Producer producer = producerFactory.createProducer();
assertThat(producer.partitionsFor(ADMIN_CREATED_TOPIC).size()).isEqualTo(10);
producer.close();

View File

@@ -184,8 +184,7 @@ public class KafkaAutoConfigurationTests {
"spring.kafka.admin.ssl.keystore-password=p5",
"spring.kafka.admin.ssl.truststore-location=classpath:tsLocP",
"spring.kafka.admin.ssl.truststore-password=p6");
KafkaAdmin admin = this.context
.getBean(KafkaAdmin.class);
KafkaAdmin admin = this.context.getBean(KafkaAdmin.class);
Map<String, Object> configs = admin.getConfig();
// common
assertThat(configs.get(AdminClientConfig.CLIENT_ID_CONFIG)).isEqualTo("cid");
@@ -202,7 +201,8 @@ public class KafkaAutoConfigurationTests {
.isEmpty();
assertThat(configs.get("foo.bar.baz")).isEqualTo("qux.fiz.buz");
assertThat(configs.get("fiz.buz")).isEqualTo("fix.fox");
assertThat(KafkaTestUtils.getPropertyValue(admin, "fatalIfBrokerNotAvailable", Boolean.class)).isTrue();
assertThat(KafkaTestUtils.getPropertyValue(admin, "fatalIfBrokerNotAvailable",
Boolean.class)).isTrue();
}
@SuppressWarnings("unchecked")

View File

@@ -75,8 +75,8 @@ public class LiquibaseAutoConfigurationTests {
@Test
public void noDataSource() {
this.contextRunner.run((context) ->
assertThat(context).doesNotHaveBean(SpringLiquibase.class));
this.contextRunner.run(
(context) -> assertThat(context).doesNotHaveBean(SpringLiquibase.class));
}
@Test
@@ -94,18 +94,19 @@ public class LiquibaseAutoConfigurationTests {
@Test
public void changelogXml() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.xml")
.run(assertLiquibase((liquibase) ->
assertThat(liquibase.getChangeLog()).isEqualTo(
"classpath:/db/changelog/db.changelog-override.xml")));
.withPropertyValues(
"spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.xml")
.run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog())
.isEqualTo("classpath:/db/changelog/db.changelog-override.xml")));
}
@Test
public void changelogJson() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.json")
.run(assertLiquibase((liquibase) ->
assertThat(liquibase.getChangeLog()).isEqualTo(
.withPropertyValues(
"spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.json")
.run(assertLiquibase(
(liquibase) -> assertThat(liquibase.getChangeLog()).isEqualTo(
"classpath:/db/changelog/db.changelog-override.json")));
}
@@ -114,55 +115,57 @@ public class LiquibaseAutoConfigurationTests {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues(
"spring.liquibase.change-log:classpath:/db/changelog/db.changelog-override.sql")
.run(assertLiquibase((liquibase) ->
assertThat(liquibase.getChangeLog()).isEqualTo(
"classpath:/db/changelog/db.changelog-override.sql")));
.run(assertLiquibase((liquibase) -> assertThat(liquibase.getChangeLog())
.isEqualTo("classpath:/db/changelog/db.changelog-override.sql")));
}
@Test
public void overrideContexts() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.liquibase.contexts:test, production")
.run(assertLiquibase((liquibase) ->
assertThat(liquibase.getContexts()).isEqualTo("test, production")));
.run(assertLiquibase((liquibase) -> assertThat(liquibase.getContexts())
.isEqualTo("test, production")));
}
@Test
public void overrideDefaultSchema() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.liquibase.default-schema:public")
.run(assertLiquibase((liquibase) ->
assertThat(liquibase.getDefaultSchema()).isEqualTo("public")));
.run(assertLiquibase(
(liquibase) -> assertThat(liquibase.getDefaultSchema())
.isEqualTo("public")));
}
@Test
public void overrideDropFirst() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.liquibase.drop-first:true")
.run(assertLiquibase((liquibase) ->
assertThat(liquibase.isDropFirst()).isTrue()));
.run(assertLiquibase(
(liquibase) -> assertThat(liquibase.isDropFirst()).isTrue()));
}
@Test
public void overrideDataSource() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.liquibase.url:jdbc:hsqldb:mem:liquibase",
"spring.liquibase.user:sa").run(assertLiquibase((liquibase) -> {
DataSource dataSource = liquibase.getDataSource();
assertThat(((HikariDataSource) dataSource).isClosed()).isTrue();
assertThat(((HikariDataSource) dataSource).getJdbcUrl())
.isEqualTo("jdbc:hsqldb:mem:liquibase");
}));
"spring.liquibase.user:sa")
.run(assertLiquibase((liquibase) -> {
DataSource dataSource = liquibase.getDataSource();
assertThat(((HikariDataSource) dataSource).isClosed()).isTrue();
assertThat(((HikariDataSource) dataSource).getJdbcUrl())
.isEqualTo("jdbc:hsqldb:mem:liquibase");
}));
}
@Test
public void changeLogDoesNotExist() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.liquibase.change-log:classpath:/no-such-changelog.yaml")
.withPropertyValues(
"spring.liquibase.change-log:classpath:/no-such-changelog.yaml")
.run((context) -> {
assertThat(context).hasFailed();
assertThat(context).getFailure().isInstanceOf(
BeanCreationException.class);
assertThat(context).getFailure()
.isInstanceOf(BeanCreationException.class);
});
}
@@ -172,7 +175,8 @@ public class LiquibaseAutoConfigurationTests {
.run(assertLiquibase((liquibase) -> {
Object log = ReflectionTestUtils.getField(liquibase, "log");
assertThat(log).isInstanceOf(CommonsLoggingLiquibaseLogger.class);
assertThat(this.outputCapture.toString()).doesNotContain(": liquibase:");
assertThat(this.outputCapture.toString())
.doesNotContain(": liquibase:");
}));
}
@@ -180,8 +184,8 @@ public class LiquibaseAutoConfigurationTests {
public void overrideLabels() {
this.contextRunner.withUserConfiguration(EmbeddedDataSourceConfiguration.class)
.withPropertyValues("spring.liquibase.labels:test, production")
.run(assertLiquibase((liquibase) ->
assertThat(liquibase.getLabels()).isEqualTo("test, production")));
.run(assertLiquibase((liquibase) -> assertThat(liquibase.getLabels())
.isEqualTo("test, production")));
}
@Test
@@ -205,7 +209,8 @@ public class LiquibaseAutoConfigurationTests {
"spring.liquibase.rollbackFile:" + file.getAbsolutePath())
.run((context) -> {
SpringLiquibase liquibase = context.getBean(SpringLiquibase.class);
File actualFile = (File) ReflectionTestUtils.getField(liquibase, "rollbackFile");
File actualFile = (File) ReflectionTestUtils.getField(liquibase,
"rollbackFile");
assertThat(actualFile).isEqualTo(file).exists();
String content = new String(FileCopyUtils.copyToByteArray(file));
assertThat(content).contains("DROP TABLE PUBLIC.customer;");
@@ -216,15 +221,15 @@ public class LiquibaseAutoConfigurationTests {
public void liquibaseDataSource() {
this.contextRunner.withUserConfiguration(LiquibaseDataSourceConfiguration.class,
EmbeddedDataSourceConfiguration.class).run((context) -> {
SpringLiquibase liquibase = context.getBean(SpringLiquibase.class);
assertThat(liquibase.getDataSource())
.isEqualTo(context.getBean("liquibaseDataSource"));
});
SpringLiquibase liquibase = context.getBean(SpringLiquibase.class);
assertThat(liquibase.getDataSource())
.isEqualTo(context.getBean("liquibaseDataSource"));
});
}
private ContextConsumer<AssertableApplicationContext> assertLiquibase(
Consumer<SpringLiquibase> consumer) {
return context -> {
return (context) -> {
assertThat(context).hasSingleBean(SpringLiquibase.class);
SpringLiquibase liquibase = context.getBean(SpringLiquibase.class);
consumer.accept(liquibase);

View File

@@ -49,15 +49,19 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class ReactiveSecurityAutoConfigurationTests {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner(ReactiveWebServerApplicationContext::new);
private ApplicationContextRunner contextRunner = new ApplicationContextRunner(
ReactiveWebServerApplicationContext::new);
@Test
public void enablesWebFluxSecurity() {
this.contextRunner.withUserConfiguration(TestConfig.class)
.withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class))
.run(context -> {
assertThat(context).getBean(HttpSecurityConfiguration.class).isNotNull();
assertThat(context).getBean(WebFluxSecurityConfiguration.class).isNotNull();
.withConfiguration(
AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class))
.run((context) -> {
assertThat(context).getBean(HttpSecurityConfiguration.class)
.isNotNull();
assertThat(context).getBean(WebFluxSecurityConfiguration.class)
.isNotNull();
assertThat(context).getBean(WebFilterChainFilter.class).isNotNull();
});
}
@@ -65,32 +69,42 @@ public class ReactiveSecurityAutoConfigurationTests {
@Test
public void configuresADefaultUser() {
this.contextRunner.withUserConfiguration(TestConfig.class)
.withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class))
.run(context -> {
UserDetailsRepository userDetailsRepository = context.getBean(UserDetailsRepository.class);
assertThat(userDetailsRepository.findByUsername("user").block()).isNotNull();
.withConfiguration(
AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class))
.run((context) -> {
UserDetailsRepository userDetailsRepository = context
.getBean(UserDetailsRepository.class);
assertThat(userDetailsRepository.findByUsername("user").block())
.isNotNull();
});
}
@Test
public void doesNotConfigureDefaultUserIfUserDetailsRepositoryAvailable() {
this.contextRunner.withUserConfiguration(UserConfig.class, TestConfig.class)
.withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class))
.run(context -> {
UserDetailsRepository userDetailsRepository = context.getBean(UserDetailsRepository.class);
assertThat(userDetailsRepository.findByUsername("user").block()).isNull();
assertThat(userDetailsRepository.findByUsername("foo").block()).isNotNull();
assertThat(userDetailsRepository.findByUsername("admin").block()).isNotNull();
.withConfiguration(
AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class))
.run((context) -> {
UserDetailsRepository userDetailsRepository = context
.getBean(UserDetailsRepository.class);
assertThat(userDetailsRepository.findByUsername("user").block())
.isNull();
assertThat(userDetailsRepository.findByUsername("foo").block())
.isNotNull();
assertThat(userDetailsRepository.findByUsername("admin").block())
.isNotNull();
});
}
@Test
public void doesNotConfigureDefaultUserIfAuthenticationManagerAvailable() {
this.contextRunner.withUserConfiguration(AuthenticationManagerConfig.class, TestConfig.class)
.withConfiguration(AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class))
.run(context -> {
assertThat(context).getBean(UserDetailsRepository.class).isNull();
});
this.contextRunner
.withUserConfiguration(AuthenticationManagerConfig.class,
TestConfig.class)
.withConfiguration(
AutoConfigurations.of(ReactiveSecurityAutoConfiguration.class))
.run((context) -> assertThat(context).getBean(UserDetailsRepository.class)
.isNull());
}
@Configuration
@@ -114,8 +128,10 @@ public class ReactiveSecurityAutoConfigurationTests {
@Bean
public MapUserDetailsRepository userDetailsRepository() {
UserDetails foo = User.withUsername("foo").password("foo").roles("USER").build();
UserDetails admin = User.withUsername("admin").password("admin").roles("USER", "ADMIN").build();
UserDetails foo = User.withUsername("foo").password("foo").roles("USER")
.build();
UserDetails admin = User.withUsername("admin").password("admin")
.roles("USER", "ADMIN").build();
return new MapUserDetailsRepository(foo, admin);
}

View File

@@ -96,7 +96,7 @@ public class WebServicesAutoConfigurationTests {
public void withWsdlBeans() {
this.contextRunner
.withPropertyValues("spring.webservices.wsdl-locations=classpath:/wsdl")
.run(context -> {
.run((context) -> {
assertThat(context.getBeansOfType(SimpleWsdl11Definition.class))
.hasSize(1).containsKey("service");
assertThat(context.getBeansOfType(SimpleXsdSchema.class)).hasSize(1)

View File

@@ -110,6 +110,7 @@ public class RemoteClientConfiguration implements InitializingBean {
return new HttpHeaderInterceptor(secretHeaderName, secret);
}
@Override
public void afterPropertiesSet() {
logWarnings();
}

View File

@@ -35,7 +35,8 @@ public class SecurityTestApplication {
@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager() throws Exception {
return new InMemoryUserDetailsManager(User.withUsername("user").password("secret").roles("USER").build());
return new InMemoryUserDetailsManager(
User.withUsername("user").password("secret").roles("USER").build());
}
@RestController