From a64ba9c94066c121ce8b8a91209fc3d199915e04 Mon Sep 17 00:00:00 2001 From: "James R. Perkins" Date: Thu, 18 Jan 2024 07:31:47 -0800 Subject: [PATCH] Migrate tests to keep the log files that were created. Put the log files into a directory with the test name and method name. Signed-off-by: James R. Perkins --- .github/workflows/maven.yml | 8 + .../handlers/AbstractHandlerTest.java | 97 ++++++----- ...riodicRotatingFileHandlerFailureTests.java | 11 +- .../PeriodicRotatingFileHandlerTests.java | 17 +- ...icSizeRotatingFileHandlerFailureTests.java | 20 ++- .../PeriodicSizeRotatingFileHandlerTests.java | 164 +++++++++--------- .../SizeRotatingFileHandlerTests.java | 103 +++++------ 7 files changed, 217 insertions(+), 203 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index d0c2a0cf..801dbdc4 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -37,6 +37,14 @@ jobs: 21 - name: Build and Test run: mvn -B clean verify "-Djava11.home=${{env.JAVA_HOME_11_X64}}" "-Djava17.home=${{env.JAVA_HOME_17_X64}}" + - uses: actions/upload-artifact@v4 + if: failure() + with: + name: surefire-reports-${{ matrix.os }}-${{ matrix.java }} + path: | + **/logs/ + **/failsafe-reports/ + **/surefire-reports/ format-check: runs-on: ubuntu-latest diff --git a/src/test/java/org/jboss/logmanager/handlers/AbstractHandlerTest.java b/src/test/java/org/jboss/logmanager/handlers/AbstractHandlerTest.java index 7e0a20f0..ff708d5f 100644 --- a/src/test/java/org/jboss/logmanager/handlers/AbstractHandlerTest.java +++ b/src/test/java/org/jboss/logmanager/handlers/AbstractHandlerTest.java @@ -20,7 +20,6 @@ package org.jboss.logmanager.handlers; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; @@ -32,74 +31,80 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.List; +import java.util.stream.Stream; import java.util.zip.GZIPInputStream; import org.jboss.logmanager.ExtHandler; import org.jboss.logmanager.ExtLogRecord; import org.jboss.logmanager.formatters.PatternFormatter; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; /** * @author James R. Perkins */ public class AbstractHandlerTest { - static final File BASE_LOG_DIR; + + private static final Path BASE_LOG_DIR; static { - BASE_LOG_DIR = new File(System.getProperty("log.dir")); + BASE_LOG_DIR = Path.of(System.getProperty("log.dir")); } final static PatternFormatter FORMATTER = new PatternFormatter("%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"); + private TestInfo testInfo; + @BeforeEach - public void setup() throws Exception { - BASE_LOG_DIR.mkdir(); - } - - @AfterEach - public void cleanUp() throws Exception { - deleteChildrenRecursively(BASE_LOG_DIR); - } - - static boolean deleteRecursively(final File dir) { - if (dir.isDirectory()) { - final File[] files = dir.listFiles(); - if (files != null) { - for (final File f : files) { - if (f.isDirectory()) { - if (!deleteRecursively(f)) { - return false; - } - } - if (!f.delete()) { - return false; - } - } - } + public void setup(final TestInfo testInfo) throws Exception { + this.testInfo = testInfo; + deletePath(logDirectory(testInfo)); + } + + @Test + public void simple() { + Assertions.assertTrue(testInfo.getTestMethod().isPresent()); + } + + protected Path resolvePath(final String filename) throws IOException { + return logDirectory().resolve(filename); + } + + protected Path logDirectory() throws IOException { + return logDirectory(testInfo); + } + + protected Path logDirectory(final TestInfo testInfo) throws IOException { + Assertions.assertTrue(testInfo.getTestClass().isPresent()); + Assertions.assertTrue(testInfo.getTestMethod().isPresent()); + final Path dir = BASE_LOG_DIR + .resolve(testInfo.getTestClass().get().getSimpleName() + "-" + testInfo.getTestMethod().get().getName()); + if (Files.notExists(dir)) { + Files.createDirectories(dir); } - return dir.delete(); - } - - static boolean deleteChildrenRecursively(final File dir) { - if (dir.isDirectory()) { - final File[] files = dir.listFiles(); - if (files != null) { - for (final File f : files) { - if (f.isDirectory()) { - if (!deleteRecursively(f)) { - return false; - } - } - if (!f.delete()) { - return false; - } - } + return dir; + } + + private static void deletePath(final Path path) throws IOException { + if (Files.isDirectory(path)) { + try (Stream paths = Files.walk(path)) { + paths.sorted(Comparator.reverseOrder()) + .forEach(p -> { + try { + Files.delete(p); + } catch (IOException e) { + System.out.printf("Failed to delete path %s%n", p); + e.printStackTrace(System.out); + } + }); } + } else { + Files.delete(path); } - return true; } protected static void configureHandlerDefaults(final ExtHandler handler) { diff --git a/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerFailureTests.java b/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerFailureTests.java index 8019ff66..73db5fa3 100644 --- a/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerFailureTests.java +++ b/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerFailureTests.java @@ -19,7 +19,7 @@ package org.jboss.logmanager.handlers; -import java.io.FileNotFoundException; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -44,13 +44,16 @@ public class PeriodicRotatingFileHandlerFailureTests extends AbstractHandlerTest { private final static String FILENAME = "periodic-rotating-file-handler.log"; - private final Path logFile = BASE_LOG_DIR.toPath().resolve(FILENAME); + private Path logFile; private final SimpleDateFormat rotateFormatter = new SimpleDateFormat(".dd"); private PeriodicRotatingFileHandler handler; @BeforeEach - public void createHandler() throws FileNotFoundException { + public void createHandler() throws IOException { + if (logFile == null) { + logFile = resolvePath(FILENAME); + } // Create the handler handler = new PeriodicRotatingFileHandler(logFile.toFile(), rotateFormatter.toPattern(), false); handler.setFormatter(FORMATTER); @@ -69,7 +72,7 @@ public void closeHandler() { @BMRule(name = "Test failed rotated", targetClass = "java.nio.file.Files", targetMethod = "move", targetLocation = "AT ENTRY", condition = "$2.getFileName().toString().matches(\"periodic-rotating-file-handler\\\\.log\\\\.\\\\d+\")", action = "throw new IOException(\"Fail on purpose\")") public void testFailedRotate() throws Exception { final Calendar cal = Calendar.getInstance(); - final Path rotatedFile = BASE_LOG_DIR.toPath().resolve(FILENAME + rotateFormatter.format(cal.getTime())); + final Path rotatedFile = resolvePath(FILENAME + rotateFormatter.format(cal.getTime())); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); final int currentDay = cal.get(Calendar.DAY_OF_MONTH); final int nextDay = currentDay + 1; diff --git a/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerTests.java index ae8da07d..0f927cda 100644 --- a/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerTests.java +++ b/src/test/java/org/jboss/logmanager/handlers/PeriodicRotatingFileHandlerTests.java @@ -20,7 +20,7 @@ package org.jboss.logmanager.handlers; import java.io.BufferedWriter; -import java.io.FileNotFoundException; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -47,13 +47,16 @@ public class PeriodicRotatingFileHandlerTests extends AbstractHandlerTest { private final static String FILENAME = "periodic-rotating-file-handler.log"; - private final Path logFile = BASE_LOG_DIR.toPath().resolve(FILENAME); + private Path logFile; private final SimpleDateFormat rotateFormatter = new SimpleDateFormat(".dd"); private PeriodicRotatingFileHandler handler; @BeforeEach - public void createHandler() throws FileNotFoundException { + public void createHandler() throws IOException { + if (logFile == null) { + logFile = resolvePath(FILENAME); + } // Create the handler handler = new PeriodicRotatingFileHandler(logFile.toFile(), rotateFormatter.toPattern(), false); handler.setFormatter(FORMATTER); @@ -71,14 +74,14 @@ public void closeHandler() { @Test public void testRotate() throws Exception { final Calendar cal = Calendar.getInstance(); - final Path rotatedFile = BASE_LOG_DIR.toPath().resolve(FILENAME + rotateFormatter.format(cal.getTime())); + final Path rotatedFile = resolvePath(FILENAME + rotateFormatter.format(cal.getTime())); testRotate(cal, rotatedFile); } @Test public void testOverwriteRotate() throws Exception { final Calendar cal = Calendar.getInstance(); - final Path rotatedFile = BASE_LOG_DIR.toPath().resolve(FILENAME + rotateFormatter.format(cal.getTime())); + final Path rotatedFile = resolvePath(FILENAME + rotateFormatter.format(cal.getTime())); // Create the rotated file to ensure at some point it gets overwritten Files.deleteIfExists(rotatedFile); @@ -102,7 +105,7 @@ public void testArchiveRotateZip() throws Exception { @BMRule(name = "Test failed rotated", targetClass = "java.nio.file.Files", targetMethod = "move", targetLocation = "AT ENTRY", condition = "$2.getFileName().toString().matches(\"periodic-rotating-file-handler\\\\.log\\\\.\\\\d+\")", action = "throw new IOException(\"Fail on purpose\")") public void testFailedRotate() throws Exception { final Calendar cal = Calendar.getInstance(); - final Path rotatedFile = BASE_LOG_DIR.toPath().resolve(FILENAME + rotateFormatter.format(cal.getTime())); + final Path rotatedFile = resolvePath(FILENAME + rotateFormatter.format(cal.getTime())); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); final int currentDay = cal.get(Calendar.DAY_OF_MONTH); final int nextDay = currentDay + 1; @@ -209,7 +212,7 @@ record = createLogRecord(Level.INFO, "Date: %s", thirdDay); handler.publish(record); // There should be three files - final Path logDir = BASE_LOG_DIR.toPath(); + final Path logDir = logDirectory(); final Path rotated1 = logDir.resolve(FILENAME + firstDateSuffix + archiveSuffix); final Path rotated2 = logDir.resolve(FILENAME + secondDateSuffix + archiveSuffix); Assertions.assertTrue(Files.exists(logFile), () -> "Missing file " + logFile); diff --git a/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerFailureTests.java b/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerFailureTests.java index 2698996e..af0bb8b0 100644 --- a/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerFailureTests.java +++ b/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerFailureTests.java @@ -19,7 +19,7 @@ package org.jboss.logmanager.handlers; -import java.io.File; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -29,6 +29,7 @@ import org.jboss.byteman.contrib.bmunit.BMRule; import org.jboss.byteman.contrib.bmunit.WithByteman; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** @@ -38,7 +39,14 @@ public class PeriodicSizeRotatingFileHandlerFailureTests extends AbstractHandlerTest { private final static String FILENAME = "rotating-file-handler.log"; - private final File logFile = new File(BASE_LOG_DIR, FILENAME); + private Path logFile; + + @BeforeEach + public void setup() throws IOException { + if (logFile == null) { + logFile = resolvePath(FILENAME); + } + } @Test @BMRule(name = "Test failed rotated", targetClass = "java.nio.file.Files", targetMethod = "move", targetLocation = "AT ENTRY", condition = "$2.getFileName().toString().equals(\"rotating-file-handler.log.2\")", action = "throw new IOException(\"Fail on purpose\")") @@ -48,7 +56,7 @@ public void testFailedRotate() throws Exception { handler.setErrorManager(AssertingErrorManager.of(ErrorManager.GENERIC_FAILURE)); handler.setRotateSize(1024L); handler.setMaxBackupIndex(5); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); // Allow a few rotates for (int i = 0; i < 100; i++) { @@ -58,12 +66,12 @@ public void testFailedRotate() throws Exception { handler.close(); // The log file should exist, as should one rotated file since we fail the rotation on the second rotate - Assertions.assertTrue(logFile.exists(), () -> String.format("Expected log file %s to exist", logFile)); - final Path rotatedFile = BASE_LOG_DIR.toPath().resolve(FILENAME + ".1"); + Assertions.assertTrue(Files.exists(logFile), () -> String.format("Expected log file %s to exist", logFile)); + final Path rotatedFile = resolvePath(FILENAME + ".1"); Assertions.assertTrue(Files.exists(rotatedFile), () -> String.format("Expected rotated file %s to exist", rotatedFile)); // The last line of the log file should end with "99" as it should be the last record - final List lines = Files.readAllLines(logFile.toPath(), StandardCharsets.UTF_8); + final List lines = Files.readAllLines(logFile, StandardCharsets.UTF_8); final String lastLine = lines.get(lines.size() - 1); Assertions.assertTrue(lastLine.endsWith("99"), "Expected the last line to end with 99: " + lastLine); } diff --git a/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerTests.java index a0e222dd..f37dd264 100644 --- a/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerTests.java +++ b/src/test/java/org/jboss/logmanager/handlers/PeriodicSizeRotatingFileHandlerTests.java @@ -19,7 +19,7 @@ package org.jboss.logmanager.handlers; -import java.io.File; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -32,11 +32,13 @@ import java.util.List; import java.util.Map; import java.util.logging.ErrorManager; +import java.util.stream.Stream; import org.jboss.byteman.contrib.bmunit.BMRule; import org.jboss.byteman.contrib.bmunit.WithByteman; import org.jboss.logmanager.ExtLogRecord; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -47,7 +49,7 @@ public class PeriodicSizeRotatingFileHandlerTests extends AbstractHandlerTest { private final static String FILENAME = "rotating-file-handler.log"; - private final File logFile = new File(BASE_LOG_DIR, FILENAME); + private Path logFile; private static final List supportedPeriods = new ArrayList(); private static final Map periodFormatMap = new HashMap(); @@ -71,6 +73,13 @@ public class PeriodicSizeRotatingFileHandlerTests extends AbstractHandlerTest { periodFormatMap.put(Calendar.MINUTE, new SimpleDateFormat("yyyy-MM-dd-HH-mm")); } + @BeforeEach + public void setup() throws IOException { + if (logFile == null) { + logFile = resolvePath(FILENAME); + } + } + @Test public void testSizeRotate() throws Exception { final SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); @@ -82,7 +91,7 @@ public void testSizeRotate() throws Exception { handler.setRotateSize(1024L); handler.setMaxBackupIndex(2); handler.setSuffix("." + fmt.toPattern()); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); // Allow a few rotates for (int i = 0; i < 100; i++) { @@ -92,15 +101,11 @@ public void testSizeRotate() throws Exception { handler.close(); // We should end up with 3 files, 2 rotated and the default log - final File file1 = new File(BASE_LOG_DIR, FILENAME + extension + ".1"); - final File file2 = new File(BASE_LOG_DIR, FILENAME + extension + ".2"); - Assertions.assertTrue(logFile.exists()); - Assertions.assertTrue(file1.exists()); - Assertions.assertTrue(file2.exists()); - - // Clean up files - file1.delete(); - file2.delete(); + final Path file1 = resolvePath(FILENAME + extension + ".1"); + final Path file2 = resolvePath(FILENAME + extension + ".2"); + Assertions.assertTrue(Files.exists(logFile)); + Assertions.assertTrue(Files.exists(file1)); + Assertions.assertTrue(Files.exists(file2)); } @Test @@ -116,11 +121,11 @@ public void testBootRotate() throws Exception { handler.setMaxBackupIndex(1); handler.setSuffix("." + fmt.toPattern()); handler.setRotateOnBoot(true); - handler.setFile(logFile); - final File rotatedFile = new File(BASE_LOG_DIR, FILENAME + extension + ".1"); + handler.setFile(logFile.toFile()); + final Path rotatedFile = resolvePath(FILENAME + extension + ".1"); // The rotated file should not exist - Assertions.assertFalse(rotatedFile.exists(), "Rotated file should not exist"); + Assertions.assertFalse(Files.exists(rotatedFile), "Rotated file should not exist"); // Log a few records for (int i = 0; i < 5; i++) { @@ -129,20 +134,20 @@ public void testBootRotate() throws Exception { // Close the handler and create a new one handler.close(); - final long size = logFile.length(); + final long size = Files.size(logFile); handler = new PeriodicSizeRotatingFileHandler(); configureHandlerDefaults(handler); handler.setRotateSize(5000L); handler.setMaxBackupIndex(1); handler.setSuffix("." + fmt.toPattern()); handler.setRotateOnBoot(true); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); // The rotated file should exist - Assertions.assertTrue(rotatedFile.exists(), "Rotated file should exist"); + Assertions.assertTrue(Files.exists(rotatedFile), "Rotated file should exist"); // Rotated file size should match the size of the previous file - Assertions.assertEquals(size, rotatedFile.length()); + Assertions.assertEquals(size, Files.size(rotatedFile)); // Log a few records for (int i = 0; i < 10; i++) { @@ -152,15 +157,12 @@ public void testBootRotate() throws Exception { handler.close(); // File should have been rotated - Assertions.assertTrue(logFile.exists()); - Assertions.assertTrue(rotatedFile.exists()); + Assertions.assertTrue(Files.exists(logFile)); + Assertions.assertTrue(Files.exists(rotatedFile)); // Neither file should be empty - Assertions.assertTrue(logFile.length() > 0L); - Assertions.assertTrue(rotatedFile.length() > 0L); - - // Clean up files - rotatedFile.delete(); + Assertions.assertTrue(Files.size(logFile) > 0L); + Assertions.assertTrue(Files.size(rotatedFile) > 0L); } @Test @@ -216,7 +218,7 @@ public void testFailedRotate() throws Exception { handler.setErrorManager(AssertingErrorManager.of(ErrorManager.GENERIC_FAILURE)); handler.setRotateSize(1024L); handler.setMaxBackupIndex(5); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); // Allow a few rotates for (int i = 0; i < 100; i++) { @@ -226,12 +228,12 @@ public void testFailedRotate() throws Exception { handler.close(); // The log file should exist, as should one rotated file since we fail the rotation on the second rotate - Assertions.assertTrue(logFile.exists(), () -> String.format("Expected log file %s to exist", logFile)); - final Path rotatedFile = BASE_LOG_DIR.toPath().resolve(FILENAME + ".1"); + Assertions.assertTrue(Files.exists(logFile), () -> String.format("Expected log file %s to exist", logFile)); + final Path rotatedFile = resolvePath(FILENAME + ".1"); Assertions.assertTrue(Files.exists(rotatedFile), () -> String.format("Expected rotated file %s to exist", rotatedFile)); // The last line of the log file should end with "99" as it should be the last record - final List lines = Files.readAllLines(logFile.toPath(), StandardCharsets.UTF_8); + final List lines = Files.readAllLines(logFile, StandardCharsets.UTF_8); final String lastLine = lines.get(lines.size() - 1); Assertions.assertTrue(lastLine.endsWith("99"), "Expected the last line to end with 99: " + lastLine); } @@ -244,7 +246,7 @@ private void testArchiveRotate(final String dateSuffix, final String archiveSuff handler.setRotateSize(1024L); handler.setMaxBackupIndex(2); handler.setRotateOnBoot(rotateOnBoot); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); handler.setSuffix((dateSuffix == null ? "" : dateSuffix) + archiveSuffix); // Set append to true to ensure the rotated file is overwritten handler.setAppend(true); @@ -257,10 +259,10 @@ private void testArchiveRotate(final String dateSuffix, final String archiveSuff handler.close(); // We should end up with 3 files, 2 rotated and the default log - final Path logDir = BASE_LOG_DIR.toPath(); + final Path logDir = logDirectory(); final Path path1 = logDir.resolve(FILENAME + currentDate + ".1" + archiveSuffix); final Path path2 = logDir.resolve(FILENAME + currentDate + ".2" + archiveSuffix); - Assertions.assertTrue(logFile.exists()); + Assertions.assertTrue(Files.exists(logDir)); Assertions.assertTrue(Files.exists(path1)); Assertions.assertTrue(Files.exists(path2)); @@ -269,17 +271,13 @@ private void testArchiveRotate(final String dateSuffix, final String archiveSuff validateGzipContents(path1, "Test message:"); validateGzipContents(path2, "Test message:"); } else if (archiveSuffix.endsWith(".zip")) { - validateZipContents(path1, logFile.getName(), "Test message:"); - validateZipContents(path2, logFile.getName(), "Test message:"); + validateZipContents(path1, logFile.getFileName().toString(), "Test message:"); + validateZipContents(path2, logFile.getFileName().toString(), "Test message:"); } else { Assertions.fail("Unknown archive suffix: " + archiveSuffix); } - compareArchiveContents(path1, path2, logFile.getName()); - - // Clean up files - Files.deleteIfExists(path1); - Files.deleteIfExists(path2); + compareArchiveContents(path1, path2, logFile.getFileName().toString()); } private void testPeriodicAndSizeRotate0(int handlerPeriod, int logMessagePeriod, boolean testSize) throws Exception { @@ -298,23 +296,24 @@ private void testPeriodicAndSizeRotate0(int handlerPeriod, int logMessagePeriod, handler.setRotateSize(rotateSize); handler.setMaxBackupIndex(2); handler.setSuffix("." + fmt.toPattern()); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); // Write a record for (int i = 0; i < logCount; i++) { handler.publish(createLogRecord("Test message: %d", i)); } - File rotatedFile1, rotatedFile2; + Path rotatedFile1, rotatedFile2; if (testSize) { - rotatedFile1 = new File(BASE_LOG_DIR, FILENAME + extension + ".1"); - rotatedFile2 = new File(BASE_LOG_DIR, FILENAME + extension + ".2"); + rotatedFile1 = resolvePath(FILENAME + extension + ".1"); + rotatedFile2 = resolvePath(FILENAME + extension + ".2"); // File should have been rotated - String message = "Log should have rotated, but it did not\n"; - Assertions.assertTrue(logFile.exists()); - Assertions.assertTrue(rotatedFile1.exists(), message + rotatedFile1.getPath()); - Assertions.assertTrue(rotatedFile2.exists(), message + rotatedFile2.getPath()); + Assertions.assertTrue(Files.exists(logFile)); + Assertions.assertTrue(Files.exists(rotatedFile1), + String.format("Log should have rotated, but it did not%n%s", rotatedFile1)); + Assertions.assertTrue(Files.exists(rotatedFile2), + String.format("Log should have rotated, but it did not%n%s", rotatedFile2)); } // Increase the calender to force a rotation @@ -333,35 +332,28 @@ private void testPeriodicAndSizeRotate0(int handlerPeriod, int logMessagePeriod, // The extension name will be the new period since the size rotation // has happened since the date rotation extension = "." + fmt.format(cal.getTimeInMillis()); - rotatedFile1 = new File(BASE_LOG_DIR, FILENAME + extension + ".1"); - rotatedFile2 = new File(BASE_LOG_DIR, FILENAME + extension + ".2"); + rotatedFile1 = resolvePath(FILENAME + extension + ".1"); + rotatedFile2 = resolvePath(FILENAME + extension + ".2"); } else { // The extension name will still be the old period since no size rotation // has happened to bump up the new period - rotatedFile1 = new File(BASE_LOG_DIR, FILENAME + extension); - rotatedFile2 = new File(BASE_LOG_DIR, FILENAME + extension); + rotatedFile1 = resolvePath(FILENAME + extension); + rotatedFile2 = resolvePath(FILENAME + extension); } - Assertions.assertTrue(logFile.exists()); - Assertions.assertTrue(logFile.length() > 0L); - - try { - ErrorCreator errorCreator = new ErrorCreator(handlerPeriod, logMessagePeriod, testSize); - if (shouldRotate(logMessagePeriod, handlerPeriod, testSize)) { - Assertions.assertTrue(rotatedFile1.exists(), errorCreator.create(true, rotatedFile1)); - Assertions.assertTrue(rotatedFile2.exists(), errorCreator.create(true, rotatedFile2)); - Assertions.assertTrue(rotatedFile1.length() > 0L); - Assertions.assertTrue(rotatedFile2.length() > 0L); - } else { - Assertions.assertFalse(rotatedFile1.exists(), errorCreator.create(false, rotatedFile1)); - Assertions.assertFalse(rotatedFile2.exists(), errorCreator.create(false, rotatedFile2)); - Assertions.assertFalse(rotatedFile1.length() > 0L); - Assertions.assertFalse(rotatedFile2.length() > 0L); - } - } finally { - for (String logFile : BASE_LOG_DIR.list()) { - new File(BASE_LOG_DIR + File.separator + logFile).delete(); - } + Assertions.assertTrue(Files.exists(logFile)); + Assertions.assertTrue(Files.size(logFile) > 0L); + ErrorCreator errorCreator = new ErrorCreator(handlerPeriod, logMessagePeriod, testSize); + if (shouldRotate(logMessagePeriod, handlerPeriod, testSize)) { + Assertions.assertTrue(Files.exists(rotatedFile1), errorCreator.create(true, rotatedFile1)); + Assertions.assertTrue(Files.exists(rotatedFile2), errorCreator.create(true, rotatedFile2)); + Assertions.assertTrue(Files.size(rotatedFile1) > 0L); + Assertions.assertTrue(Files.size(rotatedFile2) > 0L); + } else { + Assertions.assertFalse(Files.exists(rotatedFile1), errorCreator.create(true, rotatedFile1)); + Assertions.assertFalse(Files.exists(rotatedFile2), errorCreator.create(true, rotatedFile2)); + Assertions.assertFalse(Files.size(rotatedFile1) > 0L); + Assertions.assertFalse(Files.size(rotatedFile2) > 0L); } } @@ -399,7 +391,7 @@ private static boolean isPeriodOneLess(int period1, int period2) { return (supportedPeriods.indexOf(period1) - supportedPeriods.indexOf(period2)) == 1; } - private static final class ErrorCreator { + private final class ErrorCreator { private int handlerPeriod, logMessagePeriod; private boolean testSize; @@ -409,25 +401,27 @@ public ErrorCreator(int handlerPeriod, int logMessagePeriod, boolean testSize) { this.testSize = testSize; } - public String create(boolean expectRotation, File log) throws Exception { + public String create(boolean expectRotation, Path log) throws Exception { StringBuilder builder = new StringBuilder(); if (expectRotation) { - builder.append("Expected log rotation, but it didn't happen\n"); + builder.append("Expected log rotation, but it didn't happen").append(System.lineSeparator()); } else { - builder.append("Expected NO log rotation, but it happened anyways\n"); + builder.append("Expected NO log rotation, but it happened anyways").append(System.lineSeparator()); } - builder.append("Handler: " + periodFormatMap.get(handlerPeriod).toPattern()); + builder.append("Handler: ").append(periodFormatMap.get(handlerPeriod).toPattern()); builder.append(" ; "); - builder.append("Message: " + periodFormatMap.get(logMessagePeriod).toPattern()); + builder.append("Message: ").append(periodFormatMap.get(logMessagePeriod).toPattern()); builder.append(" ; "); - builder.append("testSize=" + testSize); - - builder.append("\nChecking for log file here: "); - builder.append(log.getPath() + "\n"); - builder.append("List of log files:\n"); - for (String f : BASE_LOG_DIR.list()) { - builder.append("\t" + f + "\n"); + builder.append("testSize=").append(testSize); + + builder.append(System.lineSeparator()).append("Checking for log file here: "); + builder.append(log).append(System.lineSeparator()); + builder.append("List of log files:").append(System.lineSeparator()); + try (Stream paths = Files.walk(logDirectory())) { + paths.forEach(path -> { + builder.append('\t').append(path).append(System.lineSeparator()); + }); } builder.append("-- End of listing --"); return builder.toString(); diff --git a/src/test/java/org/jboss/logmanager/handlers/SizeRotatingFileHandlerTests.java b/src/test/java/org/jboss/logmanager/handlers/SizeRotatingFileHandlerTests.java index decbe516..d5465b18 100644 --- a/src/test/java/org/jboss/logmanager/handlers/SizeRotatingFileHandlerTests.java +++ b/src/test/java/org/jboss/logmanager/handlers/SizeRotatingFileHandlerTests.java @@ -19,7 +19,7 @@ package org.jboss.logmanager.handlers; -import java.io.File; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -31,6 +31,7 @@ import org.jboss.byteman.contrib.bmunit.BMRule; import org.jboss.byteman.contrib.bmunit.WithByteman; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** @@ -40,7 +41,14 @@ public class SizeRotatingFileHandlerTests extends AbstractHandlerTest { private final static String FILENAME = "rotating-file-handler.log"; - private final File logFile = new File(BASE_LOG_DIR, FILENAME); + private Path logFile; + + @BeforeEach + public void setup() throws IOException { + if (logFile == null) { + logFile = resolvePath(FILENAME); + } + } @Test public void testSizeRotate() throws Exception { @@ -48,7 +56,7 @@ public void testSizeRotate() throws Exception { configureHandlerDefaults(handler); handler.setRotateSize(1024L); handler.setMaxBackupIndex(2); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); // Allow a few rotates for (int i = 0; i < 100; i++) { @@ -58,15 +66,11 @@ public void testSizeRotate() throws Exception { handler.close(); // We should end up with 3 files, 2 rotated and the default log - final File file1 = new File(BASE_LOG_DIR, FILENAME + ".1"); - final File file2 = new File(BASE_LOG_DIR, FILENAME + ".2"); - Assertions.assertTrue(logFile.exists()); - Assertions.assertTrue(file1.exists()); - Assertions.assertTrue(file2.exists()); - - // Clean up files - file1.delete(); - file2.delete(); + final Path file1 = resolvePath(FILENAME + ".1"); + final Path file2 = resolvePath(FILENAME + ".2"); + Assertions.assertTrue(Files.exists(logFile)); + Assertions.assertTrue(Files.exists(file1)); + Assertions.assertTrue(Files.exists(file2)); } @Test @@ -75,7 +79,7 @@ public void testSuffixSizeRotate() throws Exception { configureHandlerDefaults(handler); handler.setRotateSize(1024L); handler.setMaxBackupIndex(2); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); handler.setSuffix(".yyyy-MM-dd"); // Allow a few rotates @@ -90,15 +94,11 @@ public void testSuffixSizeRotate() throws Exception { final String suffix = sdf.format(new Date()); // We should end up with 3 files, 2 rotated and the default log - final File file1 = new File(BASE_LOG_DIR, FILENAME + suffix + ".1"); - final File file2 = new File(BASE_LOG_DIR, FILENAME + suffix + ".2"); - Assertions.assertTrue(logFile.exists()); - Assertions.assertTrue(file1.exists()); - Assertions.assertTrue(file2.exists()); - - // Clean up files - file1.delete(); - file2.delete(); + final Path file1 = resolvePath(FILENAME + suffix + ".1"); + final Path file2 = resolvePath(FILENAME + suffix + ".2"); + Assertions.assertTrue(Files.exists(logFile)); + Assertions.assertTrue(Files.exists(file1)); + Assertions.assertTrue(Files.exists(file2)); } @Test @@ -109,11 +109,11 @@ public void testBootRotate() throws Exception { handler.setRotateSize(5000L); handler.setMaxBackupIndex(1); handler.setRotateOnBoot(true); - handler.setFile(logFile); - final File rotatedFile = new File(BASE_LOG_DIR, FILENAME + ".1"); + handler.setFile(logFile.toFile()); + final Path rotatedFile = resolvePath(FILENAME + ".1"); // The rotated file should not exist - Assertions.assertFalse(rotatedFile.exists(), "Rotated file should not exist"); + Assertions.assertFalse(Files.exists(rotatedFile), "Rotated file should not exist"); // Log a few records for (int i = 0; i < 5; i++) { @@ -122,19 +122,19 @@ public void testBootRotate() throws Exception { // Close the handler and create a new one handler.close(); - final long size = logFile.length(); + final long size = Files.size(logFile); handler = new SizeRotatingFileHandler(); configureHandlerDefaults(handler); handler.setRotateSize(5000L); handler.setMaxBackupIndex(1); handler.setRotateOnBoot(true); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); // The rotated file should exist - Assertions.assertTrue(rotatedFile.exists(), "Rotated file should exist"); + Assertions.assertTrue(Files.exists(rotatedFile), "Rotated file should exist"); // Rotated file size should match the size of the previous file - Assertions.assertEquals(size, rotatedFile.length()); + Assertions.assertEquals(size, Files.size(rotatedFile)); // Log a few records for (int i = 0; i < 10; i++) { @@ -144,15 +144,12 @@ public void testBootRotate() throws Exception { handler.close(); // File should have been rotated - Assertions.assertTrue(logFile.exists()); - Assertions.assertTrue(rotatedFile.exists()); + Assertions.assertTrue(Files.exists(logFile)); + Assertions.assertTrue(Files.exists(rotatedFile)); // Neither file should be empty - Assertions.assertTrue(logFile.length() > 0L); - Assertions.assertTrue(rotatedFile.length() > 0L); - - // Clean up files - rotatedFile.delete(); + Assertions.assertTrue(Files.size(logFile) > 0L); + Assertions.assertTrue(Files.size(rotatedFile) > 0L); } @Test @@ -162,8 +159,8 @@ public void testBootRotateChange() throws Exception { // Enough to not rotate handler.setRotateSize(5000L); handler.setMaxBackupIndex(1); - handler.setFile(logFile); - final Path rotatedFile = BASE_LOG_DIR.toPath().resolve(FILENAME + ".1"); + handler.setFile(logFile.toFile()); + final Path rotatedFile = resolvePath(FILENAME + ".1"); // The rotated file should not exist Assertions.assertTrue(Files.notExists(rotatedFile), "Rotated file should not exist"); @@ -175,7 +172,7 @@ public void testBootRotateChange() throws Exception { // Configure the handler to rotate on boot and reset the file handler.setRotateOnBoot(true); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); // Log a few records for (int i = 0; i < 10; i++) { @@ -185,11 +182,11 @@ public void testBootRotateChange() throws Exception { handler.close(); // File should have been rotated - Assertions.assertTrue(logFile.exists()); + Assertions.assertTrue(Files.exists(logFile)); Assertions.assertTrue(Files.exists(rotatedFile)); // Neither file should be empty - Assertions.assertTrue(logFile.length() > 0L); + Assertions.assertTrue(Files.size(logFile) > 0L); Assertions.assertTrue(Files.size(rotatedFile) > 0L); } @@ -217,7 +214,7 @@ public void testFailedRotate() throws Exception { handler.setErrorManager(AssertingErrorManager.of(ErrorManager.GENERIC_FAILURE)); handler.setRotateSize(1024L); handler.setMaxBackupIndex(5); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); // Allow a few rotates for (int i = 0; i < 100; i++) { @@ -227,12 +224,12 @@ public void testFailedRotate() throws Exception { handler.close(); // The log file should exist, as should one rotated file since we fail the rotation on the second rotate - Assertions.assertTrue(logFile.exists(), () -> String.format("Expected log file %s to exist", logFile)); - final Path rotatedFile = BASE_LOG_DIR.toPath().resolve(FILENAME + ".1"); + Assertions.assertTrue(Files.exists(logFile), () -> String.format("Expected log file %s to exist", logFile)); + final Path rotatedFile = resolvePath(FILENAME + ".1"); Assertions.assertTrue(Files.exists(rotatedFile), () -> String.format("Expected rotated file %s to exist", rotatedFile)); // The last line of the log file should end with "99" as it should be the last record - final List lines = Files.readAllLines(logFile.toPath(), StandardCharsets.UTF_8); + final List lines = Files.readAllLines(logFile, StandardCharsets.UTF_8); final String lastLine = lines.get(lines.size() - 1); Assertions.assertTrue(lastLine.endsWith("99"), "Expected the last line to end with 99: " + lastLine); } @@ -243,7 +240,7 @@ private void testArchiveRotate(final String archiveSuffix, final boolean rotateO handler.setRotateSize(1024L); handler.setMaxBackupIndex(2); handler.setRotateOnBoot(rotateOnBoot); - handler.setFile(logFile); + handler.setFile(logFile.toFile()); handler.setSuffix(archiveSuffix); // Set append to true to ensure the rotated file is overwritten handler.setAppend(true); @@ -256,10 +253,10 @@ private void testArchiveRotate(final String archiveSuffix, final boolean rotateO handler.close(); // We should end up with 3 files, 2 rotated and the default log - final Path logDir = BASE_LOG_DIR.toPath(); + final Path logDir = logDirectory(); final Path path1 = logDir.resolve(FILENAME + ".1" + archiveSuffix); final Path path2 = logDir.resolve(FILENAME + ".2" + archiveSuffix); - Assertions.assertTrue(logFile.exists()); + Assertions.assertTrue(Files.exists(logFile)); Assertions.assertTrue(Files.exists(path1)); Assertions.assertTrue(Files.exists(path2)); @@ -268,16 +265,12 @@ private void testArchiveRotate(final String archiveSuffix, final boolean rotateO validateGzipContents(path1, "Test message:"); validateGzipContents(path2, "Test message:"); } else if (archiveSuffix.endsWith(".zip")) { - validateZipContents(path1, logFile.getName(), "Test message:"); - validateZipContents(path2, logFile.getName(), "Test message:"); + validateZipContents(path1, logFile.getFileName().toString(), "Test message:"); + validateZipContents(path2, logFile.getFileName().toString(), "Test message:"); } else { Assertions.fail("Unknown archive suffix: " + archiveSuffix); } - compareArchiveContents(path1, path2, logFile.getName()); - - // Clean up files - Files.deleteIfExists(path1); - Files.deleteIfExists(path2); + compareArchiveContents(path1, path2, logFile.getFileName().toString()); } }