diff options
Diffstat (limited to 'src/test')
41 files changed, 727 insertions, 309 deletions
diff --git a/src/test/java/org/apache/commons/io/CharsetsTest.java b/src/test/java/org/apache/commons/io/CharsetsTest.java index b68b90b6..7c988978 100644 --- a/src/test/java/org/apache/commons/io/CharsetsTest.java +++ b/src/test/java/org/apache/commons/io/CharsetsTest.java @@ -21,6 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.util.Set; import java.util.SortedMap; import org.junit.jupiter.api.Test; @@ -31,6 +32,20 @@ import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") // testing deprecated code public class CharsetsTest { + /** + * For parameterized tests. + */ + public static final String AVAIL_CHARSETS = "org.apache.commons.io.CharsetsTest#availableCharsetsKeySet"; + + /** + * For parameterized tests. + * + * @return {@code Charset.availableCharsets().keySet()}. + */ + public static Set<String> availableCharsetsKeySet() { + return Charset.availableCharsets().keySet(); + } + @Test public void testIso8859_1() { assertEquals("ISO-8859-1", Charsets.ISO_8859_1.name()); diff --git a/src/test/java/org/apache/commons/io/DemuxInputStreamTest.java b/src/test/java/org/apache/commons/io/DemuxInputStreamTest.java index 6872bc54..6b1a63b2 100644 --- a/src/test/java/org/apache/commons/io/DemuxInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/DemuxInputStreamTest.java @@ -37,7 +37,7 @@ import org.junit.jupiter.api.Test; */ public class DemuxInputStreamTest { - private static class ReaderThread extends Thread { + private static final class ReaderThread extends Thread { private final DemuxInputStream demuxInputStream; private final InputStream inputStream; private final StringBuffer stringBuffer = new StringBuffer(); @@ -62,7 +62,7 @@ public class DemuxInputStreamTest { // System.out.println( "Reading: " + (char)ch ); stringBuffer.append((char) ch); - final int sleepMillis = Math.abs(c_random.nextInt() % 10); + final int sleepMillis = Math.abs(RANDOM.nextInt() % 10); TestUtils.sleep(sleepMillis); ch = demuxInputStream.read(); } @@ -72,7 +72,7 @@ public class DemuxInputStreamTest { } } - private static class WriterThread extends Thread { + private static final class WriterThread extends Thread { private final byte[] byteArray; private final DemuxOutputStream demuxOutputStream; private final OutputStream outputStream; @@ -91,7 +91,7 @@ public class DemuxInputStreamTest { try { // System.out.println( "Writing: " + (char)byteArray[ i ] ); demuxOutputStream.write(element); - final int sleepMillis = Math.abs(c_random.nextInt() % 10); + final int sleepMillis = Math.abs(RANDOM.nextInt() % 10); TestUtils.sleep(sleepMillis); } catch (final Exception e) { e.printStackTrace(); @@ -100,7 +100,7 @@ public class DemuxInputStreamTest { } } - private static final Random c_random = new Random(); + private static final Random RANDOM = new Random(); private static final String DATA1 = "Data for thread1"; private static final String DATA2 = "Data for thread2"; diff --git a/src/test/java/org/apache/commons/io/DirectoryWalkerTest.java b/src/test/java/org/apache/commons/io/DirectoryWalkerTest.java index 5ac3aa9c..ccb5c110 100644 --- a/src/test/java/org/apache/commons/io/DirectoryWalkerTest.java +++ b/src/test/java/org/apache/commons/io/DirectoryWalkerTest.java @@ -90,7 +90,7 @@ public class DirectoryWalkerTest { * Test DirectoryWalker implementation that always returns false * from handleDirectoryStart() */ - private static class TestFalseFileFinder extends TestFileFinder { + private static final class TestFalseFileFinder extends TestFileFinder { protected TestFalseFileFinder(final FileFilter filter, final int depthLimit) { super(filter, depthLimit); @@ -143,7 +143,7 @@ public class DirectoryWalkerTest { * Test DirectoryWalker implementation that finds files in a directory hierarchy * applying a file filter. */ - private static class TestFileFinderString extends DirectoryWalker<String> { + private static final class TestFileFinderString extends DirectoryWalker<String> { protected TestFileFinderString(final FileFilter filter, final int depthLimit) { super(filter, depthLimit); @@ -234,12 +234,12 @@ public class DirectoryWalkerTest { private static final File outputDir = new File(ioDir, "output"); private static final File[] dirs = {orgDir, apacheDir, commonsDir, ioDir, outputDir}; // Files - private static final File filenameUtils = new File(ioDir, "FilenameUtils.java"); + private static final File fileNameUtils = new File(ioDir, "FilenameUtils.java"); private static final File ioUtils = new File(ioDir, "IOUtils.java"); private static final File proxyWriter = new File(outputDir, "ProxyWriter.java"); private static final File nullStream = new File(outputDir, "NullOutputStream.java"); - private static final File[] ioFiles = {filenameUtils, ioUtils}; + private static final File[] ioFiles = {fileNameUtils, ioUtils}; private static final File[] outputFiles = {proxyWriter, nullStream}; // Filters diff --git a/src/test/java/org/apache/commons/io/DirectoryWalkerTestCaseJava4.java b/src/test/java/org/apache/commons/io/DirectoryWalkerTestCaseJava4.java index f55699ad..ad7337dd 100644 --- a/src/test/java/org/apache/commons/io/DirectoryWalkerTestCaseJava4.java +++ b/src/test/java/org/apache/commons/io/DirectoryWalkerTestCaseJava4.java @@ -102,7 +102,7 @@ public class DirectoryWalkerTestCaseJava4 { * Test DirectoryWalker implementation that always returns false * from handleDirectoryStart() */ - private static class TestFalseFileFinder extends TestFileFinder { + private static final class TestFalseFileFinder extends TestFileFinder { protected TestFalseFileFinder(final FileFilter filter, final int depthLimit) { super(filter, depthLimit); @@ -237,12 +237,12 @@ public class DirectoryWalkerTestCaseJava4 { private static final File outputDir = new File(ioDir, "output"); private static final File[] dirs = {orgDir, apacheDir, commonsDir, ioDir, outputDir}; // Files - private static final File filenameUtils = new File(ioDir, "FilenameUtils.java"); + private static final File fileNameUtils = new File(ioDir, "FilenameUtils.java"); private static final File ioUtils = new File(ioDir, "IOUtils.java"); private static final File proxyWriter = new File(outputDir, "ProxyWriter.java"); private static final File nullStream = new File(outputDir, "NullOutputStream.java"); - private static final File[] ioFiles = {filenameUtils, ioUtils}; + private static final File[] ioFiles = {fileNameUtils, ioUtils}; private static final File[] outputFiles = {proxyWriter, nullStream}; // Filters private static final IOFileFilter dirsFilter = createNameFilter(dirs); diff --git a/src/test/java/org/apache/commons/io/EndianUtilsTest.java b/src/test/java/org/apache/commons/io/EndianUtilsTest.java index 79df0c66..4247644d 100644 --- a/src/test/java/org/apache/commons/io/EndianUtilsTest.java +++ b/src/test/java/org/apache/commons/io/EndianUtilsTest.java @@ -38,7 +38,7 @@ public class EndianUtilsTest { } @Test - public void testEOFException() throws IOException { + public void testEOFException() { final ByteArrayInputStream input = new ByteArrayInputStream(new byte[] {}); assertThrows(EOFException.class, () -> EndianUtils.readSwappedDouble(input)); } diff --git a/src/test/java/org/apache/commons/io/FileUtilsDirectoryContainsTest.java b/src/test/java/org/apache/commons/io/FileUtilsDirectoryContainsTest.java index bba9f098..3e92fef6 100644 --- a/src/test/java/org/apache/commons/io/FileUtilsDirectoryContainsTest.java +++ b/src/test/java/org/apache/commons/io/FileUtilsDirectoryContainsTest.java @@ -112,7 +112,7 @@ public class FileUtilsDirectoryContainsTest { } @Test - public void testDirectoryDoesNotExist() throws IOException { + public void testDirectoryDoesNotExist() { final File dir = new File("DOESNOTEXIST"); assertFalse(dir.exists()); assertThrows(IllegalArgumentException.class, () -> FileUtils.directoryContains(dir, file1)); @@ -158,12 +158,12 @@ public class FileUtilsDirectoryContainsTest { } @Test - public void testSameFile() throws IOException { + public void testSameFile() { assertThrows(IllegalArgumentException.class, () -> FileUtils.directoryContains(file1, file1)); } @Test - public void testUnrealizedContainment() throws IOException { + public void testUnrealizedContainment() { final File dir = new File("DOESNOTEXIST"); final File file = new File(dir, "DOESNOTEXIST2"); assertFalse(dir.exists()); diff --git a/src/test/java/org/apache/commons/io/FileUtilsListFilesTest.java b/src/test/java/org/apache/commons/io/FileUtilsListFilesTest.java index 27a81c98..e65bc8de 100644 --- a/src/test/java/org/apache/commons/io/FileUtilsListFilesTest.java +++ b/src/test/java/org/apache/commons/io/FileUtilsListFilesTest.java @@ -29,6 +29,7 @@ import java.util.stream.Collectors; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; +import org.apache.commons.lang3.function.Consumers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -45,8 +46,15 @@ public class FileUtilsListFilesTest { return files.stream().map(File::getName).collect(Collectors.toList()); } + /** + * Consumes and closes the underlying stream. + * + * @param files The iterator to consume. + * @return a new collection. + */ private Collection<String> filesToFilenames(final Iterator<File> files) { final Collection<String> fileNames = new ArrayList<>(); + // Iterator.forEachRemaining() closes the underlying stream. files.forEachRemaining(f -> fileNames.add(f.getName())); return fileNames; } @@ -88,68 +96,83 @@ public class FileUtilsListFilesTest { final String[] extensions = { "xml", "txt" }; Iterator<File> files = FileUtils.iterateFiles(temporaryFolder, extensions, false); - Collection<String> filenames = filesToFilenames(files); - assertEquals(1, filenames.size()); - assertTrue(filenames.contains("dummy-build.xml")); - assertFalse(filenames.contains("README")); - assertFalse(filenames.contains("dummy-file.txt")); - - files = FileUtils.iterateFiles(temporaryFolder, extensions, true); - filenames = filesToFilenames(files); - assertEquals(4, filenames.size()); - assertTrue(filenames.contains("dummy-file.txt")); - assertFalse(filenames.contains("dummy-index.html")); + try { + final Collection<String> fileNames = filesToFilenames(files); + assertEquals(1, fileNames.size()); + assertTrue(fileNames.contains("dummy-build.xml")); + assertFalse(fileNames.contains("README")); + assertFalse(fileNames.contains("dummy-file.txt")); + } finally { + // Backstop in case filesToFilenames() failure. + files.forEachRemaining(Consumers.nop()); + } + + try { + files = FileUtils.iterateFiles(temporaryFolder, extensions, true); + final Collection<String> fileNames = filesToFilenames(files); + assertEquals(4, fileNames.size()); + assertTrue(fileNames.contains("dummy-file.txt")); + assertFalse(fileNames.contains("dummy-index.html")); + } finally { + // Backstop in case filesToFilenames() failure. + files.forEachRemaining(Consumers.nop()); + } files = FileUtils.iterateFiles(temporaryFolder, null, false); - filenames = filesToFilenames(files); - assertEquals(2, filenames.size()); - assertTrue(filenames.contains("dummy-build.xml")); - assertTrue(filenames.contains("README")); - assertFalse(filenames.contains("dummy-file.txt")); + try { + final Collection<String> fileNames = filesToFilenames(files); + assertEquals(2, fileNames.size()); + assertTrue(fileNames.contains("dummy-build.xml")); + assertTrue(fileNames.contains("README")); + assertFalse(fileNames.contains("dummy-file.txt")); + } finally { + // Backstop in case filesToFilenames() failure. + files.forEachRemaining(Consumers.nop()); + } } @Test public void testListFiles() { Collection<File> files; - Collection<String> filenames; + Collection<String> fileNames; IOFileFilter fileFilter; IOFileFilter dirFilter; // First, find non-recursively fileFilter = FileFilterUtils.trueFileFilter(); files = FileUtils.listFiles(temporaryFolder, fileFilter, null); - filenames = filesToFilenames(files); - assertTrue(filenames.contains("dummy-build.xml"), "'dummy-build.xml' is missing"); - assertFalse(filenames.contains("dummy-index.html"), "'dummy-index.html' shouldn't be found"); - assertFalse(filenames.contains("Entries"), "'Entries' shouldn't be found"); + fileNames = filesToFilenames(files); + assertTrue(fileNames.contains("dummy-build.xml"), "'dummy-build.xml' is missing"); + assertFalse(fileNames.contains("dummy-index.html"), "'dummy-index.html' shouldn't be found"); + assertFalse(fileNames.contains("Entries"), "'Entries' shouldn't be found"); // Second, find recursively fileFilter = FileFilterUtils.trueFileFilter(); dirFilter = FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter("CVS")); files = FileUtils.listFiles(temporaryFolder, fileFilter, dirFilter); - filenames = filesToFilenames(files); - assertTrue(filenames.contains("dummy-build.xml"), "'dummy-build.xml' is missing"); - assertTrue(filenames.contains("dummy-index.html"), "'dummy-index.html' is missing"); - assertFalse(filenames.contains("Entries"), "'Entries' shouldn't be found"); + fileNames = filesToFilenames(files); + assertTrue(fileNames.contains("dummy-build.xml"), "'dummy-build.xml' is missing"); + assertTrue(fileNames.contains("dummy-index.html"), "'dummy-index.html' is missing"); + assertFalse(fileNames.contains("Entries"), "'Entries' shouldn't be found"); // Do the same as above but now with the filter coming from FileFilterUtils fileFilter = FileFilterUtils.trueFileFilter(); dirFilter = FileFilterUtils.makeCVSAware(null); files = FileUtils.listFiles(temporaryFolder, fileFilter, dirFilter); - filenames = filesToFilenames(files); - assertTrue(filenames.contains("dummy-build.xml"), "'dummy-build.xml' is missing"); - assertTrue(filenames.contains("dummy-index.html"), "'dummy-index.html' is missing"); - assertFalse(filenames.contains("Entries"), "'Entries' shouldn't be found"); + fileNames = filesToFilenames(files); + assertTrue(fileNames.contains("dummy-build.xml"), "'dummy-build.xml' is missing"); + assertTrue(fileNames.contains("dummy-index.html"), "'dummy-index.html' is missing"); + assertFalse(fileNames.contains("Entries"), "'Entries' shouldn't be found"); // Again with the CVS filter but now with a non-null parameter fileFilter = FileFilterUtils.trueFileFilter(); dirFilter = FileFilterUtils.prefixFileFilter("sub"); dirFilter = FileFilterUtils.makeCVSAware(dirFilter); files = FileUtils.listFiles(temporaryFolder, fileFilter, dirFilter); - filenames = filesToFilenames(files); - assertTrue(filenames.contains("dummy-build.xml"), "'dummy-build.xml' is missing"); - assertTrue(filenames.contains("dummy-index.html"), "'dummy-index.html' is missing"); - assertFalse(filenames.contains("Entries"), "'Entries' shouldn't be found"); + fileNames = filesToFilenames(files); + assertTrue(fileNames.contains("dummy-build.xml"), "'dummy-build.xml' is missing"); + assertTrue(fileNames.contains("dummy-index.html"), "'dummy-index.html' is missing"); + assertFalse(fileNames.contains("Entries"), "'Entries' shouldn't be found"); assertThrows(NullPointerException.class, () -> FileUtils.listFiles(temporaryFolder, null, null)); } @@ -160,23 +183,23 @@ public class FileUtilsListFilesTest { Collection<File> files = FileUtils.listFiles(temporaryFolder, extensions, false); assertEquals(1, files.size()); - Collection<String> filenames = filesToFilenames(files); - assertTrue(filenames.contains("dummy-build.xml")); - assertFalse(filenames.contains("README")); - assertFalse(filenames.contains("dummy-file.txt")); + Collection<String> fileNames = filesToFilenames(files); + assertTrue(fileNames.contains("dummy-build.xml")); + assertFalse(fileNames.contains("README")); + assertFalse(fileNames.contains("dummy-file.txt")); files = FileUtils.listFiles(temporaryFolder, extensions, true); - filenames = filesToFilenames(files); - assertEquals(4, filenames.size()); - assertTrue(filenames.contains("dummy-file.txt")); - assertFalse(filenames.contains("dummy-index.html")); + fileNames = filesToFilenames(files); + assertEquals(4, fileNames.size()); + assertTrue(fileNames.contains("dummy-file.txt")); + assertFalse(fileNames.contains("dummy-index.html")); files = FileUtils.listFiles(temporaryFolder, null, false); assertEquals(2, files.size()); - filenames = filesToFilenames(files); - assertTrue(filenames.contains("dummy-build.xml")); - assertTrue(filenames.contains("README")); - assertFalse(filenames.contains("dummy-file.txt")); + fileNames = filesToFilenames(files); + assertTrue(fileNames.contains("dummy-build.xml")); + assertTrue(fileNames.contains("README")); + assertFalse(fileNames.contains("dummy-file.txt")); } diff --git a/src/test/java/org/apache/commons/io/FileUtilsTest.java b/src/test/java/org/apache/commons/io/FileUtilsTest.java index 4d976c4e..2c820c8d 100644 --- a/src/test/java/org/apache/commons/io/FileUtilsTest.java +++ b/src/test/java/org/apache/commons/io/FileUtilsTest.java @@ -40,6 +40,7 @@ import java.math.BigInteger; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -47,6 +48,7 @@ import java.nio.file.StandardCopyOption; import java.nio.file.attribute.AclFileAttributeView; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; @@ -86,6 +88,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIf; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -123,20 +126,6 @@ public class FileUtilsTest extends AbstractTempDirTest { } } - // Test helper class to pretend a file is shorter than it is - private static class ShorterFile extends File { - private static final long serialVersionUID = 1L; - - public ShorterFile(final String pathname) { - super(pathname); - } - - @Override - public long length() { - return super.length() - 1; - } - } - private static final String UTF_8 = StandardCharsets.UTF_8.name(); /** Test data. */ @@ -168,11 +157,6 @@ public class FileUtilsTest extends AbstractTempDirTest { */ private static final ListDirectoryWalker LIST_WALKER = new ListDirectoryWalker(); - /** - * Delay in milliseconds to make sure test for "last modified date" are accurate - */ - //private static final int LAST_MODIFIED_DELAY = 600; - private File testFile1; private File testFile2; @@ -1452,7 +1436,7 @@ public class FileUtilsTest extends AbstractTempDirTest { public void testFileUtils() throws Exception { // Loads file from classpath final File file1 = new File(tempDirFile, "test.txt"); - final String filename = file1.getAbsolutePath(); + final String fileName = file1.getAbsolutePath(); //Create test file on-the-fly (used to be in CVS) try (OutputStream out = Files.newOutputStream(file1.toPath())) { @@ -1461,16 +1445,16 @@ public class FileUtilsTest extends AbstractTempDirTest { final File file2 = new File(tempDirFile, "test2.txt"); - FileUtils.writeStringToFile(file2, filename, UTF_8); + FileUtils.writeStringToFile(file2, fileName, UTF_8); assertTrue(file2.exists()); assertTrue(file2.length() > 0); final String file2contents = FileUtils.readFileToString(file2, UTF_8); - assertEquals(filename, file2contents, "Second file's contents correct"); + assertEquals(fileName, file2contents, "Second file's contents correct"); assertTrue(file2.delete()); - final String contents = FileUtils.readFileToString(new File(filename), UTF_8); + final String contents = FileUtils.readFileToString(new File(fileName), UTF_8); assertEquals("This is a test", contents, "FileUtils.fileRead()"); } @@ -1645,8 +1629,8 @@ public class FileUtilsTest extends AbstractTempDirTest { @Test public void testIO575() throws IOException { final Path sourceDir = Files.createTempDirectory("source-dir"); - final String filename = "some-file"; - final Path sourceFile = Files.createFile(sourceDir.resolve(filename)); + final String fileName = "some-file"; + final Path sourceFile = Files.createFile(sourceDir.resolve(fileName)); assertEquals(SystemUtils.IS_OS_WINDOWS, sourceFile.toFile().canExecute()); @@ -1658,7 +1642,7 @@ public class FileUtilsTest extends AbstractTempDirTest { FileUtils.copyDirectory(sourceDir.toFile(), destDir.toFile()); - final Path destFile = destDir.resolve(filename); + final Path destFile = destDir.resolve(fileName); assertTrue(destFile.toFile().exists()); assertTrue(destFile.toFile().canExecute()); @@ -2445,6 +2429,41 @@ public class FileUtilsTest extends AbstractTempDirTest { } @Test + public void testReadFileToByteArray_Errors() { + assertThrows(NullPointerException.class, () -> FileUtils.readFileToByteArray(null)); + assertThrows(IOException.class, () -> FileUtils.readFileToByteArray(new File("non-exsistent"))); + assertThrows(IOException.class, () -> FileUtils.readFileToByteArray(tempDirFile)); + } + + @Test + @EnabledIf("isPosixFilePermissionsSupported") + public void testReadFileToByteArray_IOExceptionOnPosixFileSystem() throws Exception { + final File file = TestUtils.newFile(tempDirFile, "cant-read.txt"); + TestUtils.createFile(file, 100); + Files.setPosixFilePermissions(file.toPath(), PosixFilePermissions.fromString("---------")); + + assertThrows(IOException.class, () -> FileUtils.readFileToByteArray(file)); + } + + @Test + public void testReadFileToString_Errors() { + assertThrows(NullPointerException.class, () -> FileUtils.readFileToString(null)); + assertThrows(IOException.class, () -> FileUtils.readFileToString(new File("non-exsistent"))); + assertThrows(IOException.class, () -> FileUtils.readFileToString(tempDirFile)); + assertThrows(UnsupportedCharsetException.class, () -> FileUtils.readFileToString(tempDirFile, "unsupported-charset")); + } + + @Test + @EnabledIf("isPosixFilePermissionsSupported") + public void testReadFileToString_IOExceptionOnPosixFileSystem() throws Exception { + final File file = TestUtils.newFile(tempDirFile, "cant-read.txt"); + TestUtils.createFile(file, 100); + Files.setPosixFilePermissions(file.toPath(), PosixFilePermissions.fromString("---------")); + + assertThrows(IOException.class, () -> FileUtils.readFileToString(file)); + } + + @Test public void testReadFileToStringWithDefaultEncoding() throws Exception { final File file = new File(tempDirFile, "read.obj"); final String fixture = "Hello /u1234"; @@ -2478,6 +2497,24 @@ public class FileUtilsTest extends AbstractTempDirTest { } @Test + public void testReadLines_Errors() { + assertThrows(NullPointerException.class, () -> FileUtils.readLines(null)); + assertThrows(IOException.class, () -> FileUtils.readLines(new File("non-exsistent"))); + assertThrows(IOException.class, () -> FileUtils.readLines(tempDirFile)); + assertThrows(UnsupportedCharsetException.class, () -> FileUtils.readLines(tempDirFile, "unsupported-charset")); + } + + @Test + @EnabledIf("isPosixFilePermissionsSupported") + public void testReadLines_IOExceptionOnPosixFileSystem() throws Exception { + final File file = TestUtils.newFile(tempDirFile, "cant-read.txt"); + TestUtils.createFile(file, 100); + Files.setPosixFilePermissions(file.toPath(), PosixFilePermissions.fromString("---------")); + + assertThrows(IOException.class, () -> FileUtils.readLines(file)); + } + + @Test public void testSizeOf() throws Exception { final File file = new File(tempDirFile, getName()); diff --git a/src/test/java/org/apache/commons/io/IOUtilsMultithreadedSkipTest.java b/src/test/java/org/apache/commons/io/IOUtilsMultithreadedSkipTest.java index 9db0d67b..a492d397 100644 --- a/src/test/java/org/apache/commons/io/IOUtilsMultithreadedSkipTest.java +++ b/src/test/java/org/apache/commons/io/IOUtilsMultithreadedSkipTest.java @@ -87,7 +87,7 @@ public class IOUtilsMultithreadedSkipTest { try (final InputStream inputStream = getClass().getResourceAsStream(FIXTURE)) { bytes = IOUtils.toByteArray(inputStream); } - final int numSkips = (random.nextInt(bytes.length) / 100) + 1; + final int numSkips = random.nextInt(bytes.length) / 100 + 1; final int[] skips = generateSkips(bytes, numSkips, random); final int[] expected; diff --git a/src/test/java/org/apache/commons/io/IOUtilsTest.java b/src/test/java/org/apache/commons/io/IOUtilsTest.java index e361e885..c921abc1 100644 --- a/src/test/java/org/apache/commons/io/IOUtilsTest.java +++ b/src/test/java/org/apache/commons/io/IOUtilsTest.java @@ -1257,7 +1257,7 @@ public class IOUtilsTest { assertThrows(NullPointerException.class, () -> IOUtils.resourceToURL(null, ClassLoader.getSystemClassLoader())); } - public void testSingleEOL(final String s1, final String s2, final boolean ifEquals) throws IOException { + public void testSingleEOL(final String s1, final String s2, final boolean ifEquals) { assertEquals(ifEquals, IOUtils.contentEqualsIgnoreEOL( new CharArrayReader(s1.toCharArray()), new CharArrayReader(s2.toCharArray()) @@ -1750,6 +1750,15 @@ public class IOUtilsTest { } @Test + public void testWriteLines() throws IOException { + final String[] data = {"The", "quick"}; + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + IOUtils.writeLines(Arrays.asList(data), "\n", out, "UTF-16"); + final String result = new String(out.toByteArray(), StandardCharsets.UTF_16); + assertEquals("The\nquick\n", result); + } + + @Test public void testWriteLittleString() throws IOException { final String data = "\uD83D"; // White-box test to check that not closing the internal channel is not a problem. diff --git a/src/test/java/org/apache/commons/io/RandomAccessFilesTest.java b/src/test/java/org/apache/commons/io/RandomAccessFilesTest.java index d3873599..ce7fa8fd 100644 --- a/src/test/java/org/apache/commons/io/RandomAccessFilesTest.java +++ b/src/test/java/org/apache/commons/io/RandomAccessFilesTest.java @@ -19,10 +19,15 @@ package org.apache.commons.io; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.RandomAccessFile; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; import org.junit.jupiter.api.Test; @@ -31,32 +36,101 @@ import org.junit.jupiter.api.Test; */ public class RandomAccessFilesTest { - protected static final String FILE_RES_RO = "/org/apache/commons/io/test-file-20byteslength.bin"; - protected static final String FILE_NAME_RO = "src/test/resources" + FILE_RES_RO; + private static final String FILE_NAME_RO_20 = "src/test/resources/org/apache/commons/io/test-file-20byteslength.bin"; + private static final String FILE_NAME_RO_0 = "src/test/resources/org/apache/commons/io/test-file-empty.bin"; + private static final String FILE_NAME_RO_0_BIS = "src/test/resources/org/apache/commons/io/test-file-empty2.bin"; + + @Test + public void testContentEquals() throws IOException { + try (RandomAccessFile raf1 = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20)) { + assertEquals(raf1, raf1); + assertTrue(RandomAccessFiles.contentEquals(raf1, raf1)); + } + // as above, to make sure resources are OK + try (RandomAccessFile raf1 = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20)) { + assertEquals(raf1, raf1); + assertTrue(RandomAccessFiles.contentEquals(raf1, raf1)); + } + // same 20 bytes + try (RandomAccessFile raf1 = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20); + RandomAccessFile raf2 = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20)) { + assertTrue(RandomAccessFiles.contentEquals(raf1, raf2)); + } + // same empty file + try (RandomAccessFile raf1 = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_0); + RandomAccessFile raf2 = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_0)) { + assertTrue(RandomAccessFiles.contentEquals(raf1, raf2)); + assertTrue(RandomAccessFiles.contentEquals(RandomAccessFiles.reset(raf2), RandomAccessFiles.reset(raf1))); + } + // diff empty file + try (RandomAccessFile raf1 = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_0); + RandomAccessFile raf2 = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_0_BIS)) { + assertTrue(RandomAccessFiles.contentEquals(raf1, raf2)); + assertTrue(RandomAccessFiles.contentEquals(RandomAccessFiles.reset(raf2), RandomAccessFiles.reset(raf1))); + } + try (RandomAccessFile raf1 = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_0); + RandomAccessFile raf2 = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20)) { + assertFalse(RandomAccessFiles.contentEquals(raf1, raf2)); + assertFalse(RandomAccessFiles.contentEquals(RandomAccessFiles.reset(raf2), RandomAccessFiles.reset(raf1))); + } + // + final Path bigFile1 = Files.createTempFile(getClass().getSimpleName(), "-1.bin"); + final Path bigFile2 = Files.createTempFile(getClass().getSimpleName(), "-2.bin"); + final Path bigFile3 = Files.createTempFile(getClass().getSimpleName(), "-3.bin"); + try { + final int newLength = 1_000_000; + final byte[] bytes1 = new byte[newLength]; + final byte[] bytes2 = new byte[newLength]; + Arrays.fill(bytes1, (byte) 1); + Arrays.fill(bytes2, (byte) 2); + Files.write(bigFile1, bytes1); + Files.write(bigFile2, bytes2); + try (RandomAccessFile raf1 = RandomAccessFileMode.READ_ONLY.create(bigFile1); + RandomAccessFile raf2 = RandomAccessFileMode.READ_ONLY.create(bigFile2)) { + assertFalse(RandomAccessFiles.contentEquals(raf1, raf2)); + assertFalse(RandomAccessFiles.contentEquals(RandomAccessFiles.reset(raf2), RandomAccessFiles.reset(raf1))); + assertTrue(RandomAccessFiles.contentEquals(RandomAccessFiles.reset(raf1), RandomAccessFiles.reset(raf1))); + } + // Make the last byte different + final byte[] bytes3 = bytes1.clone(); + bytes3[bytes3.length - 1] = 9; + Files.write(bigFile3, bytes3); + try (RandomAccessFile raf1 = RandomAccessFileMode.READ_ONLY.create(bigFile1); + RandomAccessFile raf3 = RandomAccessFileMode.READ_ONLY.create(bigFile3)) { + assertFalse(RandomAccessFiles.contentEquals(raf1, raf3)); + assertFalse(RandomAccessFiles.contentEquals(RandomAccessFiles.reset(raf3), RandomAccessFiles.reset(raf1))); + } + } finally { + // Delete ASAP + Files.deleteIfExists(bigFile1); + Files.deleteIfExists(bigFile2); + Files.deleteIfExists(bigFile3); + } + } @Test public void testRead() throws IOException { - try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO)) { + try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20)) { final byte[] buffer = RandomAccessFiles.read(raf, 0, 0); assertArrayEquals(new byte[] {}, buffer); } - try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO)) { + try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20)) { final byte[] buffer = RandomAccessFiles.read(raf, 1, 0); assertArrayEquals(new byte[] {}, buffer); } - try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO)) { + try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20)) { final byte[] buffer = RandomAccessFiles.read(raf, 0, 1); assertArrayEquals(new byte[] { '1' }, buffer); } - try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO)) { + try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20)) { final byte[] buffer = RandomAccessFiles.read(raf, 1, 1); assertArrayEquals(new byte[] { '2' }, buffer); } - try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO)) { + try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20)) { final byte[] buffer = RandomAccessFiles.read(raf, 0, 20); assertEquals(20, buffer.length); } - try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO)) { + try (final RandomAccessFile raf = RandomAccessFileMode.READ_ONLY.create(FILE_NAME_RO_20)) { assertThrows(IOException.class, () -> RandomAccessFiles.read(raf, 0, 21)); } } diff --git a/src/test/java/org/apache/commons/io/StreamIteratorTest.java b/src/test/java/org/apache/commons/io/StreamIteratorTest.java new file mode 100644 index 00000000..7cfa9afb --- /dev/null +++ b/src/test/java/org/apache/commons/io/StreamIteratorTest.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.io; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Iterator; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; + +/** + * Tests {@link StreamIterator}. + */ +public class StreamIteratorTest { + + @Test + public void testForEachRemaining() { + final AtomicBoolean closed = new AtomicBoolean(); + final Iterator<Integer> iter = StreamIterator.iterator(Stream.of(1, 2, 3).onClose(() -> closed.set(true))); + final AtomicInteger sum = new AtomicInteger(); + + iter.forEachRemaining(sum::addAndGet); + + assertEquals(6, sum.get()); + assertTrue(closed.get()); + } + + @Test + public void testHasNext() { + final AtomicBoolean closed = new AtomicBoolean(); + final Iterator<Integer> iter = StreamIterator.iterator(Stream.of(1, 2, 3).onClose(() -> closed.set(true))); + int sum = 0; + + while (iter.hasNext()) { + sum += iter.next(); + } + + assertEquals(6, sum); + assertTrue(closed.get()); + } +} diff --git a/src/test/java/org/apache/commons/io/file/AbstractTempDirTest.java b/src/test/java/org/apache/commons/io/file/AbstractTempDirTest.java index a5ed616f..16bd66cc 100644 --- a/src/test/java/org/apache/commons/io/file/AbstractTempDirTest.java +++ b/src/test/java/org/apache/commons/io/file/AbstractTempDirTest.java @@ -19,6 +19,7 @@ package org.apache.commons.io.file; import java.io.File; import java.io.IOException; +import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; @@ -52,4 +53,8 @@ public abstract class AbstractTempDirTest { tempDirFile = tempDirPath.toFile(); } + + protected final boolean isPosixFilePermissionsSupported() { + return FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); + } } diff --git a/src/test/java/org/apache/commons/io/file/FilesUncheckTest.java b/src/test/java/org/apache/commons/io/file/FilesUncheckTest.java index 4fa73681..80f4d37b 100644 --- a/src/test/java/org/apache/commons/io/file/FilesUncheckTest.java +++ b/src/test/java/org/apache/commons/io/file/FilesUncheckTest.java @@ -50,6 +50,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; +import java.util.stream.Stream; import org.apache.commons.io.IOUtils; import org.apache.commons.io.function.Uncheck; @@ -166,7 +167,9 @@ public class FilesUncheckTest { @Test public void testFind() { - assertNotNull(FilesUncheck.find(FILE_PATH_EMPTY, 0, (t, u) -> false)); + try (Stream<Path> find = FilesUncheck.find(FILE_PATH_EMPTY, 0, (t, u) -> false)) { + assertNotNull(find); + } } @Test @@ -207,17 +210,23 @@ public class FilesUncheckTest { @Test public void testLinesPath() { - assertEquals(0, FilesUncheck.lines(FILE_PATH_EMPTY).count()); + try (Stream<String> stream = FilesUncheck.lines(FILE_PATH_EMPTY)) { + assertEquals(0, stream.count()); + } } @Test public void testLinesPathCharset() { - assertEquals(0, FilesUncheck.lines(FILE_PATH_EMPTY, StandardCharsets.UTF_8).count()); + try (Stream<String> stream = FilesUncheck.lines(FILE_PATH_EMPTY, StandardCharsets.UTF_8)) { + assertEquals(0, stream.count()); + } } @Test public void testList() { - assertEquals(1, FilesUncheck.list(Paths.get("src/test/resources/org/apache/commons/io/dirs-1-file-size-0")).count()); + try (Stream<Path> stream = FilesUncheck.list(Paths.get("src/test/resources/org/apache/commons/io/dirs-1-file-size-0"))) { + assertEquals(1, stream.count()); + } } @Test @@ -426,12 +435,16 @@ public class FilesUncheckTest { @Test public void testWalkPathFileVisitOptionArray() { - assertTrue(0 < FilesUncheck.walk(TARGET_PATH, FileVisitOption.FOLLOW_LINKS).count()); + try (Stream<Path> stream = FilesUncheck.walk(TARGET_PATH, FileVisitOption.FOLLOW_LINKS)) { + assertTrue(0 < stream.count()); + } } @Test public void testWalkPathIntFileVisitOptionArray() { - assertEquals(1, FilesUncheck.walk(TARGET_PATH, 0, FileVisitOption.FOLLOW_LINKS).count()); + try (Stream<Path> stream = FilesUncheck.walk(TARGET_PATH, 0, FileVisitOption.FOLLOW_LINKS)) { + assertEquals(1, stream.count()); + } } @Test diff --git a/src/test/java/org/apache/commons/io/filefilter/AbstractConditionalFileFilterTest.java b/src/test/java/org/apache/commons/io/filefilter/AbstractConditionalFileFilterTest.java index 5a99d620..a663e5f6 100644 --- a/src/test/java/org/apache/commons/io/filefilter/AbstractConditionalFileFilterTest.java +++ b/src/test/java/org/apache/commons/io/filefilter/AbstractConditionalFileFilterTest.java @@ -104,7 +104,7 @@ public abstract class AbstractConditionalFileFilterTest extends AbstractIOFileFi final boolean[] trueResults = testTrueResults.get(i); final boolean[] falseResults = testFalseResults.get(i); final boolean fileResults = testFileResults.get(i); - final boolean filenameResults = testFilenameResults.get(i); + final boolean fileNameResults = testFilenameResults.get(i); // Test conditional AND filter created by passing filters to the constructor final IOFileFilter filter = this.buildFilterUsingAdd(filters); @@ -116,10 +116,10 @@ public abstract class AbstractConditionalFileFilterTest extends AbstractIOFileFi assertTrueFiltersInvoked(i, trueFilters, trueResults); assertFalseFiltersInvoked(i, falseFilters, falseResults); - // Test as a filename filter + // Test as a file name filter resetTrueFilters(this.trueFilters); resetFalseFilters(this.falseFilters); - assertFilenameFiltering(i, filter, this.file, filenameResults); + assertFilenameFiltering(i, filter, this.file, fileNameResults); assertTrueFiltersInvoked(i, trueFilters, trueResults); assertFalseFiltersInvoked(i, falseFilters, falseResults); } @@ -138,7 +138,7 @@ public abstract class AbstractConditionalFileFilterTest extends AbstractIOFileFi final boolean[] trueResults = testTrueResults.get(i); final boolean[] falseResults = testFalseResults.get(i); final boolean fileResults = testFileResults.get(i); - final boolean filenameResults = testFilenameResults.get(i); + final boolean fileNameResults = testFilenameResults.get(i); // Test conditional AND filter created by passing filters to the constructor final IOFileFilter filter = this.buildFilterUsingConstructor(filters); @@ -150,10 +150,10 @@ public abstract class AbstractConditionalFileFilterTest extends AbstractIOFileFi assertTrueFiltersInvoked(i, trueFilters, trueResults); assertFalseFiltersInvoked(i, falseFilters, falseResults); - // Test as a filename filter + // Test as a file name filter resetTrueFilters(this.trueFilters); resetFalseFilters(this.falseFilters); - assertFilenameFiltering(i, filter, this.file, filenameResults); + assertFilenameFiltering(i, filter, this.file, fileNameResults); assertTrueFiltersInvoked(i, trueFilters, trueResults); assertFalseFiltersInvoked(i, falseFilters, falseResults); } diff --git a/src/test/java/org/apache/commons/io/function/IOBaseStreamTest.java b/src/test/java/org/apache/commons/io/function/IOBaseStreamTest.java index 1c05418c..a0bd3e47 100644 --- a/src/test/java/org/apache/commons/io/function/IOBaseStreamTest.java +++ b/src/test/java/org/apache/commons/io/function/IOBaseStreamTest.java @@ -67,7 +67,7 @@ public class IOBaseStreamTest { /** * Implements IOBaseStream with a concrete type. */ - private static class IOBaseStreamPathFixture<B extends BaseStream<Path, B>> extends IOBaseStreamFixture<Path, IOBaseStreamPathFixture<B>, B> { + private static final class IOBaseStreamPathFixture<B extends BaseStream<Path, B>> extends IOBaseStreamFixture<Path, IOBaseStreamPathFixture<B>, B> { private IOBaseStreamPathFixture(final B baseStream) { super(baseStream); @@ -80,7 +80,7 @@ public class IOBaseStreamTest { } - private static class MyRuntimeException extends RuntimeException { + private static final class MyRuntimeException extends RuntimeException { private static final long serialVersionUID = 1L; diff --git a/src/test/java/org/apache/commons/io/function/IOBinaryOperatorStreamTest.java b/src/test/java/org/apache/commons/io/function/IOBinaryOperatorStreamTest.java index a591e780..501d75f8 100644 --- a/src/test/java/org/apache/commons/io/function/IOBinaryOperatorStreamTest.java +++ b/src/test/java/org/apache/commons/io/function/IOBinaryOperatorStreamTest.java @@ -88,14 +88,19 @@ public class IOBinaryOperatorStreamTest { public void testReduce() throws IOException { // A silly example to pass in a IOBinaryOperator. final Path current = PathUtils.current(); - final Path expected = Files.list(current).reduce((t, u) -> { - try { - return t.toRealPath(); - } catch (final IOException e) { - return fail(e); - } - }).get(); - assertEquals(expected, Files.list(current).reduce(REAL_PATH_BO).get()); + final Path expected; + try (Stream<Path> stream = Files.list(current)) { + expected = stream.reduce((t, u) -> { + try { + return t.toRealPath(); + } catch (final IOException e) { + return fail(e); + } + }).get(); + } + try (Stream<Path> stream = Files.list(current)) { + assertEquals(expected, stream.reduce(REAL_PATH_BO).get()); + } } } diff --git a/src/test/java/org/apache/commons/io/function/IOConsumerTest.java b/src/test/java/org/apache/commons/io/function/IOConsumerTest.java index 5bfeb401..1871be48 100644 --- a/src/test/java/org/apache/commons/io/function/IOConsumerTest.java +++ b/src/test/java/org/apache/commons/io/function/IOConsumerTest.java @@ -76,11 +76,11 @@ public class IOConsumerTest { public void testForAllArrayOf1() throws IOException { IOConsumer.forAll(TestUtils.throwingIOConsumer(), (String[]) null); IOConsumer.forAll(null, (String[]) null); - assertThrows(IOExceptionList.class, () -> IOConsumer.forAll(TestUtils.throwingIOConsumer(), new String[] {"1"})); + assertThrows(IOExceptionList.class, () -> IOConsumer.forAll(TestUtils.throwingIOConsumer(), "1")); // final AtomicReference<String> ref = new AtomicReference<>("0"); final IOConsumer<String> consumer1 = s -> ref.set(ref.get() + s); - IOConsumer.forAll(consumer1, new String[] {"1"}); + IOConsumer.forAll(consumer1, "1"); assertEquals("01", ref.get()); } @@ -88,11 +88,11 @@ public class IOConsumerTest { public void testForAllArrayOf2() throws IOException { IOConsumer.forAll(TestUtils.throwingIOConsumer(), (String[]) null); IOConsumer.forAll(null, (String[]) null); - assertThrows(IOExceptionList.class, () -> IOConsumer.forAll(TestUtils.throwingIOConsumer(), new String[] {"1", "2"})); + assertThrows(IOExceptionList.class, () -> IOConsumer.forAll(TestUtils.throwingIOConsumer(), "1", "2")); // final AtomicReference<String> ref = new AtomicReference<>("0"); final IOConsumer<String> consumer1 = s -> ref.set(ref.get() + s); - IOConsumer.forAll(consumer1, new String[] {"1", "2"}); + IOConsumer.forAll(consumer1, "1", "2"); assertEquals("012", ref.get()); } diff --git a/src/test/java/org/apache/commons/io/function/IOFunctionTest.java b/src/test/java/org/apache/commons/io/function/IOFunctionTest.java index 1032aeee..af859aba 100644 --- a/src/test/java/org/apache/commons/io/function/IOFunctionTest.java +++ b/src/test/java/org/apache/commons/io/function/IOFunctionTest.java @@ -38,7 +38,7 @@ import org.junit.jupiter.api.Test; */ public class IOFunctionTest { - private static class Holder<T> { + private static final class Holder<T> { T value; } @@ -168,7 +168,7 @@ public class IOFunctionTest { public void testIdentity() throws IOException { assertEquals(IOFunction.identity(), IOFunction.identity()); final IOFunction<byte[], byte[]> identityFunction = IOFunction.identity(); - final byte[] buf = new byte[] {(byte) 0xa, (byte) 0xb, (byte) 0xc}; + final byte[] buf = {(byte) 0xa, (byte) 0xb, (byte) 0xc}; assertEquals(buf, identityFunction.apply(buf)); assertArrayEquals(buf, identityFunction.apply(buf)); } diff --git a/src/test/java/org/apache/commons/io/function/IOLongSupplierTest.java b/src/test/java/org/apache/commons/io/function/IOLongSupplierTest.java index 07748ded..dce0a426 100644 --- a/src/test/java/org/apache/commons/io/function/IOLongSupplierTest.java +++ b/src/test/java/org/apache/commons/io/function/IOLongSupplierTest.java @@ -49,7 +49,7 @@ public class IOLongSupplierTest { } @Test - public void testAsSupplier() throws IOException { + public void testAsSupplier() { assertThrows(UncheckedIOException.class, () -> TestConstants.THROWING_IO_LONG_SUPPLIER.asSupplier().getAsLong()); assertEquals(1L, getThrowsNone(() -> TestUtils.compareAndSetThrowsIO(atomicLong, 1L))); assertEquals(1L, atomicLong.get()); diff --git a/src/test/java/org/apache/commons/io/function/IOStreamTest.java b/src/test/java/org/apache/commons/io/function/IOStreamTest.java index 198a361c..3e2ef9c5 100644 --- a/src/test/java/org/apache/commons/io/function/IOStreamTest.java +++ b/src/test/java/org/apache/commons/io/function/IOStreamTest.java @@ -402,7 +402,7 @@ public class IOStreamTest { @SuppressWarnings("resource") // custom stream not recognized by compiler warning machinery @Test - public void testOnCloseMultipleHandlers() throws IOException { + public void testOnCloseMultipleHandlers() { // final AtomicReference<String> ref = new AtomicReference<>(); // Sanity check @@ -511,13 +511,14 @@ public class IOStreamTest { assertEquals(1, IOStream.of("C", "D").skip(1).peek(e -> compareAndSetRE(ref, null, e)).count()); assertEquals(1, IOStream.of("C", "D").skip(1).peek(e -> compareAndSetIO(ref, null, e)).count()); assertNull(ref.get()); - } else if (AT_LEAST_JAVA_11) { - assertThrows(RuntimeException.class, () -> IOStream.of("C", "D").skip(1).peek(e -> compareAndSetRE(ref, null, e)).count()); - assertThrows(IOException.class, () -> IOStream.of("C", "D").skip(1).peek(e -> compareAndSetIO(ref, null, e)).count()); - assertEquals("B", ref.get()); } else { - assertThrows(RuntimeException.class, () -> IOStream.of("C", "D").skip(1).peek(e -> compareAndSetRE(ref, null, e)).count()); - assertThrows(IOException.class, () -> IOStream.of("C", "D").skip(1).peek(e -> compareAndSetIO(ref, null, e)).count()); + if (AT_LEAST_JAVA_11) { + assertThrows(RuntimeException.class, () -> IOStream.of("C", "D").skip(1).peek(e -> compareAndSetRE(ref, null, e)).count()); + assertThrows(IOException.class, () -> IOStream.of("C", "D").skip(1).peek(e -> compareAndSetIO(ref, null, e)).count()); + } else { + assertThrows(RuntimeException.class, () -> IOStream.of("C", "D").skip(1).peek(e -> compareAndSetRE(ref, null, e)).count()); + assertThrows(IOException.class, () -> IOStream.of("C", "D").skip(1).peek(e -> compareAndSetIO(ref, null, e)).count()); + } assertEquals("B", ref.get()); } } diff --git a/src/test/java/org/apache/commons/io/function/TestConstants.java b/src/test/java/org/apache/commons/io/function/TestConstants.java index bafe7ef0..dfea176a 100644 --- a/src/test/java/org/apache/commons/io/function/TestConstants.java +++ b/src/test/java/org/apache/commons/io/function/TestConstants.java @@ -44,17 +44,17 @@ class TestConstants { static IOFunction<Object, Object> THROWING_IO_FUNCTION = t -> throwIOException(); - static IOIntSupplier THROWING_IO_INT_SUPPLIER = () -> throwIOException(); + static IOIntSupplier THROWING_IO_INT_SUPPLIER = TestConstants::throwIOException; - static IOLongSupplier THROWING_IO_LONG_SUPPLIER = () -> throwIOException(); + static IOLongSupplier THROWING_IO_LONG_SUPPLIER = TestConstants::throwIOException; static IOPredicate<Object> THROWING_IO_PREDICATE = t -> throwIOException(); static IOQuadFunction<Object, Object, Object, Object, Object> THROWING_IO_QUAD_FUNCTION = (t, u, v, w) -> throwIOException(); - static IORunnable THROWING_IO_RUNNABLE = () -> throwIOException(); + static IORunnable THROWING_IO_RUNNABLE = TestConstants::throwIOException; - static IOSupplier<Object> THROWING_IO_SUPPLIER = () -> throwIOException(); + static IOSupplier<Object> THROWING_IO_SUPPLIER = TestConstants::throwIOException; static IOTriConsumer<Object, Object, Object> THROWING_IO_TRI_CONSUMER = (t, u, v) -> throwIOException(); diff --git a/src/test/java/org/apache/commons/io/input/BOMInputStreamTest.java b/src/test/java/org/apache/commons/io/input/BOMInputStreamTest.java index a79cb1c9..9ce5d54e 100644 --- a/src/test/java/org/apache/commons/io/input/BOMInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/input/BOMInputStreamTest.java @@ -52,7 +52,7 @@ public class BOMInputStreamTest { /** * A mock InputStream that expects {@code close()} to be called. */ - private static class ExpectCloseInputStream extends InputStream { + private static final class ExpectCloseInputStream extends InputStream { private boolean _closeCalled; public void assertCloseCalled() { @@ -415,7 +415,7 @@ public class BOMInputStreamTest { assertThrows(IllegalArgumentException.class, () -> BOMInputStream.builder() .setInputStream(createUtf8Input(data, true)) .setInclude(true) - .setByteOrderMarks(new ByteOrderMark[0]) + .setByteOrderMarks() .get() .close()); } diff --git a/src/test/java/org/apache/commons/io/input/CharSequenceInputStreamTest.java b/src/test/java/org/apache/commons/io/input/CharSequenceInputStreamTest.java index 7bc997e0..a8e06b81 100644 --- a/src/test/java/org/apache/commons/io/input/CharSequenceInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/input/CharSequenceInputStreamTest.java @@ -32,9 +32,12 @@ import java.util.Random; import java.util.Set; import org.apache.commons.io.Charsets; +import org.apache.commons.io.CharsetsTest; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class CharSequenceInputStreamTest { @@ -78,11 +81,11 @@ public class CharSequenceInputStreamTest { "Shift_JIS".equalsIgnoreCase(csName); } - @Test - public void testAvailable() throws Exception { - for (final String csName : Charset.availableCharsets().keySet()) { - // prevent java.lang.UnsupportedOperationException at sun.nio.cs.ext.ISO2022_CN.newEncoder. - // also try and avoid the following exception + @ParameterizedTest(name = "{0}") + @MethodSource(CharsetsTest.AVAIL_CHARSETS) + public void testAvailable(final String csName) throws Exception { + // prevent java.lang.UnsupportedOperationException at sun.nio.cs.ext.ISO2022_CN.newEncoder. + // also try and avoid the following exception // java.lang.UnsupportedOperationException: null // at java.nio.CharBuffer.array(CharBuffer.java:940) // at sun.nio.cs.ext.COMPOUND_TEXT_Encoder.encodeLoop(COMPOUND_TEXT_Encoder.java:75) @@ -92,14 +95,13 @@ public class CharSequenceInputStreamTest { // at org.apache.commons.io.input.CharSequenceInputStreamTest.testAvailableRead(CharSequenceInputStreamTest.java:412) // at org.apache.commons.io.input.CharSequenceInputStreamTest.testAvailable(CharSequenceInputStreamTest.java:424) - try { - if (isAvailabilityTestableForCharset(csName)) { - testAvailableSkip(csName); - testAvailableRead(csName); - } - } catch (final UnsupportedOperationException e){ - fail("Operation not supported for " + csName); + try { + if (isAvailabilityTestableForCharset(csName)) { + testAvailableSkip(csName); + testAvailableRead(csName); } + } catch (final UnsupportedOperationException e) { + fail("Operation not supported for " + csName); } } @@ -157,13 +159,12 @@ public class CharSequenceInputStreamTest { // at sun.nio.cs.ext.COMPOUND_TEXT_Encoder.encodeLoop(COMPOUND_TEXT_Encoder.java:75) // at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:544) // at org.apache.commons.io.input.CharSequenceInputStream.fillBuffer(CharSequenceInputStream.java:111) - @Test - public void testBufferedRead_AvailableCharset() throws IOException { - for (final String csName : Charset.availableCharsets().keySet()) { - // prevent java.lang.UnsupportedOperationException at sun.nio.cs.ext.ISO2022_CN.newEncoder. - if (isAvailabilityTestableForCharset(csName)) { - testBufferedRead(TEST_STRING, csName); - } + @ParameterizedTest(name = "{0}") + @MethodSource(CharsetsTest.AVAIL_CHARSETS) + public void testBufferedRead_AvailableCharset(final String csName) throws IOException { + // prevent java.lang.UnsupportedOperationException at sun.nio.cs.ext.ISO2022_CN.newEncoder. + if (isAvailabilityTestableForCharset(csName)) { + testBufferedRead(TEST_STRING, csName); } } diff --git a/src/test/java/org/apache/commons/io/input/ClassLoaderObjectInputStreamTest.java b/src/test/java/org/apache/commons/io/input/ClassLoaderObjectInputStreamTest.java index 2e8d0f53..3b341ba0 100644 --- a/src/test/java/org/apache/commons/io/input/ClassLoaderObjectInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/input/ClassLoaderObjectInputStreamTest.java @@ -43,7 +43,7 @@ public class ClassLoaderObjectInputStreamTest { A, B, C } - private static class Test implements Serializable { + private static final class Test implements Serializable { private static final long serialVersionUID = 1L; private final int i; diff --git a/src/test/java/org/apache/commons/io/input/MarkShieldInputStreamTest.java b/src/test/java/org/apache/commons/io/input/MarkShieldInputStreamTest.java index a72e0f3c..ba0944ef 100644 --- a/src/test/java/org/apache/commons/io/input/MarkShieldInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/input/MarkShieldInputStreamTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.Test; public class MarkShieldInputStreamTest { - private static class MarkTestableInputStream extends ProxyInputStream { + private static final class MarkTestableInputStream extends ProxyInputStream { int markcount; int readlimit; diff --git a/src/test/java/org/apache/commons/io/input/MessageDigestCalculatingInputStreamTest.java b/src/test/java/org/apache/commons/io/input/MessageDigestCalculatingInputStreamTest.java index 517a014e..9123c41f 100644 --- a/src/test/java/org/apache/commons/io/input/MessageDigestCalculatingInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/input/MessageDigestCalculatingInputStreamTest.java @@ -20,40 +20,57 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.io.ByteArrayInputStream; import java.security.MessageDigest; -import java.util.Random; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.codec.digest.MessageDigestAlgorithms; +import org.apache.commons.io.input.MessageDigestCalculatingInputStream.Builder; import org.junit.jupiter.api.Test; /** * Tests {@link MessageDigestCalculatingInputStream}. */ +@SuppressWarnings("deprecation") public class MessageDigestCalculatingInputStreamTest { - public static byte[] generateRandomByteStream(final int pSize) { - final byte[] buffer = new byte[pSize]; - final Random rnd = new Random(); - rnd.nextBytes(buffer); - return buffer; - } - @Test - public void test() throws Exception { + public void testNormalUse() throws Exception { for (int i = 256; i < 8192; i = i * 2) { - final byte[] buffer = generateRandomByteStream(i); - final MessageDigest messageDigest = MessageDigestCalculatingInputStream.getDefaultMessageDigest(); - final byte[] expect = messageDigest.digest(buffer); + final byte[] buffer = MessageDigestInputStreamTest.generateRandomByteStream(i); + final MessageDigest defaultMessageDigest = MessageDigestCalculatingInputStream.getDefaultMessageDigest(); + final byte[] defaultExpect = defaultMessageDigest.digest(buffer); + // Defaults try (MessageDigestCalculatingInputStream messageDigestInputStream = new MessageDigestCalculatingInputStream(new ByteArrayInputStream(buffer))) { messageDigestInputStream.consume(); - assertArrayEquals(expect, messageDigestInputStream.getMessageDigest().digest()); + assertArrayEquals(defaultExpect, messageDigestInputStream.getMessageDigest().digest()); } try (MessageDigestCalculatingInputStream messageDigestInputStream = MessageDigestCalculatingInputStream.builder() .setInputStream(new ByteArrayInputStream(buffer)).get()) { messageDigestInputStream.consume(); - assertArrayEquals(expect, messageDigestInputStream.getMessageDigest().digest()); + assertArrayEquals(defaultExpect, messageDigestInputStream.getMessageDigest().digest()); } try (MessageDigestCalculatingInputStream messageDigestInputStream = MessageDigestCalculatingInputStream.builder().setByteArray(buffer).get()) { messageDigestInputStream.consume(); - assertArrayEquals(expect, messageDigestInputStream.getMessageDigest().digest()); + assertArrayEquals(defaultExpect, messageDigestInputStream.getMessageDigest().digest()); + } + // SHA-512 + final byte[] sha512Expect = DigestUtils.sha512(buffer); + { + final Builder builder = MessageDigestCalculatingInputStream.builder(); + builder.setMessageDigest(MessageDigestAlgorithms.SHA_512); + builder.setInputStream(new ByteArrayInputStream(buffer)); + try (MessageDigestCalculatingInputStream messageDigestInputStream = builder.get()) { + messageDigestInputStream.consume(); + assertArrayEquals(sha512Expect, messageDigestInputStream.getMessageDigest().digest()); + } + } + { + final Builder builder = MessageDigestCalculatingInputStream.builder(); + builder.setMessageDigest(MessageDigestAlgorithms.SHA_512); + builder.setInputStream(new ByteArrayInputStream(buffer)); + try (MessageDigestCalculatingInputStream messageDigestInputStream = builder.get()) { + messageDigestInputStream.consume(); + assertArrayEquals(sha512Expect, messageDigestInputStream.getMessageDigest().digest()); + } } } } diff --git a/src/test/java/org/apache/commons/io/input/MessageDigestInputStreamTest.java b/src/test/java/org/apache/commons/io/input/MessageDigestInputStreamTest.java new file mode 100644 index 00000000..d41da0b7 --- /dev/null +++ b/src/test/java/org/apache/commons/io/input/MessageDigestInputStreamTest.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.io.input; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.ByteArrayInputStream; +import java.util.Random; + +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.codec.digest.MessageDigestAlgorithms; +import org.junit.jupiter.api.Test; + +/** + * Tests {@link MessageDigestInputStream}. + */ +public class MessageDigestInputStreamTest { + + static byte[] generateRandomByteStream(final int pSize) { + final byte[] buffer = new byte[pSize]; + final Random rnd = new Random(); + rnd.nextBytes(buffer); + return buffer; + } + + @Test + public void testNoDefault() throws Exception { + assertThrows(IllegalStateException.class, () -> MessageDigestInputStream.builder().get()); + assertThrows(NullPointerException.class, () -> MessageDigestInputStream.builder().setInputStream(new ByteArrayInputStream(new byte[] { 1 })).get()); + } + + @Test + public void testNormalUse() throws Exception { + for (int i = 256; i < 8192; i = i * 2) { + final byte[] buffer = generateRandomByteStream(i); + final byte[] expect = DigestUtils.sha512(buffer); + try (MessageDigestInputStream messageDigestInputStream = MessageDigestInputStream.builder().setMessageDigest(MessageDigestAlgorithms.SHA_512) + .setInputStream(new ByteArrayInputStream(buffer)).get()) { + messageDigestInputStream.consume(); + assertArrayEquals(expect, messageDigestInputStream.getMessageDigest().digest()); + } + try (MessageDigestInputStream messageDigestInputStream = MessageDigestInputStream.builder().setByteArray(buffer) + .setMessageDigest(DigestUtils.getSha512Digest()).get()) { + messageDigestInputStream.consume(); + assertArrayEquals(expect, messageDigestInputStream.getMessageDigest().digest()); + } + } + } + +} diff --git a/src/test/java/org/apache/commons/io/input/ObservableInputStreamTest.java b/src/test/java/org/apache/commons/io/input/ObservableInputStreamTest.java index 0a0e9150..8c099ade 100644 --- a/src/test/java/org/apache/commons/io/input/ObservableInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/input/ObservableInputStreamTest.java @@ -35,7 +35,7 @@ import org.junit.jupiter.api.Test; */ public class ObservableInputStreamTest { - private static class DataViewObserver extends MethodCountObserver { + private static final class DataViewObserver extends MethodCountObserver { private byte[] buffer; private int lastValue = -1; private int length = -1; @@ -55,7 +55,7 @@ public class ObservableInputStreamTest { } } - private static class LengthObserver extends Observer { + private static final class LengthObserver extends Observer { private long total; @Override @@ -153,8 +153,7 @@ public class ObservableInputStreamTest { */ @Test public void testDataByteCalled_add() throws Exception { - final byte[] buffer = MessageDigestCalculatingInputStreamTest - .generateRandomByteStream(IOUtils.DEFAULT_BUFFER_SIZE); + final byte[] buffer = MessageDigestInputStreamTest.generateRandomByteStream(IOUtils.DEFAULT_BUFFER_SIZE); final DataViewObserver lko = new DataViewObserver(); try (ObservableInputStream ois = new ObservableInputStream(new ByteArrayInputStream(buffer))) { assertEquals(-1, lko.lastValue); @@ -185,8 +184,7 @@ public class ObservableInputStreamTest { */ @Test public void testDataByteCalled_ctor() throws Exception { - final byte[] buffer = MessageDigestCalculatingInputStreamTest - .generateRandomByteStream(IOUtils.DEFAULT_BUFFER_SIZE); + final byte[] buffer = MessageDigestInputStreamTest.generateRandomByteStream(IOUtils.DEFAULT_BUFFER_SIZE); final DataViewObserver lko = new DataViewObserver(); try (ObservableInputStream ois = new ObservableInputStream(new ByteArrayInputStream(buffer), lko)) { assertEquals(-1, lko.lastValue); @@ -216,10 +214,9 @@ public class ObservableInputStreamTest { */ @Test public void testDataBytesCalled() throws Exception { - final byte[] buffer = MessageDigestCalculatingInputStreamTest - .generateRandomByteStream(IOUtils.DEFAULT_BUFFER_SIZE); + final byte[] buffer = MessageDigestInputStreamTest.generateRandomByteStream(IOUtils.DEFAULT_BUFFER_SIZE); try (ByteArrayInputStream bais = new ByteArrayInputStream(buffer); - final ObservableInputStream ois = new ObservableInputStream(bais)) { + final ObservableInputStream ois = new ObservableInputStream(bais)) { final DataViewObserver observer = new DataViewObserver(); final byte[] readBuffer = new byte[23]; assertNull(observer.buffer); diff --git a/src/test/java/org/apache/commons/io/input/ProxyReaderTest.java b/src/test/java/org/apache/commons/io/input/ProxyReaderTest.java index b176d480..110d11d2 100644 --- a/src/test/java/org/apache/commons/io/input/ProxyReaderTest.java +++ b/src/test/java/org/apache/commons/io/input/ProxyReaderTest.java @@ -28,7 +28,7 @@ import org.junit.jupiter.api.Test; public class ProxyReaderTest { /** Custom NullReader implementation. */ - private static class CustomNullReader extends NullReader { + private static final class CustomNullReader extends NullReader { CustomNullReader(final int len) { super(len); } @@ -45,7 +45,7 @@ public class ProxyReaderTest { } /** ProxyReader implementation. */ - private static class ProxyReaderImpl extends ProxyReader { + private static final class ProxyReaderImpl extends ProxyReader { ProxyReaderImpl(final Reader proxy) { super(proxy); } diff --git a/src/test/java/org/apache/commons/io/input/TailerTest.java b/src/test/java/org/apache/commons/io/input/TailerTest.java index f0e1f340..783e1718 100644 --- a/src/test/java/org/apache/commons/io/input/TailerTest.java +++ b/src/test/java/org/apache/commons/io/input/TailerTest.java @@ -60,7 +60,7 @@ import org.junit.jupiter.api.io.TempDir; */ public class TailerTest { - private static class NonStandardTailable implements Tailer.Tailable { + private static final class NonStandardTailable implements Tailer.Tailable { private final File file; @@ -115,7 +115,7 @@ public class TailerTest { /** * Test {@link TailerListener} implementation. */ - private static class TestTailerListener extends TailerListenerAdapter { + private static final class TestTailerListener extends TailerListenerAdapter { // Must be synchronized because it is written by one thread and read by another private final List<String> lines = Collections.synchronizedList(new ArrayList<>()); @@ -266,16 +266,6 @@ public class TailerTest { } @Test - public void testCreatorWithDelayAndFromStartWithReopen() throws Exception { - final File file = new File(temporaryFolder, "tailer-create-with-delay-and-from-start-with-reopen.txt"); - createFile(file, 0); - final TestTailerListener listener = new TestTailerListener(1); - try (Tailer tailer = Tailer.create(file, listener, TEST_DELAY_MILLIS, false, false)) { - validateTailer(listener, file); - } - } - - @Test public void testCreateWithDelay() throws Exception { final File file = new File(temporaryFolder, "tailer-create-with-delay.txt"); createFile(file, 0); @@ -325,6 +315,16 @@ public class TailerTest { } } + @Test + public void testCreatorWithDelayAndFromStartWithReopen() throws Exception { + final File file = new File(temporaryFolder, "tailer-create-with-delay-and-from-start-with-reopen.txt"); + createFile(file, 0); + final TestTailerListener listener = new TestTailerListener(1); + try (Tailer tailer = Tailer.create(file, listener, TEST_DELAY_MILLIS, false, false)) { + validateTailer(listener, file); + } + } + /* * Tests [IO-357][Tailer] InterruptedException while the thread is sleeping is silently ignored. */ diff --git a/src/test/java/org/apache/commons/io/input/TimestampedObserverTest.java b/src/test/java/org/apache/commons/io/input/TimestampedObserverTest.java index 54922005..ea37b381 100644 --- a/src/test/java/org/apache/commons/io/input/TimestampedObserverTest.java +++ b/src/test/java/org/apache/commons/io/input/TimestampedObserverTest.java @@ -51,7 +51,7 @@ public class TimestampedObserverTest { assertTrue(timestampedObserver.getOpenToNowDuration().toNanos() > 0); assertNull(timestampedObserver.getCloseInstant()); assertFalse(timestampedObserver.isClosed()); - final byte[] buffer = MessageDigestCalculatingInputStreamTest.generateRandomByteStream(IOUtils.DEFAULT_BUFFER_SIZE); + final byte[] buffer = MessageDigestInputStreamTest.generateRandomByteStream(IOUtils.DEFAULT_BUFFER_SIZE); try (ObservableInputStream ois = new ObservableInputStream(new ByteArrayInputStream(buffer), timestampedObserver)) { assertTrue(timestampedObserver.getOpenInstant().isAfter(before)); assertTrue(timestampedObserver.getOpenToNowDuration().toNanos() > 0); @@ -68,7 +68,7 @@ public class TimestampedObserverTest { @Test public void testExample() throws IOException { final TimestampedObserver timestampedObserver = new TimestampedObserver(); - final byte[] buffer = MessageDigestCalculatingInputStreamTest + final byte[] buffer = MessageDigestInputStreamTest .generateRandomByteStream(IOUtils.DEFAULT_BUFFER_SIZE); try (ObservableInputStream ois = new ObservableInputStream(new ByteArrayInputStream(buffer), timestampedObserver)) { diff --git a/src/test/java/org/apache/commons/io/input/UnsynchronizedBufferedInputStreamTest.java b/src/test/java/org/apache/commons/io/input/UnsynchronizedBufferedInputStreamTest.java index f7fcba81..d2e969ca 100644 --- a/src/test/java/org/apache/commons/io/input/UnsynchronizedBufferedInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/input/UnsynchronizedBufferedInputStreamTest.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -31,6 +30,7 @@ import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.io.IOUtils; +import org.apache.commons.io.input.UnsynchronizedBufferedInputStream.Builder; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -50,12 +50,16 @@ public class UnsynchronizedBufferedInputStreamTest { Path fileName; - private BufferedInputStream is; + private UnsynchronizedBufferedInputStream is; private InputStream isFile; byte[] ibuf = new byte[BUFFER_SIZE]; + private Builder builder() { + return new UnsynchronizedBufferedInputStream.Builder(); + } + /** * Sets up the fixture, for example, open a network connection. This method is called before a test is executed. * @@ -67,7 +71,7 @@ public class UnsynchronizedBufferedInputStreamTest { Files.write(fileName, DATA.getBytes(StandardCharsets.UTF_8)); isFile = Files.newInputStream(fileName); - is = new BufferedInputStream(isFile); + is = builder().setInputStream(isFile).get(); } /** @@ -82,7 +86,7 @@ public class UnsynchronizedBufferedInputStreamTest { } /** - * Tests java.io.BufferedInputStream#available() + * Tests {@link UnsynchronizedBufferedInputStream#available()}. * * @throws IOException Thrown on test failure. */ @@ -91,7 +95,8 @@ public class UnsynchronizedBufferedInputStreamTest { assertEquals(DATA.length(), is.available(), "Returned incorrect number of available bytes"); // Test that a closed stream throws an IOE for available() - final BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(new byte[] { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' })); + final UnsynchronizedBufferedInputStream bis = builder() + .setInputStream(new ByteArrayInputStream(new byte[] { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' })).get(); final int available = bis.available(); bis.close(); assertTrue(available != 0); @@ -100,18 +105,13 @@ public class UnsynchronizedBufferedInputStreamTest { } /** - * Tests java.io.BufferedInputStream#close() + * Tests {@link UnsynchronizedBufferedInputStream#close()}. * * @throws IOException Thrown on test failure. */ @Test public void test_close() throws IOException { - new BufferedInputStream(isFile).close(); - - // regression for HARMONY-667 - try (BufferedInputStream buf = new BufferedInputStream(null, 5)) { - // closes - } + builder().setInputStream(isFile).get().close(); try (InputStream in = new InputStream() { Object lock = new Object(); @@ -140,7 +140,7 @@ public class UnsynchronizedBufferedInputStreamTest { return 1; } }) { - final BufferedInputStream bufin = new BufferedInputStream(in); + final UnsynchronizedBufferedInputStream bufin = builder().setInputStream(in).get(); final Thread thread = new Thread(() -> { try { Thread.sleep(1000); @@ -155,28 +155,24 @@ public class UnsynchronizedBufferedInputStreamTest { } /* - * Tests java.io.BufferedInputStream(InputStream) + * Tests {@link UnsynchronizedBufferedInputStream#Builder()}. */ @Test - public void test_ConstructorLjava_io_InputStream() throws IOException { - try (BufferedInputStream str = new BufferedInputStream(null)) { - assertThrows(IOException.class, () -> str.read(), "Expected an IOException"); - } + public void test_ConstructorLjava_io_InputStream() { + assertThrows(NullPointerException.class, () -> builder().setInputStream(null).get()); } /* - * Tests java.io.BufferedInputStream(InputStream) + * Tests {@link UnsynchronizedBufferedInputStream#Builder()}. */ @Test public void test_ConstructorLjava_io_InputStreamI() throws IOException { - try (BufferedInputStream str = new BufferedInputStream(null, 1)) { - assertThrows(IOException.class, () -> str.read(), "Expected an IOException"); - } + assertThrows(NullPointerException.class, () -> builder().setInputStream(null).setBufferSize(1).get()); - // Test for method java.io.BufferedInputStream(java.io.InputStream, int) + // Test for method UnsynchronizedBufferedInputStream(InputStream, int) // Create buffer with exact size of file - is = new BufferedInputStream(isFile, this.DATA.length()); + is = builder().setInputStream(isFile).setBufferSize(DATA.length()).get(); // Ensure buffer gets filled by evaluating one read is.read(); // Close underlying FileInputStream, all but 1 buffered bytes should @@ -184,16 +180,17 @@ public class UnsynchronizedBufferedInputStreamTest { isFile.close(); // Read the remaining buffered characters, no IOException should // occur. - is.skip(this.DATA.length() - 2); + is.skip(DATA.length() - 2); is.read(); // is.read should now throw an exception because it will have to be filled. assertThrows(IOException.class, () -> is.read()); - assertThrows(NullPointerException.class, () -> UnsynchronizedBufferedInputStream.builder().setInputStream(null).setBufferSize(100).get()); + assertThrows(NullPointerException.class, () -> builder().setInputStream(null).setBufferSize(100).get()); + assertThrows(NullPointerException.class, () -> builder().setInputStream(null)); } /** - * Tests java.io.BufferedInputStream#mark(int) + * Tests {@link UnsynchronizedBufferedInputStream#mark(int)}. * * @throws IOException Thrown on test failure. */ @@ -213,21 +210,21 @@ public class UnsynchronizedBufferedInputStreamTest { for (int i = 0; i < 256; i++) { bytes[i] = (byte) i; } - InputStream in = new BufferedInputStream(new ByteArrayInputStream(bytes), 12); + InputStream in = builder().setInputStream(new ByteArrayInputStream(bytes)).setBufferSize(12).get(); in.skip(6); in.mark(14); in.read(new byte[14], 0, 14); in.reset(); assertTrue(in.read() == 6 && in.read() == 7, "Wrong bytes"); - in = new BufferedInputStream(new ByteArrayInputStream(bytes), 12); + in = builder().setInputStream(new ByteArrayInputStream(bytes)).setBufferSize(12).get(); in.skip(6); in.mark(8); in.skip(7); in.reset(); assertTrue(in.read() == 6 && in.read() == 7, "Wrong bytes 2"); - BufferedInputStream buf = new BufferedInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4 }), 2); + UnsynchronizedBufferedInputStream buf = builder().setInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4 })).setBufferSize(2).get(); buf.mark(3); bytes = new byte[3]; int result = buf.read(bytes); @@ -237,7 +234,7 @@ public class UnsynchronizedBufferedInputStreamTest { assertEquals(2, bytes[2], "Assert 2:"); assertEquals(3, buf.read(), "Assert 3:"); - buf = new BufferedInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4 }), 2); + buf = builder().setInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4 })).setBufferSize(2).get(); buf.mark(3); bytes = new byte[4]; result = buf.read(bytes); @@ -249,14 +246,14 @@ public class UnsynchronizedBufferedInputStreamTest { assertEquals(4, buf.read(), "Assert 8:"); assertEquals(-1, buf.read(), "Assert 9:"); - buf = new BufferedInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4 }), 2); + buf = builder().setInputStream(new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4 })).setBufferSize(2).get(); buf.mark(Integer.MAX_VALUE); buf.read(); buf.close(); } /** - * Tests java.io.BufferedInputStream#markSupported() + * Tests {@link UnsynchronizedBufferedInputStream#markSupported()}. */ @Test public void test_markSupported() { @@ -264,7 +261,7 @@ public class UnsynchronizedBufferedInputStreamTest { } /** - * Tests java.io.BufferedInputStream#read() + * Tests {@link UnsynchronizedBufferedInputStream#read()}. * * @throws IOException Thrown on test failure. */ @@ -278,7 +275,7 @@ public class UnsynchronizedBufferedInputStreamTest { for (int i = 0; i < 256; i++) { bytes[i] = (byte) i; } - final InputStream in = new BufferedInputStream(new ByteArrayInputStream(bytes), 12); + final InputStream in = builder().setInputStream(new ByteArrayInputStream(bytes)).setBufferSize(12).get(); assertEquals(0, in.read(), "Wrong initial byte"); // Fill the buffer final byte[] buf = new byte[14]; in.read(buf, 0, 14); // Read greater than the buffer @@ -287,7 +284,7 @@ public class UnsynchronizedBufferedInputStreamTest { } /** - * Tests java.io.BufferedInputStream#read(byte[], int, int) + * Tests {@link UnsynchronizedBufferedInputStream#read(byte[], int, int)}. * * @throws IOException Thrown on test failure. */ @@ -299,7 +296,7 @@ public class UnsynchronizedBufferedInputStreamTest { is.read(buf1, 0, buf1.length); assertTrue(new String(buf1, 0, buf1.length).equals(DATA.substring(3000, 3100)), "Failed to read correct data"); - try (BufferedInputStream bufin = new BufferedInputStream(new InputStream() { + try (UnsynchronizedBufferedInputStream bufin = builder().setInputStream(new InputStream() { int size = 2, pos = 0; byte[] contents = new byte[size]; @@ -330,7 +327,7 @@ public class UnsynchronizedBufferedInputStreamTest { pos += toRead; return toRead; } - })) { + }).get()) { bufin.read(); final int result = bufin.read(new byte[2], 0, 2); assertEquals(1, result, () -> "Incorrect result: " + result); @@ -338,26 +335,7 @@ public class UnsynchronizedBufferedInputStreamTest { } /** - * Tests java.io.BufferedInputStream#read(byte[], int, int) - * - * @throws IOException Thrown on test failure. - */ - @Test - public void test_read$BII_Exception() throws IOException { - final BufferedInputStream bis = new BufferedInputStream(null); - assertThrows(NullPointerException.class, () -> bis.read(null, -1, -1)); - - assertThrows(IndexOutOfBoundsException.class, () -> bis.read(new byte[0], -1, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> bis.read(new byte[0], 1, -1)); - assertThrows(IndexOutOfBoundsException.class, () -> bis.read(new byte[0], 1, 1)); - - bis.close(); - - assertThrows(IOException.class, () -> bis.read(null, -1, -1)); - } - - /** - * Tests java.io.BufferedInputStream#reset() + * Tests {@link UnsynchronizedBufferedInputStream#reset()}. * * @throws IOException Thrown on test failure. */ @@ -372,7 +350,7 @@ public class UnsynchronizedBufferedInputStreamTest { is.reset(); assertTrue(new String(buf1, 0, buf1.length).equals(new String(buf2, 0, buf2.length)), "Reset failed"); - final BufferedInputStream bIn = new BufferedInputStream(new ByteArrayInputStream("1234567890".getBytes())); + final UnsynchronizedBufferedInputStream bIn = builder().setInputStream(new ByteArrayInputStream("1234567890".getBytes())).get(); bIn.mark(10); for (int i = 0; i < 11; i++) { bIn.read(); @@ -381,36 +359,14 @@ public class UnsynchronizedBufferedInputStreamTest { } /** - * Tests java.io.BufferedInputStream#reset() - * - * @throws IOException Thrown on test failure. - */ - @Test - public void test_reset_Exception() throws IOException { - final BufferedInputStream bis = new BufferedInputStream(null); - - // throws IOException with message "Mark has been invalidated" - assertThrows(IOException.class, () -> bis.reset()); - - // does not throw IOException - bis.mark(1); - bis.reset(); - - bis.close(); - - // throws IOException with message "stream is closed" - assertThrows(IOException.class, () -> bis.reset()); - } - - /** - * Tests java.io.BufferedInputStream#reset() + * Tests {@link UnsynchronizedBufferedInputStream#reset()}. * * @throws IOException Thrown on test failure. */ @Test public void test_reset_scenario1() throws IOException { final byte[] input = "12345678900".getBytes(); - final BufferedInputStream bufin = new BufferedInputStream(new ByteArrayInputStream(input)); + final UnsynchronizedBufferedInputStream bufin = builder().setInputStream(new ByteArrayInputStream(input)).get(); bufin.read(); bufin.mark(5); bufin.skip(5); @@ -418,33 +374,31 @@ public class UnsynchronizedBufferedInputStreamTest { } /** - * Tests java.io.BufferedInputStream#reset() + * Tests {@link UnsynchronizedBufferedInputStream#reset()}. * * @throws IOException Thrown on test failure. */ @Test public void test_reset_scenario2() throws IOException { final byte[] input = "12345678900".getBytes(); - final BufferedInputStream bufin = new BufferedInputStream(new ByteArrayInputStream(input)); + final UnsynchronizedBufferedInputStream bufin = builder().setInputStream(new ByteArrayInputStream(input)).get(); bufin.mark(5); bufin.skip(6); bufin.reset(); } /** - * Tests java.io.BufferedInputStream#skip(long) + * Tests {@link UnsynchronizedBufferedInputStream#skip(long)}. * * @throws IOException Thrown on test failure. */ @Test public void test_skip_NullInputStream() throws IOException { - try (BufferedInputStream buf = new BufferedInputStream(null, 5)) { - assertEquals(0, buf.skip(0)); - } + assertThrows(NullPointerException.class, () -> builder().setInputStream(null).setBufferSize(5).get()); } /** - * Tests java.io.BufferedInputStream#skip(long) + * Tests {@link UnsynchronizedBufferedInputStream#skip(long)}. * * @throws IOException Thrown on test failure. */ @@ -456,10 +410,5 @@ public class UnsynchronizedBufferedInputStreamTest { is.read(buf1, 0, buf1.length); is.reset(); assertTrue(new String(buf1, 0, buf1.length).equals(DATA.substring(1000, 1010)), "Failed to skip to correct position"); - - // regression for HARMONY-667 - try (BufferedInputStream buf = new BufferedInputStream(null, 5)) { - assertThrows(IOException.class, () -> buf.skip(10)); - } } } diff --git a/src/test/java/org/apache/commons/io/input/XmlStreamReaderTest.java b/src/test/java/org/apache/commons/io/input/XmlStreamReaderTest.java index 555cf7ca..63d587a8 100644 --- a/src/test/java/org/apache/commons/io/input/XmlStreamReaderTest.java +++ b/src/test/java/org/apache/commons/io/input/XmlStreamReaderTest.java @@ -30,6 +30,7 @@ import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -37,10 +38,15 @@ import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.text.MessageFormat; import java.util.HashMap; +import java.util.Locale; import java.util.Map; +import org.apache.commons.io.CharsetsTest; import org.apache.commons.io.IOUtils; +import org.apache.commons.io.function.IOFunction; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.junitpioneer.jupiter.DefaultLocale; public class XmlStreamReaderTest { @@ -162,6 +168,14 @@ public class XmlStreamReaderTest { return new ByteArrayInputStream(baos.toByteArray()); } + private void parseCharset(final String hdr, final String enc, final IOFunction<InputStream, XmlStreamReader> factory) throws Exception { + try (final InputStream stream = new ByteArrayInputStream(hdr.getBytes(StandardCharsets.UTF_8))) { + try (final XmlStreamReader xml = factory.apply(stream)) { + assertEquals(enc.toUpperCase(Locale.ROOT), xml.getEncoding(), enc); + } + } + } + public void testAlternateDefaultEncoding(final String contentType, final String bomEnc, final String streamEnc, final String prologEnc, final String alternateEnc) throws Exception { try (InputStream is = getXmlInputStream(bomEnc, prologEnc == null ? XML1 : XML3, streamEnc, prologEnc); @@ -276,6 +290,8 @@ public class XmlStreamReaderTest { assertThrows(NullPointerException.class, () -> new XmlStreamReader((URL) null)); } + // XML Stream generator + @Test public void testEncodingAttributeXML() throws Exception { try (InputStream is = new ByteArrayInputStream(ENCODING_ATTRIBUTE_XML.getBytes(StandardCharsets.UTF_8)); @@ -294,8 +310,6 @@ public class XmlStreamReaderTest { } } - // XML Stream generator - @Test public void testHttp() throws Exception { // niallp 2010-10-06 - remove following 2 tests - I reinstated @@ -431,6 +445,20 @@ public class XmlStreamReaderTest { } } + @ParameterizedTest(name = "{0}") + @MethodSource(CharsetsTest.AVAIL_CHARSETS) + public void testIO_815(final String csName) throws Exception { + final MessageFormat fmt = new MessageFormat("<?xml version=\"1.0\" encoding=''{0}''?>\n<root>text</root>"); + final IOFunction<InputStream, XmlStreamReader> factoryCtor = XmlStreamReader::new; + final IOFunction<InputStream, XmlStreamReader> factoryBuilder = stream -> XmlStreamReader.builder().setInputStream(stream).get(); + parseCharset(fmt.format(new Object[] { csName }), csName, factoryCtor); + parseCharset(fmt.format(new Object[] { csName }), csName, factoryBuilder); + for (final String alias : Charset.forName(csName).aliases()) { + parseCharset(fmt.format(new Object[] { alias }), alias, factoryCtor); + parseCharset(fmt.format(new Object[] { alias }), alias, factoryBuilder); + } + } + // Turkish language has specific rules to convert dotted and dotless i character. @Test @DefaultLocale(language = "tr") diff --git a/src/test/java/org/apache/commons/io/input/XmlStreamReaderUtilitiesTest.java b/src/test/java/org/apache/commons/io/input/XmlStreamReaderUtilitiesTest.java index e2cd2e68..821df8a6 100644 --- a/src/test/java/org/apache/commons/io/input/XmlStreamReaderUtilitiesTest.java +++ b/src/test/java/org/apache/commons/io/input/XmlStreamReaderUtilitiesTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.Test; public class XmlStreamReaderUtilitiesTest { /** Mock {@link XmlStreamReader} implementation */ - private static class MockXmlStreamReader extends XmlStreamReader { + private static final class MockXmlStreamReader extends XmlStreamReader { MockXmlStreamReader(final String defaultEncoding) throws IOException { super(CharSequenceInputStream.builder().setCharSequence("").get(), null, true, defaultEncoding); } diff --git a/src/test/java/org/apache/commons/io/input/compatibility/XmlStreamReaderUtilitiesCompatibilityTest.java b/src/test/java/org/apache/commons/io/input/compatibility/XmlStreamReaderUtilitiesCompatibilityTest.java index ee4310a8..acfeb742 100644 --- a/src/test/java/org/apache/commons/io/input/compatibility/XmlStreamReaderUtilitiesCompatibilityTest.java +++ b/src/test/java/org/apache/commons/io/input/compatibility/XmlStreamReaderUtilitiesCompatibilityTest.java @@ -27,7 +27,7 @@ import org.apache.commons.io.input.XmlStreamReaderUtilitiesTest; public class XmlStreamReaderUtilitiesCompatibilityTest extends XmlStreamReaderUtilitiesTest { /** Mock {@link XmlStreamReader} implementation */ - private static class MockXmlStreamReader extends XmlStreamReader { + private static final class MockXmlStreamReader extends XmlStreamReader { MockXmlStreamReader(final String defaultEncoding) throws IOException { super(CharSequenceInputStream.builder().setCharSequence("").get(), null, true, defaultEncoding); } diff --git a/src/test/java/org/apache/commons/io/jmh/PathUtilsContentEqualsBenchmark.java b/src/test/java/org/apache/commons/io/jmh/PathUtilsContentEqualsBenchmark.java new file mode 100644 index 00000000..20e49e71 --- /dev/null +++ b/src/test/java/org/apache/commons/io/jmh/PathUtilsContentEqualsBenchmark.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.io.jmh; + +import java.io.IOException; +import java.io.RandomAccessFile; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.io.RandomAccessFileMode; +import org.apache.commons.io.RandomAccessFiles; +import org.apache.commons.io.file.PathUtils; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +/** + * Test different implementations of {@link PathUtils#fileContentEquals(Path, Path)}. + * + * <pre> + * Benchmark Mode Cnt Score Error Units + * PathUtilsContentEqualsBenchmark.testCurrent_fileContentEquals avgt 5 4.538 ▒ 1.010 ms/op + * PathUtilsContentEqualsBenchmark.testCurrent_fileContentEquals_Blackhole avgt 5 110.627 ▒ 30.317 ms/op + * PathUtilsContentEqualsBenchmark.testProposal_contentEquals avgt 5 1.812 ▒ 0.634 ms/op + * PathUtilsContentEqualsBenchmark.testProposal_contentEquals_Blackhole avgt 5 43.521 ▒ 6.762 ms/op + * </pre> + */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@State(Scope.Thread) +@Warmup(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) +@Fork(value = 1, jvmArgs = { "-server" }) +public class PathUtilsContentEqualsBenchmark { + + private static final Path bigFile1; + private static final Path bigFile2; + + static { + // Set up test fixtures + try { + bigFile1 = Files.createTempFile(PathUtilsContentEqualsBenchmark.class.getSimpleName(), "-1.bin"); + bigFile2 = Files.createTempFile(PathUtilsContentEqualsBenchmark.class.getSimpleName(), "-2.bin"); + final int newLength = 1_000_000; + final byte[] bytes1 = new byte[newLength]; + Arrays.fill(bytes1, (byte) 1); + Files.write(bigFile1, bytes1); + Files.copy(bigFile1, bigFile2, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + public static boolean newFileContentEquals(final Path path1, final Path path2) throws IOException { + try (RandomAccessFile raf1 = RandomAccessFileMode.READ_ONLY.create(path1); + RandomAccessFile raf2 = RandomAccessFileMode.READ_ONLY.create(path2)) { + return RandomAccessFiles.contentEquals(raf1, raf2); + } + } + + @Benchmark + public boolean[] testCurrent_fileContentEquals() throws IOException { + final boolean[] res = new boolean[1]; + res[0] = PathUtils.fileContentEquals(bigFile1, bigFile2); + return res; + } + + @Benchmark + public void testCurrent_fileContentEquals_Blackhole(final Blackhole blackhole) throws IOException { + for (int i = 0; i < 5; i++) { + for (int j = 0; j < 5; j++) { + blackhole.consume(PathUtils.fileContentEquals(bigFile1, bigFile2)); + } + } + } + + @Benchmark + public boolean[] testProposal_contentEquals() throws IOException { + final boolean[] res = new boolean[1]; + res[0] = newFileContentEquals(bigFile1, bigFile2); + return res; + } + + @Benchmark + public void testProposal_contentEquals_Blackhole(final Blackhole blackhole) throws IOException { + for (int i = 0; i < 5; i++) { + for (int j = 0; j < 5; j++) { + blackhole.consume(newFileContentEquals(bigFile1, bigFile2)); + } + } + } + +} diff --git a/src/test/java/org/apache/commons/io/output/ByteArrayOutputStreamTest.java b/src/test/java/org/apache/commons/io/output/ByteArrayOutputStreamTest.java index 2d11e58c..a65961d0 100644 --- a/src/test/java/org/apache/commons/io/output/ByteArrayOutputStreamTest.java +++ b/src/test/java/org/apache/commons/io/output/ByteArrayOutputStreamTest.java @@ -46,7 +46,7 @@ public class ByteArrayOutputStreamTest { T newInstance(final int size); } - private static class ByteArrayOutputStreamFactory implements BAOSFactory<ByteArrayOutputStream> { + private static final class ByteArrayOutputStreamFactory implements BAOSFactory<ByteArrayOutputStream> { @Override public ByteArrayOutputStream newInstance() { return new ByteArrayOutputStream(); @@ -58,7 +58,7 @@ public class ByteArrayOutputStreamTest { } } - private static class UnsynchronizedByteArrayOutputStreamFactory implements BAOSFactory<UnsynchronizedByteArrayOutputStream> { + private static final class UnsynchronizedByteArrayOutputStreamFactory implements BAOSFactory<UnsynchronizedByteArrayOutputStream> { @Override public UnsynchronizedByteArrayOutputStream newInstance() { return new UnsynchronizedByteArrayOutputStream(); diff --git a/src/test/java/org/apache/commons/io/output/ThresholdingOutputStreamTest.java b/src/test/java/org/apache/commons/io/output/ThresholdingOutputStreamTest.java index dd1299e0..080a4927 100644 --- a/src/test/java/org/apache/commons/io/output/ThresholdingOutputStreamTest.java +++ b/src/test/java/org/apache/commons/io/output/ThresholdingOutputStreamTest.java @@ -33,7 +33,7 @@ import org.junit.jupiter.api.Test; public class ThresholdingOutputStreamTest { @Test - public void testSetByteCount_Stream() throws Exception { + public void testSetByteCount_OutputStream() throws Exception { final AtomicBoolean reached = new AtomicBoolean(false); try (ThresholdingOutputStream tos = new ThresholdingOutputStream(3) { { @@ -41,7 +41,7 @@ public class ThresholdingOutputStreamTest { } @Override - protected OutputStream getStream() throws IOException { + protected OutputStream getOutputStream() throws IOException { return new ByteArrayOutputStream(4); } @@ -58,7 +58,7 @@ public class ThresholdingOutputStreamTest { } @Test - public void testSetByteCount_OutputStream() throws Exception { + public void testSetByteCount_Stream() throws Exception { final AtomicBoolean reached = new AtomicBoolean(false); try (ThresholdingOutputStream tos = new ThresholdingOutputStream(3) { { @@ -66,7 +66,7 @@ public class ThresholdingOutputStreamTest { } @Override - protected OutputStream getOutputStream() throws IOException { + protected OutputStream getStream() throws IOException { return new ByteArrayOutputStream(4); } diff --git a/src/test/java/org/apache/commons/io/test/TestUtils.java b/src/test/java/org/apache/commons/io/test/TestUtils.java index 0620603d..3a01f702 100644 --- a/src/test/java/org/apache/commons/io/test/TestUtils.java +++ b/src/test/java/org/apache/commons/io/test/TestUtils.java @@ -224,11 +224,11 @@ public abstract class TestUtils { } } - public static File newFile(final File testDirectory, final String filename) throws IOException { - final File destination = new File(testDirectory, filename); + public static File newFile(final File testDirectory, final String fileName) throws IOException { + final File destination = new File(testDirectory, fileName); /* - assertTrue( filename + "Test output data file shouldn't previously exist", - !destination.exists() ); + assertTrue(fileName + "Test output data file shouldn't previously exist", + !destination.exists()); */ if (destination.exists()) { FileUtils.forceDelete(destination); diff --git a/src/test/resources/org/apache/commons/io/test-file-empty2.bin b/src/test/resources/org/apache/commons/io/test-file-empty2.bin new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/src/test/resources/org/apache/commons/io/test-file-empty2.bin |