Ensure @AutoConfigureTestDatabase does not replace test databases

Update `@AutoConfigureTestDatabase` support so that by default test
databases are not replaced.

Fixes gh-35253
This commit is contained in:
Phillip Webb
2024-06-27 17:25:36 -07:00
parent 2e28d2642d
commit 8628f7334f
16 changed files with 654 additions and 22 deletions

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.autoconfigure.jdbc;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.autoconfigure.OverrideAutoConfiguration;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabaseDockerComposeIntegrationTests.SetupDockerCompose;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testsupport.container.DisabledIfDockerUnavailable;
import org.springframework.boot.testsupport.container.TestImage;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.TestPropertySourceUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link AutoConfigureTestDatabase} with Docker Compose.
*
* @author Phillip Webb
*/
@SpringBootTest
@ContextConfiguration(initializers = SetupDockerCompose.class)
@AutoConfigureTestDatabase
@OverrideAutoConfiguration(enabled = false)
@DisabledIfDockerUnavailable
class AutoConfigureTestDatabaseDockerComposeIntegrationTests {
@Autowired
private DataSource dataSource;
@Test
void dataSourceIsNotReplaced() {
assertThat(this.dataSource).isInstanceOf(HikariDataSource.class).isNotInstanceOf(EmbeddedDatabase.class);
}
@Configuration
@ImportAutoConfiguration(DataSourceAutoConfiguration.class)
static class Config {
}
static class SetupDockerCompose implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
try {
Path composeFile = Files.createTempFile("", "-postgres-compose");
String composeFileContent = new ClassPathResource("postgres-compose.yaml")
.getContentAsString(StandardCharsets.UTF_8)
.replace("{imageName}", TestImage.POSTGRESQL.toString());
Files.writeString(composeFile, composeFileContent);
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(applicationContext,
"spring.docker.compose.skip.in-tests=false", "spring.docker.compose.stop.command=down",
"spring.docker.compose.file=" + composeFile.toAbsolutePath().toString());
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.autoconfigure.jdbc;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.autoconfigure.OverrideAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testsupport.container.TestImage;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link AutoConfigureTestDatabase} with Testcontainers and a
* {@link DynamicPropertySource @DynamicPropertySource}.
*
* @author Phillip Webb
*/
@SpringBootTest
@AutoConfigureTestDatabase
@Testcontainers(disabledWithoutDocker = true)
@OverrideAutoConfiguration(enabled = false)
class AutoConfigureTestDatabaseDynamicPropertySourceIntegrationTests {
@Container
static PostgreSQLContainer<?> postgres = TestImage.container(PostgreSQLContainer.class);
@Autowired
private DataSource dataSource;
@DynamicPropertySource
static void jdbcProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
}
@Test
void dataSourceIsNotReplaced() {
assertThat(this.dataSource).isInstanceOf(HikariDataSource.class).isNotInstanceOf(EmbeddedDatabase.class);
}
@Configuration
@ImportAutoConfiguration(DataSourceAutoConfiguration.class)
static class Config {
}
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.autoconfigure.jdbc;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.autoconfigure.OverrideAutoConfiguration;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabaseNonTestDatabaseIntegrationTests.SetupDatabase;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testsupport.container.DisabledIfDockerUnavailable;
import org.springframework.boot.testsupport.container.TestImage;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.TestPropertySourceUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link AutoConfigureTestDatabase} with Docker Compose.
*
* @author Phillip Webb
*/
@SpringBootTest
@ContextConfiguration(initializers = SetupDatabase.class)
@AutoConfigureTestDatabase
@OverrideAutoConfiguration(enabled = false)
@DisabledIfDockerUnavailable
class AutoConfigureTestDatabaseNonTestDatabaseIntegrationTests {
@Container
static PostgreSQLContainer<?> postgres = TestImage.container(PostgreSQLContainer.class);
@Autowired
private DataSource dataSource;
@Test
void dataSourceIsReplaced() {
assertThat(this.dataSource).isInstanceOf(EmbeddedDatabase.class);
}
@Configuration
@ImportAutoConfiguration(DataSourceAutoConfiguration.class)
static class Config {
}
static class SetupDatabase implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
postgres.start();
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(applicationContext,
"spring.datasource.url=" + postgres.getJdbcUrl());
}
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.autoconfigure.jdbc;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.autoconfigure.OverrideAutoConfiguration;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.boot.testsupport.container.TestImage;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration test for {@link AutoConfigureTestDatabase} with Testcontainers and a
* {@link ServiceConnection @ServiceConnection}.
*
* @author Phillip Webb
*/
@SpringBootTest
@AutoConfigureTestDatabase(replace = Replace.NON_TEST)
@Testcontainers(disabledWithoutDocker = true)
@OverrideAutoConfiguration(enabled = false)
class AutoConfigureTestDatabaseServiceConnectionIntegrationTests {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = TestImage.container(PostgreSQLContainer.class);
@Autowired
private DataSource dataSource;
@Test
void dataSourceIsNotReplaced() {
assertThat(this.dataSource).isInstanceOf(HikariDataSource.class).isNotInstanceOf(EmbeddedDatabase.class);
}
@Configuration
@ImportAutoConfiguration(DataSourceAutoConfiguration.class)
static class Config {
}
}

