Introduce class-level execution phases for @⁠Sql

This commit introduces BEFORE_TEST_CLASS and AFTER_TEST_CLASS execution
phases for @⁠Sql.

See gh-27285
This commit is contained in:
Andreas Ahlenstorf
2021-08-15 17:19:21 +02:00
committed by Sam Brannen
parent 2b47b8942d
commit 5aa2d0515e
8 changed files with 298 additions and 10 deletions

View File

@@ -42,6 +42,7 @@ import org.springframework.test.annotation.DirtiesContext.HierarchyMode;
* override {@link #setMethodInvoker(MethodInvoker)} and {@link #getMethodInvoker()}.
*
* @author Sam Brannen
* @author Andreas Ahlenstorf
* @since 2.5
* @see TestContextManager
* @see TestExecutionListener
@@ -110,6 +111,25 @@ public interface TestContext extends AttributeAccessor, Serializable {
*/
Object getTestInstance();
/**
* Tests whether a test method is part of this test context. Returns
* {@code true} if this context has a current test method, {@code false}
* otherwise.
*
* <p>The default implementation of this method always returns {@code false}.
* Custom {@code TestContext} implementations are therefore highly encouraged
* to override this method with a more meaningful implementation. Note that
* the standard {@code TestContext} implementation in Spring overrides this
* method appropriately.
* @return {@code true} if the test execution has already entered a test
* method
* @since 6.1
* @see #getTestMethod()
*/
default boolean hasTestMethod() {
return false;
}
/**
* Get the current {@linkplain Method test method} for this test context.
* <p>Note: this is a mutable property.

View File

@@ -33,6 +33,11 @@ import org.springframework.core.annotation.AliasFor;
*
* <p>Method-level declarations override class-level declarations by default,
* but this behavior can be configured via {@link SqlMergeMode @SqlMergeMode}.
* However, this does not apply to class-level declarations that use
* {@link ExecutionPhase#BEFORE_TEST_CLASS} or
* {@link ExecutionPhase#AFTER_TEST_CLASS}. Such declarations are retained and
* scripts and statements are executed once per class in addition to any
* method-level annotations.
*
* <p>Script execution is performed by the {@link SqlScriptsTestExecutionListener},
* which is enabled by default.
@@ -61,6 +66,7 @@ import org.springframework.core.annotation.AliasFor;
* modules as well as their transitive dependencies to be present on the classpath.
*
* @author Sam Brannen
* @author Andreas Ahlenstorf
* @since 4.1
* @see SqlConfig
* @see SqlMergeMode
@@ -161,6 +167,18 @@ public @interface Sql {
*/
enum ExecutionPhase {
/**
* The configured SQL scripts and statements will be executed
* once <em>before</em> any test method is run.
*/
BEFORE_TEST_CLASS,
/**
* The configured SQL scripts and statements will be executed
* once <em>after</em> any test method is run.
*/
AFTER_TEST_CLASS,
/**
* The configured SQL scripts and statements will be executed
* <em>before</em> the corresponding test method.

View File

@@ -67,10 +67,17 @@ import static org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX;
* {@link Sql#scripts scripts} and inlined {@link Sql#statements statements}
* configured via the {@link Sql @Sql} annotation.
*
* <p>Scripts and inlined statements will be executed {@linkplain #beforeTestMethod(TestContext) before}
* or {@linkplain #afterTestMethod(TestContext) after} execution of the corresponding
* {@linkplain java.lang.reflect.Method test method}, depending on the configured
* value of the {@link Sql#executionPhase executionPhase} flag.
* <p>Class-level annotations that are constrained to a class-level execution
* phase ({@link ExecutionPhase#BEFORE_TEST_CLASS} or
* {@link ExecutionPhase#AFTER_TEST_CLASS}) will be run
* {@linkplain #beforeTestClass(TestContext) once before all test methods} or
* {@linkplain #afterTestMethod(TestContext) once after all test methods},
* respectively. All other scripts and inlined statements will be executed
* {@linkplain #beforeTestMethod(TestContext) before} or
* {@linkplain #afterTestMethod(TestContext) after} execution of the
* corresponding {@linkplain java.lang.reflect.Method test method}, depending
* on the configured value of the {@link Sql#executionPhase executionPhase}
* flag.
*
* <p>Scripts and inlined statements will be executed without a transaction,
* within an existing Spring-managed transaction, or within an isolated transaction,
@@ -98,6 +105,7 @@ import static org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX;
*
* @author Sam Brannen
* @author Dmitry Semukhin
* @author Andreas Ahlenstorf
* @since 4.1
* @see Sql
* @see SqlConfig
@@ -126,6 +134,26 @@ public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListen
return 5000;
}
/**
* Execute SQL scripts configured via {@link Sql @Sql} for the supplied
* {@link TestContext} once per test class <em>before</em> any test method
* is run.
*/
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
executeBeforeOrAfterClassSqlScripts(testContext, ExecutionPhase.BEFORE_TEST_CLASS);
}
/**
* Execute SQL scripts configured via {@link Sql @Sql} for the supplied
* {@link TestContext} once per test class <em>after</em> all test methods
* have been run.
*/
@Override
public void afterTestClass(TestContext testContext) throws Exception {
executeBeforeOrAfterClassSqlScripts(testContext, ExecutionPhase.AFTER_TEST_CLASS);
}
/**
* Execute SQL scripts configured via {@link Sql @Sql} for the supplied
* {@link TestContext} <em>before</em> the current test method.
@@ -159,6 +187,17 @@ public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListen
registerClasspathResources(getScripts(sql, testClass, testMethod, false), runtimeHints, classLoader)));
}
/**
* Execute class-level SQL scripts configured via {@link Sql @Sql} for the
* supplied {@link TestContext} and the execution phases
* {@link ExecutionPhase#BEFORE_TEST_CLASS} and
* {@link ExecutionPhase#AFTER_TEST_CLASS}.
*/
private void executeBeforeOrAfterClassSqlScripts(TestContext testContext, ExecutionPhase executionPhase) {
Class<?> testClass = testContext.getTestClass();
executeSqlScripts(getSqlAnnotationsFor(testClass), testContext, executionPhase, true);
}
/**
* Execute SQL scripts configured via {@link Sql @Sql} for the supplied
* {@link TestContext} and {@link ExecutionPhase}.
@@ -246,6 +285,9 @@ public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListen
private void executeSqlScripts(
Sql sql, ExecutionPhase executionPhase, TestContext testContext, boolean classLevel) {
Assert.isTrue(classLevel || isValidMethodLevelPhase(sql.executionPhase()),
() -> "%s cannot be used on methods".formatted(sql.executionPhase()));
if (executionPhase != sql.executionPhase()) {
return;
}
@@ -260,7 +302,12 @@ public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListen
.formatted(executionPhase, testContext.getTestClass().getName()));
}
String[] scripts = getScripts(sql, testContext.getTestClass(), testContext.getTestMethod(), classLevel);
Method testMethod = null;
if (testContext.hasTestMethod()) {
testMethod = testContext.getTestMethod();
}
String[] scripts = getScripts(sql, testContext.getTestClass(), testMethod, classLevel);
List<Resource> scriptResources = TestContextResourceUtils.convertToResourceList(
testContext.getApplicationContext(), scripts);
for (String stmt : sql.statements()) {
@@ -354,7 +401,7 @@ public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListen
return null;
}
private String[] getScripts(Sql sql, Class<?> testClass, Method testMethod, boolean classLevel) {
private String[] getScripts(Sql sql, Class<?> testClass, @Nullable Method testMethod, boolean classLevel) {
String[] scripts = sql.scripts();
if (ObjectUtils.isEmpty(scripts) && ObjectUtils.isEmpty(sql.statements())) {
scripts = new String[] {detectDefaultScript(testClass, testMethod, classLevel)};
@@ -366,7 +413,9 @@ public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListen
* Detect a default SQL script by implementing the algorithm defined in
* {@link Sql#scripts}.
*/
private String detectDefaultScript(Class<?> testClass, Method testMethod, boolean classLevel) {
private String detectDefaultScript(Class<?> testClass, @Nullable Method testMethod, boolean classLevel) {
Assert.state(classLevel || testMethod != null, "Method-level @Sql requires a testMethod");
String elementType = (classLevel ? "class" : "method");
String elementName = (classLevel ? testClass.getName() : testMethod.toString());
@@ -407,4 +456,9 @@ public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListen
.forEach(runtimeHints.resources()::registerResource);
}
private static boolean isValidMethodLevelPhase(ExecutionPhase executionPhase) {
// Class-level phases cannot be used on methods.
return executionPhase == ExecutionPhase.BEFORE_TEST_METHOD ||
executionPhase == ExecutionPhase.AFTER_TEST_METHOD;
}
}

View File

@@ -41,6 +41,7 @@ import org.springframework.util.StringUtils;
* @author Sam Brannen
* @author Juergen Hoeller
* @author Rob Harrop
* @author Andreas Ahlenstorf
* @since 4.0
*/
@SuppressWarnings("serial")
@@ -166,6 +167,11 @@ public class DefaultTestContext implements TestContext {
return testInstance;
}
@Override
public boolean hasTestMethod() {
return this.testMethod != null;
}
@Override
public final Method getTestMethod() {
Method testMethod = this.testMethod;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 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.
@@ -46,6 +46,7 @@ import org.springframework.util.StringUtils;
*
* @author Sam Brannen
* @author Juergen Hoeller
* @author Andreas Ahlenstorf
* @since 4.1
*/
public abstract class TestContextTransactionUtils {
@@ -227,7 +228,8 @@ public abstract class TestContextTransactionUtils {
/**
* Create a delegating {@link TransactionAttribute} for the supplied target
* {@link TransactionAttribute} and {@link TestContext}, using the names of
* the test class and test method to build the name of the transaction.
* the test class and test method (if available) to build the name of the
* transaction.
* @param testContext the {@code TestContext} upon which to base the name
* @param targetAttribute the {@code TransactionAttribute} to delegate to
* @return the delegating {@code TransactionAttribute}
@@ -248,7 +250,13 @@ public abstract class TestContextTransactionUtils {
public TestContextTransactionAttribute(TransactionAttribute targetAttribute, TestContext testContext) {
super(targetAttribute);
this.name = ClassUtils.getQualifiedMethodName(testContext.getTestMethod(), testContext.getTestClass());
if (testContext.hasTestMethod()) {
this.name = ClassUtils.getQualifiedMethodName(testContext.getTestMethod(), testContext.getTestClass());
}
else {
this.name = testContext.getTestClass().getName();
}
}
@Override