Unwrap proxied DataSources in SqlScriptsTestExecutionListener

Prior to this commit, if the DataSource in the
DataSourceFromTransactionManager was wrapped in a proxy implementing
InfrastructureProxy, SqlScriptsTestExecutionListener would throw an
exception stating that the DataSource in the ApplicationContext and the
DataSource in the DataSourceFromTransactionManager were not the same.

This commit unwraps both data sources and compares the underlying
target instances to check for equality.

In addition, this commit makes the unwrapResourceIfNecessary() method in
TransactionSynchronizationUtils public.

Closes gh-26422
This commit is contained in:
Sam Brannen
2021-01-22 18:22:00 +01:00
parent bad8954e65
commit 4a7a2258f9
3 changed files with 144 additions and 4 deletions

View File

@@ -46,6 +46,7 @@ import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.support.TransactionSynchronizationUtils;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
@@ -258,7 +259,7 @@ public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListen
else {
DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
// Ensure user configured an appropriate DataSource/TransactionManager pair.
if (dataSource != null && dataSourceFromTxMgr != null && !dataSource.equals(dataSourceFromTxMgr)) {
if (dataSource != null && dataSourceFromTxMgr != null && !sameDataSource(dataSource, dataSourceFromTxMgr)) {
throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: " +
"the configured DataSource [%s] (named '%s') is not the one associated with " +
"transaction manager [%s] (named '%s').", testContext, dataSource.getClass().getName(),
@@ -292,6 +293,17 @@ public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListen
return populator;
}
/**
* Determine if the two data sources are effectively the same, unwrapping
* proxies as necessary to compare the target instances.
* @since 5.3.4
* @see TransactionSynchronizationUtils#unwrapResourceIfNecessary(Object)
*/
private static boolean sameDataSource(DataSource ds1, DataSource ds2) {
return TransactionSynchronizationUtils.unwrapResourceIfNecessary(ds1)
.equals(TransactionSynchronizationUtils.unwrapResourceIfNecessary(ds2));
}
@Nullable
private DataSource getDataSourceFromTransactionManager(PlatformTransactionManager transactionManager) {
try {