Introduce initial support for processing test contexts ahead-of-time

This commit introduces TestContextAotGenerator for processing Spring
integration test classes and generating AOT artifacts. Specifically,
this class performs the following.

- bootstraps the TCF for a given test class
- builds the MergedContextConfiguration for each test class and tracks
  all test classes that share the same MergedContextConfiguration
- loads each test ApplicationContext without refreshing it
- passes the test ApplicationContext to ApplicationContextAotGenerator
  to generate the AOT optimized ApplicationContextInitializer
  - The GenerationContext passed to ApplicationContextAotGenerator uses
    a feature name of the form "TestContext###_", where "###" is a
    3-digit sequence ID left padded with zeros.

This commit also includes tests using the TestCompiler to verify that
each generated ApplicationContextInitializer can be used to populate a
GenericApplicationContext as expected.

See gh-28204
This commit is contained in:
Sam Brannen
2022-07-29 21:41:06 +03:00
parent 0973348bde
commit c1a6bfc701
12 changed files with 618 additions and 27 deletions

View File

@@ -0,0 +1,80 @@
/*
* Copyright 2002-2022 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.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.stream.Stream;
/**
* @author Sam Brannen
* @since 6.0
*/
abstract class AbstractAotTests {
static final String[] expectedSourceFilesForBasicSpringTests = {
// BasicSpringJupiterSharedConfigTests
"org/springframework/context/event/DefaultEventListenerFactory__TestContext001_BeanDefinitions.java",
"org/springframework/context/event/EventListenerMethodProcessor__TestContext001_BeanDefinitions.java",
"org/springframework/test/context/aot/samples/basic/BasicSpringJupiterSharedConfigTests__TestContext001_ApplicationContextInitializer.java",
"org/springframework/test/context/aot/samples/basic/BasicSpringJupiterSharedConfigTests__TestContext001_BeanFactoryRegistrations.java",
"org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext001_BeanDefinitions.java",
// BasicSpringJupiterTests -- not generated b/c already generated for BasicSpringJupiterSharedConfigTests.
// "org/springframework/context/event/DefaultEventListenerFactory__TestContext00?_BeanDefinitions.java",
// "org/springframework/context/event/EventListenerMethodProcessor__TestContext00?_BeanDefinitions.java",
// "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterTests__TestContext00?_ApplicationContextInitializer.java",
// "org/springframework/test/context/aot/samples/basic/BasicSpringJupiterTests__TestContext00?_BeanFactoryRegistrations.java",
// "org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext00?_BeanDefinitions.java",
// BasicSpringJupiterTests.NestedTests
"org/springframework/context/event/DefaultEventListenerFactory__TestContext002_BeanDefinitions.java",
"org/springframework/context/event/EventListenerMethodProcessor__TestContext002_BeanDefinitions.java",
"org/springframework/test/context/aot/samples/basic/BasicSpringJupiterTests_NestedTests__TestContext002_ApplicationContextInitializer.java",
"org/springframework/test/context/aot/samples/basic/BasicSpringJupiterTests_NestedTests__TestContext002_BeanFactoryRegistrations.java",
"org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext002_BeanDefinitions.java",
// BasicSpringTestNGTests
"org/springframework/context/event/DefaultEventListenerFactory__TestContext003_BeanDefinitions.java",
"org/springframework/context/event/EventListenerMethodProcessor__TestContext003_BeanDefinitions.java",
"org/springframework/test/context/aot/samples/basic/BasicSpringTestNGTests__TestContext003_ApplicationContextInitializer.java",
"org/springframework/test/context/aot/samples/basic/BasicSpringTestNGTests__TestContext003_BeanFactoryRegistrations.java",
"org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext003_BeanDefinitions.java",
// BasicSpringVintageTests
"org/springframework/context/event/DefaultEventListenerFactory__TestContext004_BeanDefinitions.java",
"org/springframework/context/event/EventListenerMethodProcessor__TestContext004_BeanDefinitions.java",
"org/springframework/test/context/aot/samples/basic/BasicSpringVintageTests__TestContext004_ApplicationContextInitializer.java",
"org/springframework/test/context/aot/samples/basic/BasicSpringVintageTests__TestContext004_BeanFactoryRegistrations.java",
"org/springframework/test/context/aot/samples/basic/BasicTestConfiguration__TestContext004_BeanDefinitions.java"
};
Stream<Class<?>> scan() {
return new TestClassScanner(classpathRoots()).scan();
}
Stream<Class<?>> scan(String... packageNames) {
return new TestClassScanner(classpathRoots()).scan(packageNames);
}
Set<Path> classpathRoots() {
try {
return Set.of(Paths.get(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()));
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2002-2022 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.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.aot.generate.GeneratedFiles.Kind;
import org.springframework.aot.generate.InMemoryGeneratedFiles;
import org.springframework.aot.test.generator.compile.TestCompiler;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Smoke tests for AOT support in the TestContext framework.
*
* @author Sam Brannen
* @since 6.0
*/
class AotSmokeTests extends AbstractAotTests {
@Test
// Using @CompileWithTargetClassAccess results in the following exception in classpathRoots():
// java.lang.NullPointerException: Cannot invoke "java.net.URL.toURI()" because the return
// value of "java.security.CodeSource.getLocation()" is null
void scanClassPathThenGenerateSourceFilesAndCompileThem() {
Stream<Class<?>> testClasses = scan("org.springframework.test.context.aot.samples.basic");
InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles();
TestContextAotGenerator generator = new TestContextAotGenerator(generatedFiles);
generator.processAheadOfTime(testClasses);
List<String> sourceFiles = generatedFiles.getGeneratedFiles(Kind.SOURCE).keySet().stream().toList();
assertThat(sourceFiles).containsExactlyInAnyOrder(expectedSourceFilesForBasicSpringTests);
TestCompiler.forSystem().withFiles(generatedFiles).compile(compiled -> {
// just make sure compilation completes without errors
});
}
}

View File

@@ -16,13 +16,9 @@
package org.springframework.test.context.aot;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterSharedConfigTests;
import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterTests;
import org.springframework.test.context.aot.samples.basic.BasicSpringTestNGTests;
import org.springframework.test.context.aot.samples.basic.BasicSpringVintageTests;
@@ -35,12 +31,13 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Sam Brannen
* @since 6.0
*/
class TestClassScannerTests {
class TestClassScannerTests extends AbstractAotTests {
@Test
void scanBasicTestClasses() {
assertThat(scan("org.springframework.test.context.aot.samples.basic"))
.containsExactlyInAnyOrder(
BasicSpringJupiterSharedConfigTests.class,
BasicSpringJupiterTests.class,
BasicSpringJupiterTests.NestedTests.class,
BasicSpringVintageTests.class,
@@ -51,7 +48,8 @@ class TestClassScannerTests {
@Test
void scanTestSuitesForJupiter() {
assertThat(scan("org.springframework.test.context.aot.samples.suites.jupiter"))
.containsExactlyInAnyOrder(BasicSpringJupiterTests.class, BasicSpringJupiterTests.NestedTests.class);
.containsExactlyInAnyOrder(BasicSpringJupiterSharedConfigTests.class,
BasicSpringJupiterTests.class, BasicSpringJupiterTests.NestedTests.class);
}
@Test
@@ -70,6 +68,7 @@ class TestClassScannerTests {
void scanTestSuitesForAllTestEngines() {
assertThat(scan("org.springframework.test.context.aot.samples.suites.all"))
.containsExactlyInAnyOrder(
BasicSpringJupiterSharedConfigTests.class,
BasicSpringJupiterTests.class,
BasicSpringJupiterTests.NestedTests.class,
BasicSpringVintageTests.class,
@@ -81,6 +80,7 @@ class TestClassScannerTests {
void scanTestSuitesWithNestedSuites() {
assertThat(scan("org.springframework.test.context.aot.samples.suites.nested"))
.containsExactlyInAnyOrder(
BasicSpringJupiterSharedConfigTests.class,
BasicSpringJupiterTests.class,
BasicSpringJupiterTests.NestedTests.class,
BasicSpringVintageTests.class
@@ -92,21 +92,4 @@ class TestClassScannerTests {
assertThat(scan()).hasSizeGreaterThan(400);
}
private Stream<Class<?>> scan() {
return new TestClassScanner(classpathRoots()).scan();
}
private Stream<Class<?>> scan(String... packageNames) {
return new TestClassScanner(classpathRoots()).scan(packageNames);
}
private Set<Path> classpathRoots() {
try {
return Set.of(Paths.get(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()));
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}

View File

@@ -0,0 +1,125 @@
/*
* Copyright 2002-2022 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.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.aot.generate.DefaultGenerationContext;
import org.springframework.aot.generate.GeneratedFiles.Kind;
import org.springframework.aot.generate.InMemoryGeneratedFiles;
import org.springframework.aot.test.generator.compile.CompileWithTargetClassAccess;
import org.springframework.aot.test.generator.compile.TestCompiler;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.javapoet.ClassName;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterSharedConfigTests;
import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterTests;
import org.springframework.test.context.aot.samples.basic.BasicSpringTestNGTests;
import org.springframework.test.context.aot.samples.basic.BasicSpringVintageTests;
import org.springframework.test.context.aot.samples.common.MessageService;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link TestContextAotGenerator}.
*
* @author Sam Brannen
* @since 6.0
*/
@CompileWithTargetClassAccess
class TestContextAotGeneratorTests extends AbstractAotTests {
/**
* @see AotSmokeTests#scanClassPathThenGenerateSourceFilesAndCompileThem()
*/
@Test
void generate() {
Stream<Class<?>> testClasses = Stream.of(
BasicSpringJupiterSharedConfigTests.class,
BasicSpringJupiterTests.class,
BasicSpringJupiterTests.NestedTests.class,
BasicSpringTestNGTests.class,
BasicSpringVintageTests.class);
InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles();
TestContextAotGenerator generator = new TestContextAotGenerator(generatedFiles);
generator.processAheadOfTime(testClasses);
List<String> sourceFiles = generatedFiles.getGeneratedFiles(Kind.SOURCE).keySet().stream().toList();
assertThat(sourceFiles).containsExactlyInAnyOrder(expectedSourceFilesForBasicSpringTests);
TestCompiler.forSystem().withFiles(generatedFiles).compile(compiled -> {
// just make sure compilation completes without errors
});
}
@Test
// We cannot parameterize with the test classes, since @CompileWithTargetClassAccess
// cannot support @ParameterizedTest methods.
void generateApplicationContextInitializer() {
InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles();
TestContextAotGenerator generator = new TestContextAotGenerator(generatedFiles);
Set<Class<?>> testClasses = Set.of(
BasicSpringTestNGTests.class,
BasicSpringVintageTests.class,
BasicSpringJupiterTests.class,
BasicSpringJupiterSharedConfigTests.class);
List<ClassName> classNames = new ArrayList<>();
testClasses.forEach(testClass -> {
DefaultGenerationContext generationContext = generator.createGenerationContext(testClass);
MergedContextConfiguration mergedConfig = generator.buildMergedContextConfiguration(testClass);
ClassName className = generator.processAheadOfTime(mergedConfig, generationContext);
assertThat(className).isNotNull();
classNames.add(className);
generationContext.writeGeneratedContent();
});
compile(generatedFiles, classNames, context -> {
MessageService messageService = context.getBean(MessageService.class);
assertThat(messageService.generateMessage()).isEqualTo("Hello, AOT!");
// TODO Support @TestPropertySource in AOT testing mode.
// assertThat(context.getEnvironment().getProperty("test.engine"))
// .as("@TestPropertySource").isNotNull();
});
}
@SuppressWarnings("unchecked")
private void compile(InMemoryGeneratedFiles generatedFiles, List<ClassName> classNames,
Consumer<GenericApplicationContext> result) {
TestCompiler.forSystem().withFiles(generatedFiles).compile(compiled -> {
classNames.forEach(className -> {
GenericApplicationContext gac = new GenericApplicationContext();
ApplicationContextInitializer<GenericApplicationContext> contextInitializer =
compiled.getInstance(ApplicationContextInitializer.class, className.reflectionName());
contextInitializer.initialize(gac);
gac.refresh();
result.accept(gac);
});
});
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2002-2022 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.samples.basic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.aot.samples.common.MessageService;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Uses configuration identical to {@link BasicSpringJupiterTests}.
*
* @author Sam Brannen
* @since 6.0
*/
@SpringJUnitConfig(BasicTestConfiguration.class)
@TestPropertySource(properties = "test.engine = jupiter")
public class BasicSpringJupiterSharedConfigTests {
@Autowired
ApplicationContext context;
@Autowired
MessageService messageService;
@Value("${test.engine}")
String testEngine;
@org.junit.jupiter.api.Test
void test() {
assertThat(messageService.generateMessage()).isEqualTo("Hello, AOT!");
assertThat(testEngine).isEqualTo("jupiter");
assertThat(context.getEnvironment().getProperty("test.engine"))
.as("@TestPropertySource").isEqualTo("jupiter");
}
}

View File

@@ -22,6 +22,7 @@ import org.junit.jupiter.api.extension.Extension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.aot.samples.common.MessageService;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@@ -36,11 +37,16 @@ import static org.assertj.core.api.Assertions.assertThat;
// for repeated annotations.
@ExtendWith(DummyExtension.class)
@SpringJUnitConfig(BasicTestConfiguration.class)
@TestPropertySource(properties = "test.engine = jupiter")
public class BasicSpringJupiterTests {
@org.junit.jupiter.api.Test
void test(@Autowired MessageService messageService) {
void test(@Autowired ApplicationContext context, @Autowired MessageService messageService,
@Value("${test.engine}") String testEngine) {
assertThat(messageService.generateMessage()).isEqualTo("Hello, AOT!");
assertThat(testEngine).isEqualTo("jupiter");
assertThat(context.getEnvironment().getProperty("test.engine"))
.as("@TestPropertySource").isEqualTo("jupiter");
}
@Nested
@@ -48,9 +54,13 @@ public class BasicSpringJupiterTests {
public class NestedTests {
@org.junit.jupiter.api.Test
void test(@Autowired MessageService messageService, @Value("${foo}") String foo) {
void test(@Autowired ApplicationContext context, @Autowired MessageService messageService,
@Value("${test.engine}") String testEngine, @Value("${foo}") String foo) {
assertThat(messageService.generateMessage()).isEqualTo("Hello, AOT!");
assertThat(foo).isEqualTo("bar");
assertThat(testEngine).isEqualTo("jupiter");
assertThat(context.getEnvironment().getProperty("test.engine"))
.as("@TestPropertySource").isEqualTo("jupiter");
}
}

View File

@@ -17,7 +17,10 @@
package org.springframework.test.context.aot.samples.basic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.aot.samples.common.MessageService;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
@@ -28,14 +31,24 @@ import static org.assertj.core.api.Assertions.assertThat;
* @since 6.0
*/
@ContextConfiguration(classes = BasicTestConfiguration.class)
@TestPropertySource(properties = "test.engine = testng")
public class BasicSpringTestNGTests extends AbstractTestNGSpringContextTests {
@Autowired
ApplicationContext context;
@Autowired
MessageService messageService;
@Value("${test.engine}")
String testEngine;
@org.testng.annotations.Test
public void test() {
assertThat(messageService.generateMessage()).isEqualTo("Hello, AOT!");
assertThat(testEngine).isEqualTo("testng");
assertThat(context.getEnvironment().getProperty("test.engine"))
.as("@TestPropertySource").isEqualTo("testng");
}
}

View File

@@ -19,7 +19,10 @@ package org.springframework.test.context.aot.samples.basic;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.aot.samples.common.MessageService;
import org.springframework.test.context.junit4.SpringRunner;
@@ -31,14 +34,24 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = BasicTestConfiguration.class)
@TestPropertySource(properties = "test.engine = vintage")
public class BasicSpringVintageTests {
@Autowired
ApplicationContext context;
@Autowired
MessageService messageService;
@Value("${test.engine}")
String testEngine;
@org.junit.Test
public void test() {
assertThat(messageService.generateMessage()).isEqualTo("Hello, AOT!");
assertThat(testEngine).isEqualTo("vintage");
assertThat(context.getEnvironment().getProperty("test.engine"))
.as("@TestPropertySource").isEqualTo("vintage");
}
}