Introduce @⁠DisabledInAotMode in the TestContext framework

This commit introduces @⁠DisabledInAotMode in the TestContext
framework to support the following use cases.

- Disabling AOT build-time processing of a test ApplicationContext --
  applicable to any testing framework (JUnit 4, JUnit Jupiter, etc.).

- Disabling an entire test class or a single test method at run time
  when the test suite is run with AOT optimizations enabled -- only
  applicable to JUnit Jupiter based tests.

Closes gh-30834
This commit is contained in:
Sam Brannen
2023-10-15 17:52:37 +02:00
parent 8e5f39b439
commit 39a282e463
10 changed files with 384 additions and 40 deletions

View File

@@ -0,0 +1,62 @@
/*
* 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.
* 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.test.context.aot;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.condition.DisabledIf;
/**
* {@code @DisabledInAotMode} signals that an annotated test class is <em>disabled</em>
* in Spring AOT (ahead-of-time) mode, which means that the {@code ApplicationContext}
* for the test class will not be processed for AOT optimizations at build time.
*
* <p>If a test class is annotated with {@code @DisabledInAotMode}, all other test
* classes which specify configuration to load the same {@code ApplicationContext}
* must also be annotated with {@code @DisabledInAotMode}. Failure to annotate
* all such test classes will result in a exception, either at build time or
* run time.
*
* <p>When used with JUnit Jupiter based tests, {@code @DisabledInAotMode} also
* signals that the annotated test class or test method is <em>disabled</em> when
* running the test suite in Spring AOT mode. When applied at the class level,
* all test methods within that class will be disabled. In this sense,
* {@code @DisabledInAotMode} has semantics similar to those of JUnit Jupiter's
* {@link org.junit.jupiter.api.condition.DisabledInNativeImage @DisabledInNativeImage}
* annotation.
*
* <p>This annotation may be used as a meta-annotation in order to create a
* custom <em>composed annotation</em> that inherits the semantics of this
* annotation.
*
* @author Sam Brannen
* @since 6.1
* @see org.springframework.aot.AotDetector#useGeneratedArtifacts() AotDetector.useGeneratedArtifacts()
* @see org.junit.jupiter.api.condition.EnabledInNativeImage @EnabledInNativeImage
* @see org.junit.jupiter.api.condition.DisabledInNativeImage @DisabledInNativeImage
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@DisabledIf(value = "org.springframework.aot.AotDetector#useGeneratedArtifacts",
disabledReason = "Disabled in Spring AOT mode")
public @interface DisabledInAotMode {
}

View File

@@ -18,9 +18,11 @@ package org.springframework.test.context.aot;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.apache.commons.logging.Log;
@@ -91,6 +93,9 @@ public class TestContextAotGenerator {
private static final Log logger = LogFactory.getLog(TestContextAotGenerator.class);
private static final Predicate<? super Class<?>> isDisabledInAotMode =
testClass -> MergedAnnotations.from(testClass).isPresent(DisabledInAotMode.class);
private final ApplicationContextAotGenerator aotGenerator = new ApplicationContextAotGenerator();
@@ -235,35 +240,56 @@ public class TestContextAotGenerator {
ClassLoader classLoader = getClass().getClassLoader();
MultiValueMap<ClassName, Class<?>> initializerClassMappings = new LinkedMultiValueMap<>();
mergedConfigMappings.forEach((mergedConfig, testClasses) -> {
if (logger.isDebugEnabled()) {
logger.debug("Generating AOT artifacts for test classes " +
testClasses.stream().map(Class::getName).toList());
}
this.mergedConfigRuntimeHints.registerHints(this.runtimeHints, mergedConfig, classLoader);
try {
// Use first test class discovered for a given unique MergedContextConfiguration.
Class<?> testClass = testClasses.get(0);
DefaultGenerationContext generationContext = createGenerationContext(testClass);
ClassName initializer = processAheadOfTime(mergedConfig, generationContext);
Assert.state(!initializerClassMappings.containsKey(initializer),
() -> "ClassName [%s] already encountered".formatted(initializer.reflectionName()));
initializerClassMappings.addAll(initializer, testClasses);
generationContext.writeGeneratedContent();
}
catch (Exception ex) {
if (this.failOnError) {
throw new TestContextAotException("Failed to generate AOT artifacts for test classes " +
testClasses.stream().map(Class::getName).toList(), ex);
long numDisabled = testClasses.stream().filter(isDisabledInAotMode).count();
// At least one test class is disabled?
if (numDisabled > 0) {
// Then all related test classes should be disabled.
if (numDisabled != testClasses.size()) {
if (this.failOnError) {
throw new TestContextAotException("""
All test classes that share an ApplicationContext must be annotated
with @DisabledInAotMode if one of them is: """ + classNames(testClasses));
}
else if (logger.isWarnEnabled()) {
logger.warn("""
All test classes that share an ApplicationContext must be annotated
with @DisabledInAotMode if one of them is: """ + classNames(testClasses));
}
}
if (logger.isInfoEnabled()) {
logger.info("Skipping AOT processing due to the presence of @DisabledInAotMode for test classes " +
classNames(testClasses));
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Failed to generate AOT artifacts for test classes " +
testClasses.stream().map(Class::getName).toList(), ex);
logger.debug("Generating AOT artifacts for test classes " + classNames(testClasses));
}
else if (logger.isWarnEnabled()) {
logger.warn("""
this.mergedConfigRuntimeHints.registerHints(this.runtimeHints, mergedConfig, classLoader);
try {
// Use first test class discovered for a given unique MergedContextConfiguration.
Class<?> testClass = testClasses.get(0);
DefaultGenerationContext generationContext = createGenerationContext(testClass);
ClassName initializer = processAheadOfTime(mergedConfig, generationContext);
Assert.state(!initializerClassMappings.containsKey(initializer),
() -> "ClassName [%s] already encountered".formatted(initializer.reflectionName()));
initializerClassMappings.addAll(initializer, testClasses);
generationContext.writeGeneratedContent();
}
catch (Exception ex) {
if (this.failOnError) {
throw new TestContextAotException("Failed to generate AOT artifacts for test classes " +
classNames(testClasses), ex);
}
if (logger.isDebugEnabled()) {
logger.debug("Failed to generate AOT artifacts for test classes " + classNames(testClasses), ex);
}
else if (logger.isWarnEnabled()) {
logger.warn("""
Failed to generate AOT artifacts for test classes %s. \
Enable DEBUG logging to view the stack trace. %s"""
.formatted(testClasses.stream().map(Class::getName).toList(), ex));
.formatted(classNames(testClasses), ex));
}
}
}
});
@@ -401,4 +427,8 @@ public class TestContextAotGenerator {
return true;
}
private static List<String> classNames(List<Class<?>> classes) {
return classes.stream().map(Class::getName).toList();
}
}