From 569830cdca387974cc731979c3895bed6ff68189 Mon Sep 17 00:00:00 2001 From: Ilya Lukyanovich Date: Tue, 11 Jun 2019 17:16:25 +0300 Subject: [PATCH 1/2] Migrate LogbackLoggingSystemTests to JUnit 5 See gh-17107 --- .../logging/AbstractLoggingSystemTests.java | 23 ++- .../logging/java/JavaLoggingSystemTests.java | 70 ++++---- .../log4j2/Log4J2LoggingSystemTests.java | 93 ++++------ .../logback/LogbackLoggingSystemTests.java | 166 +++++++----------- src/checkstyle/checkstyle-suppressions.xml | 2 - 5 files changed, 147 insertions(+), 207 deletions(-) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java index 00afb27c062..e76a7dd266c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java @@ -16,18 +16,18 @@ package org.springframework.boot.logging; -import java.io.IOException; +import java.nio.file.Path; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; import org.springframework.util.StringUtils; /** * Base for {@link LoggingSystem} tests. * + * @author Ilya Lukyanovich * @author Phillip Webb * @author Andy Wilkinson */ @@ -35,23 +35,20 @@ public abstract class AbstractLoggingSystemTests { private static final String JAVA_IO_TMPDIR = "java.io.tmpdir"; - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - private String originalTempFolder; - @Before - public void configureTempDir() throws IOException { + @BeforeEach + public void configureTempDir(@TempDir Path temp) { this.originalTempFolder = System.getProperty(JAVA_IO_TMPDIR); - System.setProperty(JAVA_IO_TMPDIR, this.temp.newFolder().getAbsolutePath()); + System.setProperty(JAVA_IO_TMPDIR, temp.toAbsolutePath().toString()); } - @After + @AfterEach public void reinstateTempDir() { System.setProperty(JAVA_IO_TMPDIR, this.originalTempFolder); } - @After + @AfterEach public void clear() { System.clearProperty(LoggingSystemProperties.LOG_FILE); System.clearProperty(LoggingSystemProperties.PID_KEY); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java index a9cea892271..5f5768e10e0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/java/JavaLoggingSystemTests.java @@ -24,17 +24,18 @@ import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.logging.AbstractLoggingSystemTests; import org.springframework.boot.logging.LogLevel; import org.springframework.boot.logging.LoggerConfiguration; import org.springframework.boot.logging.LoggingSystem; import org.springframework.boot.logging.LoggingSystemProperties; -import org.springframework.boot.testsupport.system.OutputCaptureRule; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; @@ -48,49 +49,46 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException; * @author Phillip Webb * @author Ben Hale */ -public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { +@ExtendWith(OutputCaptureExtension.class) +class JavaLoggingSystemTests extends AbstractLoggingSystemTests { private static final FileFilter SPRING_LOG_FILTER = (pathname) -> pathname.getName().startsWith("spring.log"); private final JavaLoggingSystem loggingSystem = new JavaLoggingSystem(getClass().getClassLoader()); - @Rule - public OutputCaptureRule output = new OutputCaptureRule(); - private Logger logger; private Locale defaultLocale; - @Before - public void init() throws SecurityException { + @BeforeEach + void init() throws SecurityException { + this.logger = Logger.getLogger(getClass().getName()); this.defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); - this.logger = Logger.getLogger(getClass().getName()); } - @After - public void clearLocale() { - Locale.setDefault(this.defaultLocale); - } - - @After - public void resetLogger() { + @AfterEach + void resetLogger() { this.logger.setLevel(Level.OFF); } + @AfterEach + void restoreLocale() { + Locale.setDefault(this.defaultLocale); + } + @Test - public void noFile() { + void noFile(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); this.loggingSystem.initialize(null, null, null); this.logger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(output).contains("Hello world").doesNotContain("Hidden"); assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); } @Test - public void withFile() { + void withFile(CapturedOutput output) { File temp = new File(tmpDir()); File[] logFiles = temp.listFiles(SPRING_LOG_FILTER); for (File file : logFiles) { @@ -100,66 +98,62 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.info("Hidden"); this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir())); this.logger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(output).contains("Hello world").doesNotContain("Hidden"); - assertThat(temp.listFiles(SPRING_LOG_FILTER).length).isGreaterThan(0); + assertThat(temp.listFiles(SPRING_LOG_FILTER)).hasSizeGreaterThan(0); } @Test - public void testCustomFormatter() { + void testCustomFormatter(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.logger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(output).contains("Hello world").contains("???? INFO ["); } @Test - public void testSystemPropertyInitializesFormat() { + void testSystemPropertyInitializesFormat(CapturedOutput output) { System.setProperty(LoggingSystemProperties.PID_KEY, "1234"); this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, "classpath:" + ClassUtils.addResourcePathToPackagePath(getClass(), "logging.properties"), null); this.logger.info("Hello world"); this.logger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(output).contains("Hello world").contains("1234 INFO ["); } @Test - public void testNonDefaultConfigLocation() { + void testNonDefaultConfigLocation(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, "classpath:logging-nondefault.properties", null); this.logger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(output).contains("INFO: Hello"); } @Test - public void testNonexistentConfigLocation() { + void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); assertThatIllegalStateException().isThrownBy( () -> this.loggingSystem.initialize(null, "classpath:logging-nonexistent.properties", null)); } @Test - public void getSupportedLevels() { + void getSupportedLevels() { assertThat(this.loggingSystem.getSupportedLogLevels()).isEqualTo( EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF)); } @Test - public void setLevel() { + void setLevel(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.logger.fine("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.fine("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(output.toString(), "Hello")).isEqualTo(1); } @Test - public void setLevelToNull() { + void setLevelToNull(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.logger.fine("Hello"); @@ -167,11 +161,11 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.fine("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", null); this.logger.fine("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(output.toString(), "Hello")).isEqualTo(1); } @Test - public void getLoggingConfigurations() { + void getLoggingConfigurations() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); @@ -181,7 +175,7 @@ public class JavaLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void getLoggingConfiguration() { + void getLoggingConfiguration() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java index df6d0866180..6c6320253e6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/log4j2/Log4J2LoggingSystemTests.java @@ -29,27 +29,23 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.logging.AbstractLoggingSystemTests; import org.springframework.boot.logging.LogLevel; import org.springframework.boot.logging.LoggerConfiguration; import org.springframework.boot.logging.LoggingSystem; import org.springframework.boot.logging.LoggingSystemProperties; -import org.springframework.boot.testsupport.assertj.Matched; -import org.springframework.boot.testsupport.system.OutputCaptureRule; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.contentOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -63,35 +59,30 @@ import static org.mockito.Mockito.verify; * @author Andy Wilkinson * @author Ben Hale */ -public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { - - @Rule - public OutputCaptureRule output = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { private final TestLog4J2LoggingSystem loggingSystem = new TestLog4J2LoggingSystem(); private Logger logger; - @Before - public void setup() { + @BeforeEach + void setup() { this.loggingSystem.cleanUp(); this.logger = LogManager.getLogger(getClass()); } - @Override - @After - public void clear() { - super.clear(); + @AfterEach + void cleanUp() { this.loggingSystem.cleanUp(); } @Test - public void noFile() { + void noFile(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); this.loggingSystem.initialize(null, null, null); this.logger.info("Hello world"); - String output = this.output.toString().trim(); Configuration configuration = this.loggingSystem.getConfiguration(); assertThat(output).contains("Hello world").doesNotContain("Hidden"); assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); @@ -99,12 +90,11 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void withFile() { + void withFile(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir())); this.logger.info("Hello world"); - String output = this.output.toString().trim(); Configuration configuration = this.loggingSystem.getConfiguration(); assertThat(output).contains("Hello world").doesNotContain("Hidden"); assertThat(new File(tmpDir() + "/spring.log").exists()).isTrue(); @@ -112,11 +102,10 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testNonDefaultConfigLocation() { + void testNonDefaultConfigLocation(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, "classpath:log4j2-nondefault.xml", getLogFile(tmpDir() + "/tmp.log", null)); this.logger.info("Hello world"); - String output = this.output.toString().trim(); Configuration configuration = this.loggingSystem.getConfiguration(); assertThat(output).contains("Hello world").contains(tmpDir() + "/tmp.log"); assertThat(new File(tmpDir() + "/tmp.log").exists()).isFalse(); @@ -126,29 +115,29 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testNonexistentConfigLocation() { + void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); assertThatIllegalStateException() .isThrownBy(() -> this.loggingSystem.initialize(null, "classpath:log4j2-nonexistent.xml", null)); } @Test - public void getSupportedLevels() { + void getSupportedLevels() { assertThat(this.loggingSystem.getSupportedLogLevels()).isEqualTo(EnumSet.allOf(LogLevel.class)); } @Test - public void setLevel() { + void setLevel(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(output.toString(), "Hello")).isEqualTo(1); } @Test - public void setLevelToNull() { + void setLevelToNull(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.logger.debug("Hello"); @@ -156,11 +145,11 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", null); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(output.toString(), "Hello")).isEqualTo(1); } @Test - public void getLoggingConfigurations() { + void getLoggingConfigurations() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); @@ -170,7 +159,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void getLoggingConfiguration() { + void getLoggingConfiguration() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); @@ -180,44 +169,43 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void setLevelOfUnconfiguredLoggerDoesNotAffectRootConfiguration() { + void setLevelOfUnconfiguredLoggerDoesNotAffectRootConfiguration(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); LogManager.getRootLogger().debug("Hello"); this.loggingSystem.setLogLevel("foo.bar.baz", LogLevel.DEBUG); LogManager.getRootLogger().debug("Hello"); - assertThat(this.output.toString()).doesNotContain("Hello"); + assertThat(output.toString()).doesNotContain("Hello"); } @Test - public void loggingThatUsesJulIsCaptured() { + void loggingThatUsesJulIsCaptured(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, null); java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(getClass().getName()); julLogger.severe("Hello world"); - String output = this.output.toString().trim(); assertThat(output).contains("Hello world"); } @Test - public void configLocationsWithNoExtraDependencies() { + void configLocationsWithNoExtraDependencies() { assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.properties", "log4j2.xml"); } @Test - public void configLocationsWithJacksonDatabind() { + void configLocationsWithJacksonDatabind() { this.loggingSystem.availableClasses(ObjectMapper.class.getName()); assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.json", "log4j2.jsn", "log4j2.xml"); } @Test - public void configLocationsWithJacksonDataformatYaml() { + void configLocationsWithJacksonDataformatYaml() { this.loggingSystem.availableClasses("com.fasterxml.jackson.dataformat.yaml.YAMLParser"); assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.yaml", "log4j2.yml", "log4j2.xml"); } @Test - public void configLocationsWithJacksonDatabindAndDataformatYaml() { + void configLocationsWithJacksonDatabindAndDataformatYaml() { this.loggingSystem.availableClasses("com.fasterxml.jackson.dataformat.yaml.YAMLParser", ObjectMapper.class.getName()); assertThat(this.loggingSystem.getStandardConfigLocations()).contains("log4j2.yaml", "log4j2.yml", "log4j2.json", @@ -225,42 +213,39 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void springConfigLocations() { + void springConfigLocations() { String[] locations = getSpringConfigLocations(this.loggingSystem); assertThat(locations).containsExactly("log4j2-spring.properties", "log4j2-spring.xml"); } @Test - public void exceptionsIncludeClassPackaging() { + void exceptionsIncludeClassPackaging(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir())); - Matcher expectedOutput = containsString("[junit-"); - this.output.expect(expectedOutput); this.logger.warn("Expected exception", new RuntimeException("Expected")); String fileContents = contentOf(new File(tmpDir() + "/spring.log")); - assertThat(fileContents).is(Matched.by(expectedOutput)); + assertThat(fileContents).contains("[junit-"); + assertThat(output).contains("[junit-"); } @Test - public void beforeInitializeFilterDisablesErrorLogging() { + void beforeInitializeFilterDisablesErrorLogging() { this.loggingSystem.beforeInitialize(); assertThat(this.logger.isErrorEnabled()).isFalse(); this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir())); } @Test - public void customExceptionConversionWord() { + void customExceptionConversionWord(CapturedOutput output) { System.setProperty(LoggingSystemProperties.EXCEPTION_CONVERSION_WORD, "%ex"); try { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); this.loggingSystem.initialize(null, null, getLogFile(null, tmpDir())); - Matcher expectedOutput = Matchers.allOf(containsString("java.lang.RuntimeException: Expected"), - not(containsString("Wrapped by:"))); - this.output.expect(expectedOutput); this.logger.warn("Expected exception", new RuntimeException("Expected", new RuntimeException("Cause"))); String fileContents = contentOf(new File(tmpDir() + "/spring.log")); - assertThat(fileContents).is(Matched.by(expectedOutput)); + assertThat(fileContents).contains("java.lang.RuntimeException: Expected").doesNotContain("Wrapped by:"); + assertThat(output).contains("java.lang.RuntimeException: Expected").doesNotContain("Wrapped by:"); } finally { System.clearProperty(LoggingSystemProperties.EXCEPTION_CONVERSION_WORD); @@ -268,7 +253,7 @@ public class Log4J2LoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void initializationIsOnlyPerformedOnceUntilCleanedUp() { + void initializationIsOnlyPerformedOnceUntilCleanedUp() { LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); PropertyChangeListener listener = mock(PropertyChangeListener.class); loggerContext.addPropertyChangeListener(listener); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java index d180e6e50d9..14f71ae79ea 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/LogbackLoggingSystemTests.java @@ -17,6 +17,7 @@ package org.springframework.boot.logging.logback; import java.io.File; +import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.logging.Handler; @@ -29,13 +30,10 @@ import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.rolling.RollingFileAppender; import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy; -import org.hamcrest.Matcher; -import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.ILoggerFactory; import org.slf4j.bridge.SLF4JBridgeHandler; import org.slf4j.impl.StaticLoggerBinder; @@ -47,10 +45,8 @@ import org.springframework.boot.logging.LoggerConfiguration; import org.springframework.boot.logging.LoggingInitializationContext; import org.springframework.boot.logging.LoggingSystem; import org.springframework.boot.logging.LoggingSystemProperties; -import org.springframework.boot.testsupport.assertj.Matched; -import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; -import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; -import org.springframework.boot.testsupport.system.OutputCaptureRule; +import org.springframework.boot.testsupport.system.CapturedOutput; +import org.springframework.boot.testsupport.system.OutputCaptureExtension; import org.springframework.mock.env.MockEnvironment; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.StringUtils; @@ -58,8 +54,6 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.contentOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -75,12 +69,8 @@ import static org.mockito.Mockito.verify; * @author Vedran Pavic * @author Robert Thornton */ -@RunWith(ModifiedClassPathRunner.class) -@ClassPathExclusions("log4j-*.jar") -public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { - - @Rule - public OutputCaptureRule output = new OutputCaptureRule(); +@ExtendWith(OutputCaptureExtension.class) +class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { private final LogbackLoggingSystem loggingSystem = new LogbackLoggingSystem(getClass().getClassLoader()); @@ -88,41 +78,37 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { private LoggingInitializationContext initializationContext; - @Before - public void setup() { + @BeforeEach + void setup() { this.loggingSystem.cleanUp(); this.logger = ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()).getLogger(getClass()); MockEnvironment environment = new MockEnvironment(); this.initializationContext = new LoggingInitializationContext(environment); } - @Override - @After - public void clear() { - super.clear(); + @AfterEach + void cleanUp() { this.loggingSystem.cleanUp(); ((LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory()).stop(); } @Test - public void noFile() { + void noFile(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); this.loggingSystem.initialize(this.initializationContext, null, null); this.logger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(output).contains("Hello world").doesNotContain("Hidden"); assertThat(getLineWithText(output, "Hello world")).contains("INFO"); assertThat(new File(tmpDir() + "/spring.log").exists()).isFalse(); } @Test - public void withFile() { + void withFile(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); this.loggingSystem.initialize(this.initializationContext, null, getLogFile(null, tmpDir())); this.logger.info("Hello world"); - String output = this.output.toString().trim(); File file = new File(tmpDir() + "/spring.log"); assertThat(output).contains("Hello world").doesNotContain("Hidden"); assertThat(getLineWithText(output, "Hello world")).contains("INFO"); @@ -133,35 +119,31 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void defaultConfigConfiguresAConsoleAppender() { + void defaultConfigConfiguresAConsoleAppender() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); assertThat(getConsoleAppender()).isNotNull(); } @Test - public void testNonDefaultConfigLocation() { - int existingOutputLength = this.output.toString().length(); + void testNonDefaultConfigLocation(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, "classpath:logback-nondefault.xml", getLogFile(tmpDir() + "/tmp.log", null)); this.logger.info("Hello world"); - String output = this.output.toString().trim(); - assertThat(output.substring(existingOutputLength)).doesNotContain("DEBUG"); - assertThat(output).contains("Hello world").contains(tmpDir() + "/tmp.log"); - assertThat(output).endsWith("BOOTBOOT"); + assertThat(output).doesNotContain("DEBUG").contains("Hello world").contains(tmpDir() + "/tmp.log") + .endsWith("BOOTBOOT"); assertThat(new File(tmpDir() + "/tmp.log").exists()).isFalse(); } @Test - public void testLogbackSpecificSystemProperty() { + void testLogbackSpecificSystemProperty(CapturedOutput output) { System.setProperty("logback.configurationFile", "/foo/my-file.xml"); try { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); - String output = this.output.toString().trim(); assertThat(output).contains( - "Ignoring 'logback.configurationFile' " + "system property. Please use 'logging.config' instead."); + "Ignoring 'logback.configurationFile' system property. Please use 'logging.config' instead."); } finally { System.clearProperty("logback.configurationFile"); @@ -169,30 +151,30 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testNonexistentConfigLocation() { + void testNonexistentConfigLocation() { this.loggingSystem.beforeInitialize(); assertThatIllegalStateException().isThrownBy(() -> this.loggingSystem.initialize(this.initializationContext, "classpath:logback-nonexistent.xml", null)); } @Test - public void getSupportedLevels() { + void getSupportedLevels() { assertThat(this.loggingSystem.getSupportedLogLevels()).isEqualTo( EnumSet.of(LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR, LogLevel.OFF)); } @Test - public void setLevel() { + void setLevel(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", LogLevel.DEBUG); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(output.toString(), "Hello")).isEqualTo(1); } @Test - public void setLevelToNull() { + void setLevelToNull(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.logger.debug("Hello"); @@ -200,11 +182,11 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { this.logger.debug("Hello"); this.loggingSystem.setLogLevel("org.springframework.boot", null); this.logger.debug("Hello"); - assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello")).isEqualTo(1); + assertThat(StringUtils.countOccurrencesOf(output.toString(), "Hello")).isEqualTo(1); } @Test - public void getLoggingConfigurations() { + void getLoggingConfigurations() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); @@ -214,7 +196,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void getLoggingConfiguration() { + void getLoggingConfiguration() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); @@ -224,7 +206,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void getLoggingConfigurationForALL() { + void getLoggingConfigurationForALL() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); Logger logger = (Logger) StaticLoggerBinder.getSingleton().getLoggerFactory().getLogger(getClass().getName()); @@ -235,7 +217,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void systemLevelTraceShouldReturnNativeLevelTraceNotAll() { + void systemLevelTraceShouldReturnNativeLevelTraceNotAll() { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.TRACE); @@ -244,28 +226,26 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void loggingThatUsesJulIsCaptured() { + void loggingThatUsesJulIsCaptured(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(getClass().getName()); julLogger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(output).contains("Hello world"); } @Test - public void loggingLevelIsPropagatedToJul() { + void loggingLevelIsPropagatedToJul(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, null); this.loggingSystem.setLogLevel(getClass().getName(), LogLevel.DEBUG); java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(getClass().getName()); julLogger.fine("Hello debug world"); - String output = this.output.toString().trim(); assertThat(output).contains("Hello debug world"); } @Test - public void bridgeHandlerLifecycle() { + void bridgeHandlerLifecycle() { assertThat(bridgeHandlerInstalled()).isFalse(); this.loggingSystem.beforeInitialize(); assertThat(bridgeHandlerInstalled()).isTrue(); @@ -274,14 +254,14 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void standardConfigLocations() { + void standardConfigLocations() { String[] locations = this.loggingSystem.getStandardConfigLocations(); assertThat(locations).containsExactly("logback-test.groovy", "logback-test.xml", "logback.groovy", "logback.xml"); } @Test - public void springConfigLocations() { + void springConfigLocations() { String[] locations = getSpringConfigLocations(this.loggingSystem); assertThat(locations).containsExactly("logback-test-spring.groovy", "logback-test-spring.xml", "logback-spring.groovy", "logback-spring.xml"); @@ -299,29 +279,27 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testConsolePatternProperty() { + void testConsolePatternProperty(CapturedOutput output) { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.pattern.console", "%logger %msg"); LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); this.loggingSystem.initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(getLineWithText(output, "Hello world")).doesNotContain("INFO"); } @Test - public void testLevelPatternProperty() { + void testLevelPatternProperty(CapturedOutput output) { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.pattern.level", "X%clr(%p)X"); LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); this.loggingSystem.initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(getLineWithText(output, "Hello world")).contains("XINFOX"); } @Test - public void testFilePatternProperty() { + void testFilePatternProperty(CapturedOutput output) { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.pattern.file", "%logger %msg"); LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); @@ -329,13 +307,12 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { LogFile logFile = getLogFile(file.getPath(), null); this.loggingSystem.initialize(loggingInitializationContext, null, logFile); this.logger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(getLineWithText(output, "Hello world")).contains("INFO"); assertThat(getLineWithText(file, "Hello world")).doesNotContain("INFO"); } @Test - public void testCleanHistoryOnStartProperty() { + void testCleanHistoryOnStartProperty() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.clean-history-on-start", "true"); LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); @@ -348,7 +325,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testCleanHistoryOnStartPropertyWithXmlConfiguration() { + void testCleanHistoryOnStartPropertyWithXmlConfiguration() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.clean-history-on-start", "true"); LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); @@ -361,17 +338,17 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testMaxFileSizePropertyWithLogbackFileSize() { + void testMaxFileSizePropertyWithLogbackFileSize() { testMaxFileSizeProperty("100 MB", "100 MB"); } @Test - public void testMaxFileSizePropertyWithDataSize() { + void testMaxFileSizePropertyWithDataSize() { testMaxFileSizeProperty("15MB", "15 MB"); } @Test - public void testMaxFileSizePropertyWithBytesValue() { + void testMaxFileSizePropertyWithBytesValue() { testMaxFileSizeProperty(String.valueOf(10 * 1024 * 1024), "10 MB"); } @@ -389,7 +366,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testMaxFileSizePropertyWithXmlConfiguration() { + void testMaxFileSizePropertyWithXmlConfiguration() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.max-size", "100MB"); LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); @@ -402,7 +379,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testMaxHistoryProperty() { + void testMaxHistoryProperty() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.max-history", "30"); LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); @@ -415,7 +392,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testMaxHistoryPropertyWithXmlConfiguration() throws Exception { + void testMaxHistoryPropertyWithXmlConfiguration() { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.max-history", "30"); LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); @@ -428,17 +405,17 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testTotalSizeCapPropertyWithLogbackFileSize() { + void testTotalSizeCapPropertyWithLogbackFileSize() { testTotalSizeCapProperty("101 MB", "101 MB"); } @Test - public void testTotalSizeCapPropertyWithDataSize() { + void testTotalSizeCapPropertyWithDataSize() { testTotalSizeCapProperty("10MB", "10 MB"); } @Test - public void testTotalSizeCapPropertyWithBytesValue() { + void testTotalSizeCapPropertyWithBytesValue() { testTotalSizeCapProperty(String.valueOf(10 * 1024 * 1024), "10 MB"); } @@ -456,7 +433,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testTotalSizeCapPropertyWithXmlConfiguration() { + void testTotalSizeCapPropertyWithXmlConfiguration() { String expectedSize = "101 MB"; MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.file.total-size-cap", expectedSize); @@ -470,29 +447,26 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void exceptionsIncludeClassPackaging() { + void exceptionsIncludeClassPackaging(CapturedOutput output) { this.loggingSystem.beforeInitialize(); this.loggingSystem.initialize(this.initializationContext, null, getLogFile(null, tmpDir())); - Matcher expectedOutput = containsString("[junit-"); - this.output.expect(expectedOutput); this.logger.warn("Expected exception", new RuntimeException("Expected")); String fileContents = contentOf(new File(tmpDir() + "/spring.log")); - assertThat(fileContents).is(Matched.by(expectedOutput)); + assertThat(fileContents).contains("[junit-"); + assertThat(output).contains("[junit-"); } @Test - public void customExceptionConversionWord() { + void customExceptionConversionWord(CapturedOutput output) { System.setProperty(LoggingSystemProperties.EXCEPTION_CONVERSION_WORD, "%ex"); try { this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); this.loggingSystem.initialize(this.initializationContext, null, getLogFile(null, tmpDir())); - Matcher expectedOutput = Matchers.allOf(containsString("java.lang.RuntimeException: Expected"), - not(containsString("Wrapped by:"))); - this.output.expect(expectedOutput); this.logger.warn("Expected exception", new RuntimeException("Expected", new RuntimeException("Cause"))); String fileContents = contentOf(new File(tmpDir() + "/spring.log")); - assertThat(fileContents).is(Matched.by(expectedOutput)); + assertThat(fileContents).contains("java.lang.RuntimeException: Expected").doesNotContain("Wrapped by:"); + assertThat(output).contains("java.lang.RuntimeException: Expected").doesNotContain("Wrapped by:"); } finally { System.clearProperty(LoggingSystemProperties.EXCEPTION_CONVERSION_WORD); @@ -500,7 +474,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void initializeShouldSetSystemProperty() { + void initializeShouldSetSystemProperty() { // gh-5491 this.loggingSystem.beforeInitialize(); this.logger.info("Hidden"); @@ -510,7 +484,7 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void initializationIsOnlyPerformedOnceUntilCleanedUp() { + void initializationIsOnlyPerformedOnceUntilCleanedUp() { LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory(); LoggerContextListener listener = mock(LoggerContextListener.class); loggerContext.addListener(listener); @@ -527,37 +501,34 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { } @Test - public void testDateformatPatternProperty() { + void testDateformatPatternProperty(CapturedOutput output) { MockEnvironment environment = new MockEnvironment(); environment.setProperty("logging.pattern.dateformat", "yyyy-MM-dd'T'hh:mm:ss.SSSZ"); LoggingInitializationContext loggingInitializationContext = new LoggingInitializationContext(environment); this.loggingSystem.initialize(loggingInitializationContext, null, null); this.logger.info("Hello world"); - String output = this.output.toString().trim(); assertThat(getLineWithText(output, "Hello world")) .containsPattern("\\d{4}-\\d{2}\\-\\d{2}T\\d{2}:\\d{2}:\\d{2}"); } @Test - public void noDebugOutputIsProducedByDefault() { + void noDebugOutputIsProducedByDefault(CapturedOutput output) { System.clearProperty("logback.debug"); this.loggingSystem.beforeInitialize(); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); this.loggingSystem.initialize(this.initializationContext, null, logFile); - String output = this.output.toString().trim(); assertThat(output).doesNotContain("LevelChangePropagator").doesNotContain("SizeAndTimeBasedFNATP"); } @Test - public void logbackDebugPropertyIsHonored() { + void logbackDebugPropertyIsHonored(CapturedOutput output) { System.setProperty("logback.debug", "true"); try { this.loggingSystem.beforeInitialize(); File file = new File(tmpDir(), "logback-test.log"); LogFile logFile = getLogFile(file.getPath(), null); this.loggingSystem.initialize(this.initializationContext, null, logFile); - String output = this.output.toString().trim(); assertThat(output).contains("LevelChangePropagator").contains("SizeAndTimeBasedFNATP") .contains("DebugLogbackConfigurator"); } @@ -584,18 +555,13 @@ public class LogbackLoggingSystemTests extends AbstractLoggingSystemTests { return (SizeAndTimeBasedRollingPolicy) getFileAppender().getRollingPolicy(); } - private String getLineWithText(File file, String outputSearch) { + private String getLineWithText(File file, CharSequence outputSearch) { return getLineWithText(contentOf(file), outputSearch); } - private String getLineWithText(String output, String outputSearch) { - String[] lines = output.split("\\r?\\n"); - for (String line : lines) { - if (line.contains(outputSearch)) { - return line; - } - } - return null; + private String getLineWithText(CharSequence output, CharSequence outputSearch) { + return Arrays.stream(output.toString().split("\\r?\\n")).filter((line) -> line.contains(outputSearch)) + .findFirst().orElse(null); } } diff --git a/src/checkstyle/checkstyle-suppressions.xml b/src/checkstyle/checkstyle-suppressions.xml index 1c17da90188..eccbefc1b93 100644 --- a/src/checkstyle/checkstyle-suppressions.xml +++ b/src/checkstyle/checkstyle-suppressions.xml @@ -42,8 +42,6 @@ - - From df5d23ff6cd94113de018ca039df44f1c139609d Mon Sep 17 00:00:00 2001 From: Andy Wilkinson Date: Sat, 29 Jun 2019 23:19:17 +0100 Subject: [PATCH 2/2] Polish "Migrate LogbackLoggingSystemTests to JUnit 5" See gh-17107 --- .../boot/logging/AbstractLoggingSystemTests.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java index e76a7dd266c..6c4b873d3ea 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/AbstractLoggingSystemTests.java @@ -38,18 +38,18 @@ public abstract class AbstractLoggingSystemTests { private String originalTempFolder; @BeforeEach - public void configureTempDir(@TempDir Path temp) { + void configureTempDir(@TempDir Path temp) { this.originalTempFolder = System.getProperty(JAVA_IO_TMPDIR); System.setProperty(JAVA_IO_TMPDIR, temp.toAbsolutePath().toString()); } @AfterEach - public void reinstateTempDir() { + void reinstateTempDir() { System.setProperty(JAVA_IO_TMPDIR, this.originalTempFolder); } @AfterEach - public void clear() { + void clear() { System.clearProperty(LoggingSystemProperties.LOG_FILE); System.clearProperty(LoggingSystemProperties.PID_KEY); }