Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a random ${test:logging.path} #2954

Open
wants to merge 7 commits into
base: 2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@
@Target({TYPE, METHOD})
@Inherited
@Documented
@ExtendWith(ExtensionContextAnchor.class)
@ExtendWith(TestPropertyResolver.class)
@ExtendWith({ExtensionContextAnchor.class, TestPropertyResolver.class})
@Repeatable(SetTestProperty.SetTestProperties.class)
@ReadsSystemProperty
@ReadsEnvironmentVariable
Expand All @@ -54,7 +53,7 @@
@Target({TYPE, METHOD})
@Documented
@Inherited
public @interface SetTestProperties {
@interface SetTestProperties {

SetTestProperty[] value();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@
@Target({FIELD, PARAMETER})
@Inherited
@Documented
@ExtendWith(ExtensionContextAnchor.class)
@ExtendWith(TempLoggingDirectory.class)
@ExtendWith({ExtensionContextAnchor.class, TempLoggingDirectory.class})
public @interface TempLoggingDir {

CleanupMode cleanup() default CleanupMode.DEFAULT;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.test.TestProperties;
import org.junit.jupiter.api.extension.BeforeAllCallback;
Expand All @@ -39,19 +40,23 @@
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.io.CleanupMode;
import org.junit.platform.commons.PreconditionViolationException;
import org.junit.platform.commons.support.AnnotationSupport;
import org.junit.platform.commons.support.ModifierSupport;

public class TempLoggingDirectory implements BeforeAllCallback, BeforeEachCallback, ParameterResolver {

private final AtomicInteger counter = new AtomicInteger();

@Override
public void beforeAll(ExtensionContext context) throws Exception {
final List<Field> fields = AnnotationSupport.findAnnotatedFields(
context.getRequiredTestClass(), TempLoggingDir.class, ModifierSupport::isStatic);
Path loggingPath = null;
for (final Field field : fields) {
if (loggingPath != null) {
StatusLogger.getLogger().warn("Multiple fields with @TempLoggingDir annotation are not supported.");
throw new PreconditionViolationException(
"Multiple static fields with @TempLoggingDir annotation are not supported.");
} else {
final CleanupMode cleanup = determineCleanupMode(field);
loggingPath = createLoggingPath(context, cleanup).getPath();
Expand All @@ -63,8 +68,8 @@ public void beforeAll(ExtensionContext context) throws Exception {

@Override
public void beforeEach(ExtensionContext context) throws Exception {
// JUnit 5 does not set an error on the parent context if one of the children
// fail. We record the list of children.
// JUnit 5 does not set an error on the parent context if one of the children fails.
// We record the list of children.
context.getParent().ifPresent(c -> {
final PathHolder holder = ExtensionContextAnchor.getAttribute(PathHolder.class, PathHolder.class, c);
if (holder != null) {
Expand All @@ -78,7 +83,8 @@ public void beforeEach(ExtensionContext context) throws Exception {
final Object instance = context.getRequiredTestInstance();
for (final Field field : fields) {
if (loggingPath != null) {
StatusLogger.getLogger().warn("Multiple fields with @TempLoggingDir annotation are not supported.");
throw new PreconditionViolationException(
"Multiple instance fields with @TempLoggingDir annotation are not supported.");
} else {
final CleanupMode cleanup = determineCleanupMode(field);
loggingPath = createLoggingPath(context, cleanup).getPath();
Expand All @@ -100,9 +106,12 @@ public boolean supportsParameter(ParameterContext parameterContext, ExtensionCon
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
final TempLoggingDir annotation =
parameterContext.findAnnotation(TempLoggingDir.class).get();
// Get or create temporary directory
final TempLoggingDir annotation = parameterContext
.findAnnotation(TempLoggingDir.class)
.orElseThrow(() -> new PreconditionViolationException(String.format(
"Missing `%s` annotation on parameter `%s`",
TempLoggingDir.class.getSimpleName(), parameterContext)));
// Get or create a temporary directory
PathHolder holder = ExtensionContextAnchor.getAttribute(PathHolder.class, PathHolder.class, extensionContext);
if (holder == null || !extensionContext.equals(holder.getMainContext())) {
final CleanupMode mode = determineCleanupMode(annotation);
Expand All @@ -111,14 +120,9 @@ public Object resolveParameter(ParameterContext parameterContext, ExtensionConte
return holder.getPath();
}

private PathHolder createLoggingPath(final ExtensionContext context, final CleanupMode cleanup) {
private PathHolder createLoggingPath(ExtensionContext context, CleanupMode cleanup) {
final TestProperties props = TestPropertySource.createProperties(context);
// Create temporary directory
final String baseDir = System.getProperty("basedir");
final Path basePath = (baseDir != null ? Paths.get(baseDir, "target") : Paths.get(".")).resolve("logs");
final Class<?> clazz = context.getRequiredTestClass();
final String dir = clazz.getName().replaceAll("[.$]", File.separatorChar == '\\' ? "\\\\" : File.separator);
final Path perClassPath = basePath.resolve(dir);
final Path perClassPath = determinePerClassPath(context);
// Per test subfolder
final Path loggingPath = context.getTestMethod()
.map(m -> perClassPath.resolve(m.getName()))
Expand All @@ -135,6 +139,31 @@ private PathHolder createLoggingPath(final ExtensionContext context, final Clean
return holder;
}

private Path determinePerClassPath(ExtensionContext context) {
// Check if the parent context already created a folder
PathHolder holder = ExtensionContextAnchor.getAttribute(PathHolder.class, PathHolder.class, context);
if (holder == null) {
try {
// Create temporary per-class directory
final String baseDir = System.getProperty("basedir");
final Path basePath = (baseDir != null ? Paths.get(baseDir, "target") : Paths.get(".")).resolve("logs");
final Class<?> clazz = context.getRequiredTestClass();
final Package pkg = clazz.getPackage();
final String dir = pkg.getName()
.replaceAll("org\\.apache\\.(logging\\.)?log4j\\.", "")
.replaceAll("[.$]", File.separatorChar == '\\' ? "\\\\" : File.separator);
// Create a temporary directory that uses the simple class name as prefix
Path packagePath = basePath.resolve(dir);
Files.createDirectories(packagePath);
return Files.createTempDirectory(
packagePath, String.format("%s_%02d_", clazz.getSimpleName(), counter.incrementAndGet()));
} catch (final IOException e) {
throw new ExtensionContextException("Failed to create temporary directory.", e);
}
}
return holder.getPath();
}

private CleanupMode determineCleanupMode(final TempLoggingDir annotation) {
final CleanupMode mode = annotation.cleanup();
// TODO: use JupiterConfiguration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,5 @@
@Retention(RUNTIME)
@Target({TYPE, METHOD})
@Documented
@ExtendWith(ExtensionContextAnchor.class)
@ExtendWith(TestPropertyResolver.class)
@ExtendWith(StatusListenerExtension.class)
@ExtendWith({ExtensionContextAnchor.class, TestPropertyResolver.class, StatusListenerExtension.class})
public @interface UsingStatusListener {}
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@
@Target({TYPE, METHOD})
@Inherited
@Documented
@ExtendWith(ExtensionContextAnchor.class)
@ExtendWith(TestPropertyResolver.class)
@ExtendWith({ExtensionContextAnchor.class, TestPropertyResolver.class})
@ReadsSystemProperty
@ReadsEnvironmentVariable
public @interface UsingTestProperties {}
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,8 @@
* limitations under the license.
*/
@Export
@Version("2.24.0")
@BaselineIgnore("2.24.0")
@Version("2.24.1")
package org.apache.logging.log4j.test.junit;

import aQute.bnd.annotation.baseline.BaselineIgnore;
import org.osgi.annotation.bundle.Export;
import org.osgi.annotation.versioning.Version;
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;
import org.apache.logging.log4j.test.TestProperties;
import org.junit.jupiter.api.Test;

@UsingTestProperties
public class TempLoggingDirectoryTest {

private static final Path PER_CLASS_PATH = Paths.get("TempLoggingDirectoryTest");
private static final Pattern PER_CLASS_PATH = Pattern.compile("TempLoggingDirectoryTest_\\d{2}_\\d+");
private static final Path PER_TEST_PATH = Paths.get("testInjectedFields");

@TempLoggingDir
Expand All @@ -37,7 +38,8 @@ public class TempLoggingDirectoryTest {

@Test
void testInjectedFields(final @TempLoggingDir Path parameterLoggingPath, final TestProperties props) {
assertThat(staticLoggingPath).exists().endsWith(PER_CLASS_PATH);
assertThat(staticLoggingPath).exists();
assertThat(staticLoggingPath.getFileName().toString()).matches(PER_CLASS_PATH);
assertThat(instanceLoggingPath).exists().startsWith(staticLoggingPath).endsWith(PER_TEST_PATH);
assertThat(parameterLoggingPath).isEqualTo(instanceLoggingPath);
assertThat(props.getProperty(TestProperties.LOGGING_PATH)).isEqualTo(instanceLoggingPath.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,12 @@
@Documented
@Inherited
@Tag("functional")
@ExtendWith(TempLoggingDirectory.class)
@ExtendWith(LoggerContextResolver.class)
@ExtendWith(ConfigurationResolver.class)
@ExtendWith(AppenderResolver.class)
@ExtendWith({
TempLoggingDirectory.class,
LoggerContextResolver.class,
ConfigurationResolver.class,
AppenderResolver.class
})
public @interface LoggerContextSource {
/**
* Specifies the name of the configuration file to use for the annotated test.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
* @see org.junit.rules.TestRule
*/
@Export
@Version("2.23.0")
@Version("2.23.1")
package org.apache.logging.log4j.core.test.junit;

import org.osgi.annotation.bundle.Export;
Expand Down
2 changes: 1 addition & 1 deletion log4j-parent/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@
<jmdns.version>3.5.12</jmdns.version>
<jmh.version>1.37</jmh.version>
<junit.version>4.13.2</junit.version>
<junit-jupiter.version>5.10.3</junit-jupiter.version>
<junit-jupiter.version>5.11.2</junit-jupiter.version>
<junit-pioneer.version>1.9.1</junit-pioneer.version>
<kafka.version>3.8.0</kafka.version>
<lightcouch.version>0.2.0</lightcouch.version>
Expand Down