View File

@@ -0,0 +1,9 @@
services:
database:
image: '{imageName}'
ports:
- '5432'
environment:
- 'POSTGRES_USER=myuser'
- 'POSTGRES_DB=mydatabase'
- 'POSTGRES_PASSWORD=secret'

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,10 +26,12 @@ import java.lang.annotation.Target;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.container.ContainerImageMetadata;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.test.autoconfigure.properties.PropertyMapping;
import org.springframework.boot.test.autoconfigure.properties.SkipPropertyMapping;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.DynamicPropertySource;
/**
* Annotation that can be applied to a test class to configure a test database to use
@@ -54,7 +56,7 @@ public @interface AutoConfigureTestDatabase {
* @return the type of existing DataSource to replace
*/
@PropertyMapping(skip = SkipPropertyMapping.ON_DEFAULT_VALUE)
Replace replace() default Replace.ANY;
Replace replace() default Replace.NON_TEST;
/**
* The type of connection to be established when {@link #replace() replacing} the
@@ -69,6 +71,21 @@ public @interface AutoConfigureTestDatabase {
*/
enum Replace {
/**
* Replace the DataSource bean unless it is auto-configured and connecting to a
* test database. The following types of connections are considered test
* databases:
* <ul>
* <li>Any bean definition that includes {@link ContainerImageMetadata} (including
* {@code @ServiceConnection} annotated Testcontainer databases, and connections
* created using Docker Compose)</li>
* <li>Any connection configured using a {@code spring.datasource.url} backed by a
* {@link DynamicPropertySource @DynamicPropertySource}</li>
* </ul>
* @since 3.4.0
*/
NON_TEST,
/**
* Replace the DataSource bean whether it was auto-configured or manually defined.
*/

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,9 @@
package org.springframework.boot.test.autoconfigure.jdbc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
@@ -28,6 +30,8 @@ import org.springframework.aot.AotDetector;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
@@ -37,8 +41,17 @@ import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.container.ContainerImageMetadata;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.JdbcConnectionDetails;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.bind.BoundPropertiesTrackingBindHandler;
import org.springframework.boot.context.properties.source.ConfigurationProperty;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.origin.PropertySourceOrigin;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Role;
@@ -47,6 +60,8 @@ import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.type.MethodMetadata;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.util.Assert;
@@ -62,6 +77,23 @@ import org.springframework.util.ObjectUtils;
@AutoConfiguration(before = DataSourceAutoConfiguration.class)
public class TestDatabaseAutoConfiguration {
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@ConditionalOnProperty(prefix = "spring.test.database", name = "replace", havingValue = "NON_TEST",
matchIfMissing = true)
static EmbeddedDataSourceBeanFactoryPostProcessor nonTestEmbeddedDataSourceBeanFactoryPostProcessor(
Environment environment) {
return new EmbeddedDataSourceBeanFactoryPostProcessor(environment, Replace.NON_TEST);
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@ConditionalOnProperty(prefix = "spring.test.database", name = "replace", havingValue = "ANY")
static EmbeddedDataSourceBeanFactoryPostProcessor embeddedDataSourceBeanFactoryPostProcessor(
Environment environment) {
return new EmbeddedDataSourceBeanFactoryPostProcessor(environment, Replace.ANY);
}
@Bean
@ConditionalOnProperty(prefix = "spring.test.database", name = "replace", havingValue = "AUTO_CONFIGURED")
@ConditionalOnMissingBean
@@ -69,19 +101,25 @@ public class TestDatabaseAutoConfiguration {
return new EmbeddedDataSourceFactory(environment).getEmbeddedDatabase();
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@ConditionalOnProperty(prefix = "spring.test.database", name = "replace", havingValue = "ANY",
matchIfMissing = true)
static EmbeddedDataSourceBeanFactoryPostProcessor embeddedDataSourceBeanFactoryPostProcessor() {
return new EmbeddedDataSourceBeanFactoryPostProcessor();
}
@Order(Ordered.LOWEST_PRECEDENCE)
static class EmbeddedDataSourceBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
private static final ConfigurationPropertyName DATASOURCE_URL_PROPERTY = ConfigurationPropertyName
.of("spring.datasource.url");
private static final String DYNAMIC_VALUES_PROPERTY_SOURCE_CLASS = "org.springframework.test.context.support.DynamicValuesPropertySource";
private static final Log logger = LogFactory.getLog(EmbeddedDataSourceBeanFactoryPostProcessor.class);
private final Environment environment;
private final Replace replace;
EmbeddedDataSourceBeanFactoryPostProcessor(Environment environment, Replace replace) {
this.environment = environment;
this.replace = replace;
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
if (AotDetector.useGeneratedArtifacts()) {
@@ -98,7 +136,7 @@ public class TestDatabaseAutoConfiguration {
private void process(BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory) {
BeanDefinitionHolder holder = getDataSourceBeanDefinition(beanFactory);
if (holder != null) {
if (holder != null && isReplaceable(beanFactory, holder)) {
String beanName = holder.getBeanName();
boolean primary = holder.getBeanDefinition().isPrimary();
logger.info("Replacing '" + beanName + "' DataSource bean with " + (primary ? "primary " : "")
@@ -135,6 +173,60 @@ public class TestDatabaseAutoConfiguration {
return null;
}
private boolean isReplaceable(ConfigurableListableBeanFactory beanFactory, BeanDefinitionHolder holder) {
if (this.replace == Replace.NON_TEST) {
return !isAutoConfigured(holder) || !isConnectingToTestDatabase(beanFactory);
}
return true;
}
private boolean isAutoConfigured(BeanDefinitionHolder holder) {
if (holder.getBeanDefinition() instanceof AnnotatedBeanDefinition annotatedBeanDefinition) {
MethodMetadata factoryMethodMetadata = annotatedBeanDefinition.getFactoryMethodMetadata();
return (factoryMethodMetadata != null) && (factoryMethodMetadata.getDeclaringClassName()
.startsWith("org.springframework.boot.autoconfigure."));
}
return false;
}
private boolean isConnectingToTestDatabase(ConfigurableListableBeanFactory beanFactory) {
return isUsingTestServiceConnection(beanFactory) || isUsingDynamicPropertySournce();
}
private boolean isUsingTestServiceConnection(ConfigurableListableBeanFactory beanFactory) {
for (String beanName : beanFactory.getBeanNamesForType(JdbcConnectionDetails.class)) {
try {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
if (ContainerImageMetadata.isPresent(beanDefinition)) {
return true;
}
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore
}
}
return false;
}
private boolean isUsingDynamicPropertySournce() {
List<ConfigurationProperty> bound = new ArrayList<>();
Binder.get(this.environment, new BoundPropertiesTrackingBindHandler(bound::add))
.bind(DATASOURCE_URL_PROPERTY, Bindable.of(String.class));
return (!bound.isEmpty()) ? isBoundToDynamicValuesPropertySource(bound.get(0)) : false;
}
private boolean isBoundToDynamicValuesPropertySource(ConfigurationProperty configurationProperty) {
if (configurationProperty.getOrigin() instanceof PropertySourceOrigin origin) {
return isDynamicValuesPropertySource(origin.getPropertySource());
}
return false;
}
private boolean isDynamicValuesPropertySource(PropertySource<?> propertySource) {
return propertySource != null
&& DYNAMIC_VALUES_PROPERTY_SOURCE_CLASS.equals(propertySource.getClass().getName());
}
}
static class EmbeddedDataSourceFactoryBean implements FactoryBean<DataSource>, EnvironmentAware, InitializingBean {