This is an automated email from the ASF dual-hosted git repository. ggregory pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-io.git
commit 7f31d000ffa78aeb281f3c0b9db61ef4200d3547 Author: Gary Gregory <[email protected]> AuthorDate: Fri Nov 3 11:00:38 2023 -0400 Sort test members --- .../java/org/apache/commons/io/CopyUtilsTest.java | 128 ++++++++++----------- .../io/comparator/CompositeFileComparatorTest.java | 74 ++++++------ .../commons/io/filefilter/AndFileFilterTest.java | 28 ++--- .../commons/io/input/BOMInputStreamTest.java | 38 +++--- .../apache/commons/io/input/BoundedReaderTest.java | 98 ++++++++-------- .../io/input/UnixLineEndingInputStreamTest.java | 24 ++-- .../io/input/WindowsLineEndingInputStreamTest.java | 26 ++--- .../io/output/FileWriterWithEncodingTest.java | 120 +++++++++---------- .../io/serialization/MoreComplexObjectTest.java | 42 +++---- .../ValidatingObjectInputStreamTest.java | 28 ++--- 10 files changed, 303 insertions(+), 303 deletions(-) diff --git a/src/test/java/org/apache/commons/io/CopyUtilsTest.java b/src/test/java/org/apache/commons/io/CopyUtilsTest.java index 76b87541..aef6b996 100644 --- a/src/test/java/org/apache/commons/io/CopyUtilsTest.java +++ b/src/test/java/org/apache/commons/io/CopyUtilsTest.java @@ -78,6 +78,32 @@ public class CopyUtilsTest { assertArrayEquals(inData, baout.toByteArray(), "Content differs"); } + @Test + public void testCopy_byteArrayToWriterWithEncoding() throws Exception { + final String inDataStr = "data"; + final String charsetName = StandardCharsets.UTF_8.name(); + final StringWriter writer = new StringWriter(); + CopyUtils.copy(inDataStr.getBytes(charsetName), writer, charsetName); + assertEquals(inDataStr, writer.toString()); + } + + @SuppressWarnings("resource") // 'in' is deliberately not closed + @Test + public void testCopy_inputStreamToOutputStream() throws Exception { + InputStream in = new ByteArrayInputStream(inData); + in = new ThrowOnCloseInputStream(in); + + final ByteArrayOutputStream baout = new ByteArrayOutputStream(); + final OutputStream out = new ThrowOnFlushAndCloseOutputStream(baout, false, true); + + final int count = CopyUtils.copy(in, out); + + assertEquals(0, in.available(), "Not all bytes were read"); + assertEquals(inData.length, baout.size(), "Sizes differ"); + assertArrayEquals(inData, baout.toByteArray(), "Content differs"); + assertEquals(inData.length, count); + } + @SuppressWarnings("resource") // 'in' is deliberately not closed @Test public void testCopy_inputStreamToWriter() throws Exception { @@ -107,141 +133,115 @@ public class CopyUtilsTest { @SuppressWarnings("resource") // 'in' is deliberately not closed @Test - public void testCopy_readerToWriter() throws Exception { + public void testCopy_readerToOutputStream() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new ThrowOnCloseInputStream(in); final Reader reader = new java.io.InputStreamReader(in, StandardCharsets.US_ASCII); - final ByteArrayOutputStream baout = new ByteArrayOutputStream(); - final OutputStream out = new ThrowOnFlushAndCloseOutputStream(baout, false, true); - final Writer writer = new java.io.OutputStreamWriter(out, StandardCharsets.US_ASCII); - - final int count = CopyUtils.copy(reader, writer); - writer.flush(); - assertEquals(inData.length, count, "The number of characters returned by copy is wrong"); - assertEquals(inData.length, baout.size(), "Sizes differ"); - assertArrayEquals(inData, baout.toByteArray(), "Content differs"); - } - - @Test - public void testCopy_stringToOutputStream() throws Exception { - final String str = new String(inData, StandardCharsets.US_ASCII); - final ByteArrayOutputStream baout = new ByteArrayOutputStream(); final OutputStream out = new ThrowOnFlushAndCloseOutputStream(baout, false, true); - CopyUtils.copy(str, out); + CopyUtils.copy(reader, out); //Note: this method *does* flush. It is equivalent to: // OutputStreamWriter _out = new OutputStreamWriter(fout); - // IOUtils.copy( str, _out, 4096 ); // copy( Reader, Writer, int ); + // IOUtils.copy( fin, _out, 4096 ); // copy( Reader, Writer, int ); // _out.flush(); // out = fout; - // note: we don't flush here; this IOUtils method does it for us + // Note: rely on the method to flush assertEquals(inData.length, baout.size(), "Sizes differ"); assertArrayEquals(inData, baout.toByteArray(), "Content differs"); } + @SuppressWarnings("resource") // 'in' is deliberately not closed @Test - public void testCopy_stringToOutputStreamString() throws Exception { - final String str = new String(inData, StandardCharsets.US_ASCII); + public void testCopy_readerToOutputStreamString() throws Exception { + InputStream in = new ByteArrayInputStream(inData); + in = new ThrowOnCloseInputStream(in); + final Reader reader = new java.io.InputStreamReader(in, StandardCharsets.US_ASCII); final ByteArrayOutputStream baout = new ByteArrayOutputStream(); final OutputStream out = new ThrowOnFlushAndCloseOutputStream(baout, false, true); - CopyUtils.copy(str, out, StandardCharsets.US_ASCII.name()); + CopyUtils.copy(reader, out, StandardCharsets.US_ASCII.name()); //Note: this method *does* flush. It is equivalent to: // OutputStreamWriter _out = new OutputStreamWriter(fout); - // IOUtils.copy( str, _out, 4096 ); // copy( Reader, Writer, int ); + // IOUtils.copy( fin, _out, 4096 ); // copy( Reader, Writer, int ); // _out.flush(); // out = fout; - // note: we don't flush here; this IOUtils method does it for us + // Note: rely on the method to flush assertEquals(inData.length, baout.size(), "Sizes differ"); assertArrayEquals(inData, baout.toByteArray(), "Content differs"); } + @SuppressWarnings("resource") // 'in' is deliberately not closed @Test - public void testCopy_stringToWriter() throws Exception { - final String str = new String(inData, StandardCharsets.US_ASCII); + public void testCopy_readerToWriter() throws Exception { + InputStream in = new ByteArrayInputStream(inData); + in = new ThrowOnCloseInputStream(in); + final Reader reader = new java.io.InputStreamReader(in, StandardCharsets.US_ASCII); final ByteArrayOutputStream baout = new ByteArrayOutputStream(); final OutputStream out = new ThrowOnFlushAndCloseOutputStream(baout, false, true); final Writer writer = new java.io.OutputStreamWriter(out, StandardCharsets.US_ASCII); - CopyUtils.copy(str, writer); + final int count = CopyUtils.copy(reader, writer); writer.flush(); - + assertEquals(inData.length, count, "The number of characters returned by copy is wrong"); assertEquals(inData.length, baout.size(), "Sizes differ"); assertArrayEquals(inData, baout.toByteArray(), "Content differs"); } @Test - public void testCopy_byteArrayToWriterWithEncoding() throws Exception { - final String inDataStr = "data"; - final String charsetName = StandardCharsets.UTF_8.name(); - final StringWriter writer = new StringWriter(); - CopyUtils.copy(inDataStr.getBytes(charsetName), writer, charsetName); - assertEquals(inDataStr, writer.toString()); - } - - @SuppressWarnings("resource") // 'in' is deliberately not closed - @Test - public void testCopy_inputStreamToOutputStream() throws Exception { - InputStream in = new ByteArrayInputStream(inData); - in = new ThrowOnCloseInputStream(in); + public void testCopy_stringToOutputStream() throws Exception { + final String str = new String(inData, StandardCharsets.US_ASCII); final ByteArrayOutputStream baout = new ByteArrayOutputStream(); final OutputStream out = new ThrowOnFlushAndCloseOutputStream(baout, false, true); - final int count = CopyUtils.copy(in, out); + CopyUtils.copy(str, out); + //Note: this method *does* flush. It is equivalent to: + // OutputStreamWriter _out = new OutputStreamWriter(fout); + // IOUtils.copy( str, _out, 4096 ); // copy( Reader, Writer, int ); + // _out.flush(); + // out = fout; + // note: we don't flush here; this IOUtils method does it for us - assertEquals(0, in.available(), "Not all bytes were read"); assertEquals(inData.length, baout.size(), "Sizes differ"); assertArrayEquals(inData, baout.toByteArray(), "Content differs"); - assertEquals(inData.length, count); } - @SuppressWarnings("resource") // 'in' is deliberately not closed @Test - public void testCopy_readerToOutputStream() throws Exception { - InputStream in = new ByteArrayInputStream(inData); - in = new ThrowOnCloseInputStream(in); - final Reader reader = new java.io.InputStreamReader(in, StandardCharsets.US_ASCII); + public void testCopy_stringToOutputStreamString() throws Exception { + final String str = new String(inData, StandardCharsets.US_ASCII); final ByteArrayOutputStream baout = new ByteArrayOutputStream(); final OutputStream out = new ThrowOnFlushAndCloseOutputStream(baout, false, true); - CopyUtils.copy(reader, out); + CopyUtils.copy(str, out, StandardCharsets.US_ASCII.name()); //Note: this method *does* flush. It is equivalent to: // OutputStreamWriter _out = new OutputStreamWriter(fout); - // IOUtils.copy( fin, _out, 4096 ); // copy( Reader, Writer, int ); + // IOUtils.copy( str, _out, 4096 ); // copy( Reader, Writer, int ); // _out.flush(); // out = fout; + // note: we don't flush here; this IOUtils method does it for us - // Note: rely on the method to flush assertEquals(inData.length, baout.size(), "Sizes differ"); assertArrayEquals(inData, baout.toByteArray(), "Content differs"); } - @SuppressWarnings("resource") // 'in' is deliberately not closed @Test - public void testCopy_readerToOutputStreamString() throws Exception { - InputStream in = new ByteArrayInputStream(inData); - in = new ThrowOnCloseInputStream(in); - final Reader reader = new java.io.InputStreamReader(in, StandardCharsets.US_ASCII); + public void testCopy_stringToWriter() throws Exception { + final String str = new String(inData, StandardCharsets.US_ASCII); final ByteArrayOutputStream baout = new ByteArrayOutputStream(); final OutputStream out = new ThrowOnFlushAndCloseOutputStream(baout, false, true); + final Writer writer = new java.io.OutputStreamWriter(out, StandardCharsets.US_ASCII); - CopyUtils.copy(reader, out, StandardCharsets.US_ASCII.name()); - //Note: this method *does* flush. It is equivalent to: - // OutputStreamWriter _out = new OutputStreamWriter(fout); - // IOUtils.copy( fin, _out, 4096 ); // copy( Reader, Writer, int ); - // _out.flush(); - // out = fout; + CopyUtils.copy(str, writer); + writer.flush(); - // Note: rely on the method to flush assertEquals(inData.length, baout.size(), "Sizes differ"); assertArrayEquals(inData, baout.toByteArray(), "Content differs"); } diff --git a/src/test/java/org/apache/commons/io/comparator/CompositeFileComparatorTest.java b/src/test/java/org/apache/commons/io/comparator/CompositeFileComparatorTest.java index 50f2a2d3..63613b66 100644 --- a/src/test/java/org/apache/commons/io/comparator/CompositeFileComparatorTest.java +++ b/src/test/java/org/apache/commons/io/comparator/CompositeFileComparatorTest.java @@ -36,43 +36,6 @@ import org.junit.jupiter.api.Test; */ public class CompositeFileComparatorTest extends ComparatorAbstractTest { - /** - * Test Constructor with null array - */ - @Test - public void testConstructorArray_Null() { - final Comparator<File> c = new CompositeFileComparator((Comparator<File>[]) null); - assertEquals(0, c.compare(lessFile, moreFile), "less,more"); - assertEquals(0, c.compare(moreFile, lessFile), "more,less"); - assertEquals("CompositeFileComparator{}", c.toString(), "toString"); - } - - /** - * Test Constructor with null Iterable - */ - @Test - public void testConstructorIterable_Null() { - final Comparator<File> c = new CompositeFileComparator((Iterable<Comparator<File>>) null); - assertEquals(0, c.compare(lessFile, moreFile), "less,more"); - assertEquals(0, c.compare(moreFile, lessFile), "more,less"); - assertEquals("CompositeFileComparator{}", c.toString(), "toString"); - } - - /** - * Test Constructor with null Iterable - */ - @Test - public void testConstructorIterable_order() { - final List<Comparator<File>> list = new ArrayList<>(); - list.add(SizeFileComparator.SIZE_COMPARATOR); - list.add(ExtensionFileComparator.EXTENSION_COMPARATOR); - final Comparator<File> c = new CompositeFileComparator(list); - - assertEquals(0, c.compare(equalFile1, equalFile2), "equal"); - assertTrue(c.compare(lessFile, moreFile) < 0, "less"); - assertTrue(c.compare(moreFile, lessFile) > 0, "more"); - } - @BeforeEach public void setUp() throws Exception { comparator = new CompositeFileComparator(SizeFileComparator.SIZE_COMPARATOR, ExtensionFileComparator.EXTENSION_COMPARATOR); @@ -115,4 +78,41 @@ public class CompositeFileComparatorTest extends ComparatorAbstractTest { TestUtils.generateTestData(output, 48); } } + + /** + * Test Constructor with null array + */ + @Test + public void testConstructorArray_Null() { + final Comparator<File> c = new CompositeFileComparator((Comparator<File>[]) null); + assertEquals(0, c.compare(lessFile, moreFile), "less,more"); + assertEquals(0, c.compare(moreFile, lessFile), "more,less"); + assertEquals("CompositeFileComparator{}", c.toString(), "toString"); + } + + /** + * Test Constructor with null Iterable + */ + @Test + public void testConstructorIterable_Null() { + final Comparator<File> c = new CompositeFileComparator((Iterable<Comparator<File>>) null); + assertEquals(0, c.compare(lessFile, moreFile), "less,more"); + assertEquals(0, c.compare(moreFile, lessFile), "more,less"); + assertEquals("CompositeFileComparator{}", c.toString(), "toString"); + } + + /** + * Test Constructor with null Iterable + */ + @Test + public void testConstructorIterable_order() { + final List<Comparator<File>> list = new ArrayList<>(); + list.add(SizeFileComparator.SIZE_COMPARATOR); + list.add(ExtensionFileComparator.EXTENSION_COMPARATOR); + final Comparator<File> c = new CompositeFileComparator(list); + + assertEquals(0, c.compare(equalFile1, equalFile2), "equal"); + assertTrue(c.compare(lessFile, moreFile) < 0, "less"); + assertTrue(c.compare(moreFile, lessFile) > 0, "more"); + } } diff --git a/src/test/java/org/apache/commons/io/filefilter/AndFileFilterTest.java b/src/test/java/org/apache/commons/io/filefilter/AndFileFilterTest.java index aabc5ea3..9678893d 100644 --- a/src/test/java/org/apache/commons/io/filefilter/AndFileFilterTest.java +++ b/src/test/java/org/apache/commons/io/filefilter/AndFileFilterTest.java @@ -91,20 +91,6 @@ public class AndFileFilterTest extends AbstractConditionalFileFilterTest { return WORKING_PATH_NAME_PROPERTY_KEY; } - @Test - public void testSetTestFiltersClearsOld() { - // test that new filters correctly clear old filters - final List<IOFileFilter> simpleEmptyFileFilter = Collections.singletonList(EmptyFileFilter.EMPTY); - final AndFileFilter andFileFilter = new AndFileFilter(simpleEmptyFileFilter); - // make sure the filters at this point are the same - assertEquals(simpleEmptyFileFilter, andFileFilter.getFileFilters()); - - final List<IOFileFilter> simpleNonEmptyFilter = Collections.singletonList(EmptyFileFilter.NOT_EMPTY); - // when calling the setter the filters should reference the new filters - andFileFilter.setFileFilters(simpleNonEmptyFilter); - assertEquals(simpleNonEmptyFilter, andFileFilter.getFileFilters()); - } - @BeforeEach public void setUpTestFilters() { // filters @@ -310,4 +296,18 @@ public class AndFileFilterTest extends AbstractConditionalFileFilterTest { testFilenameResults.add(9, Boolean.FALSE); } } + + @Test + public void testSetTestFiltersClearsOld() { + // test that new filters correctly clear old filters + final List<IOFileFilter> simpleEmptyFileFilter = Collections.singletonList(EmptyFileFilter.EMPTY); + final AndFileFilter andFileFilter = new AndFileFilter(simpleEmptyFileFilter); + // make sure the filters at this point are the same + assertEquals(simpleEmptyFileFilter, andFileFilter.getFileFilters()); + + final List<IOFileFilter> simpleNonEmptyFilter = Collections.singletonList(EmptyFileFilter.NOT_EMPTY); + // when calling the setter the filters should reference the new filters + andFileFilter.setFileFilters(simpleNonEmptyFilter); + assertEquals(simpleNonEmptyFilter, andFileFilter.getFileFilters()); + } } 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 6d524f15..6f5e8e13 100644 --- a/src/test/java/org/apache/commons/io/input/BOMInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/input/BOMInputStreamTest.java @@ -205,24 +205,6 @@ public class BOMInputStreamTest { } while (bytes > 0); } - @Test - public void testSkipReturnValueWithBom() throws IOException { - final byte[] data = { (byte) 0x31, (byte) 0x32, (byte) 0x33 }; - try (BOMInputStream is1 = BOMInputStream.builder().setInputStream(createUtf8Input(data, true)).get()) { - assertEquals(2, is1.skip(2)); - assertEquals((byte) 0x33, is1.read()); - } - } - - @Test - public void testSkipReturnValueWithoutBom() throws IOException { - final byte[] data = { (byte) 0x31, (byte) 0x32, (byte) 0x33 }; - try (BOMInputStream is2 = BOMInputStream.builder().setInputStream(createUtf8Input(data, false)).get()) { - assertEquals(2, is2.skip(2)); // IO-428 - assertEquals((byte) 0x33, is2.read()); - } - } - @Test public void testAvailableWithBOM() throws Exception { final byte[] data = { 'A', 'B', 'C', 'D' }; @@ -685,7 +667,6 @@ public class BOMInputStreamTest { parseXml(createUtf8Input(data, true)); } - @Test public void testReadXmlWithoutBOMUtf32Be() throws Exception { assumeTrue(jvmAndSaxBothSupportCharset("UTF_32BE"), "JVM and SAX need to support UTF_32BE for this"); @@ -706,6 +687,25 @@ public class BOMInputStreamTest { parseXml(createUtf32BeDataStream(data, false)); } + + @Test + public void testSkipReturnValueWithBom() throws IOException { + final byte[] data = { (byte) 0x31, (byte) 0x32, (byte) 0x33 }; + try (BOMInputStream is1 = BOMInputStream.builder().setInputStream(createUtf8Input(data, true)).get()) { + assertEquals(2, is1.skip(2)); + assertEquals((byte) 0x33, is1.read()); + } + } + + @Test + public void testSkipReturnValueWithoutBom() throws IOException { + final byte[] data = { (byte) 0x31, (byte) 0x32, (byte) 0x33 }; + try (BOMInputStream is2 = BOMInputStream.builder().setInputStream(createUtf8Input(data, false)).get()) { + assertEquals(2, is2.skip(2)); // IO-428 + assertEquals((byte) 0x33, is2.read()); + } + } + @Test public void testSkipWithBOM() throws Exception { final byte[] data = { 'A', 'B', 'C', 'D' }; diff --git a/src/test/java/org/apache/commons/io/input/BoundedReaderTest.java b/src/test/java/org/apache/commons/io/input/BoundedReaderTest.java index 13ae5af9..71d1aad3 100644 --- a/src/test/java/org/apache/commons/io/input/BoundedReaderTest.java +++ b/src/test/java/org/apache/commons/io/input/BoundedReaderTest.java @@ -71,6 +71,44 @@ public class BoundedReaderTest { assertTrue(closed.get()); } + private void testLineNumberReader(final Reader source) throws IOException { + try (LineNumberReader reader = new LineNumberReader(new BoundedReader(source, 10_000_000))) { + while (reader.readLine() != null) { + // noop + } + } + } + + public void testLineNumberReaderAndFileReaderLastLine(final String data) throws IOException { + try (TempFile path = TempFile.create(getClass().getSimpleName(), ".txt")) { + final File file = path.toFile(); + FileUtils.write(file, data, StandardCharsets.ISO_8859_1); + try (Reader source = Files.newBufferedReader(file.toPath())) { + testLineNumberReader(source); + } + } + } + + @Test + public void testLineNumberReaderAndFileReaderLastLineEolNo() { + assertTimeout(TIMEOUT, () -> testLineNumberReaderAndFileReaderLastLine(STRING_END_NO_EOL)); + } + + @Test + public void testLineNumberReaderAndFileReaderLastLineEolYes() { + assertTimeout(TIMEOUT, () -> testLineNumberReaderAndFileReaderLastLine(STRING_END_EOL)); + } + + @Test + public void testLineNumberReaderAndStringReaderLastLineEolNo() { + assertTimeout(TIMEOUT, () -> testLineNumberReader(new StringReader(STRING_END_NO_EOL))); + } + + @Test + public void testLineNumberReaderAndStringReaderLastLineEolYes() { + assertTimeout(TIMEOUT, () -> testLineNumberReader(new StringReader(STRING_END_EOL))); + } + @Test public void testMarkReset() throws IOException { try (BoundedReader mr = new BoundedReader(sr, 3)) { @@ -138,6 +176,17 @@ public class BoundedReaderTest { } } + @Test + public void testReadBytesEOF() { + assertTimeout(TIMEOUT, () -> { + final BoundedReader mr = new BoundedReader(sr, 3); + try (BufferedReader br = new BufferedReader(mr)) { + br.readLine(); + br.readLine(); + } + }); + } + @Test public void testReadMulti() throws IOException { try (BoundedReader mr = new BoundedReader(sr, 3)) { @@ -193,53 +242,4 @@ public class BoundedReaderTest { assertEquals(-1, mr.read()); } } - - private void testLineNumberReader(final Reader source) throws IOException { - try (LineNumberReader reader = new LineNumberReader(new BoundedReader(source, 10_000_000))) { - while (reader.readLine() != null) { - // noop - } - } - } - - public void testLineNumberReaderAndFileReaderLastLine(final String data) throws IOException { - try (TempFile path = TempFile.create(getClass().getSimpleName(), ".txt")) { - final File file = path.toFile(); - FileUtils.write(file, data, StandardCharsets.ISO_8859_1); - try (Reader source = Files.newBufferedReader(file.toPath())) { - testLineNumberReader(source); - } - } - } - - @Test - public void testLineNumberReaderAndFileReaderLastLineEolNo() { - assertTimeout(TIMEOUT, () -> testLineNumberReaderAndFileReaderLastLine(STRING_END_NO_EOL)); - } - - @Test - public void testLineNumberReaderAndFileReaderLastLineEolYes() { - assertTimeout(TIMEOUT, () -> testLineNumberReaderAndFileReaderLastLine(STRING_END_EOL)); - } - - @Test - public void testLineNumberReaderAndStringReaderLastLineEolNo() { - assertTimeout(TIMEOUT, () -> testLineNumberReader(new StringReader(STRING_END_NO_EOL))); - } - - @Test - public void testLineNumberReaderAndStringReaderLastLineEolYes() { - assertTimeout(TIMEOUT, () -> testLineNumberReader(new StringReader(STRING_END_EOL))); - } - - @Test - public void testReadBytesEOF() { - assertTimeout(TIMEOUT, () -> { - final BoundedReader mr = new BoundedReader(sr, 3); - try (BufferedReader br = new BufferedReader(mr)) { - br.readLine(); - br.readLine(); - } - }); - } } diff --git a/src/test/java/org/apache/commons/io/input/UnixLineEndingInputStreamTest.java b/src/test/java/org/apache/commons/io/input/UnixLineEndingInputStreamTest.java index 9c1ac1ea..a147c7a9 100644 --- a/src/test/java/org/apache/commons/io/input/UnixLineEndingInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/input/UnixLineEndingInputStreamTest.java @@ -26,6 +26,18 @@ import org.junit.jupiter.api.Test; public class UnixLineEndingInputStreamTest { + private String roundtrip(final String msg) throws IOException { + return roundtrip(msg, true); + } + + private String roundtrip(final String msg, final boolean ensure) throws IOException { + try (final ByteArrayInputStream baos = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8)); + final UnixLineEndingInputStream lf = new UnixLineEndingInputStream(baos, ensure)) { + final byte[] buf = new byte[100]; + return new String(buf, 0, lf.read(buf), StandardCharsets.UTF_8); + } + } + @Test public void testCrAtEnd() throws Exception { assertEquals("a\n", roundtrip("a\r")); @@ -57,18 +69,6 @@ public class UnixLineEndingInputStreamTest { assertEquals("a", roundtrip("a", false)); } - private String roundtrip(final String msg) throws IOException { - return roundtrip(msg, true); - } - - private String roundtrip(final String msg, final boolean ensure) throws IOException { - try (final ByteArrayInputStream baos = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8)); - final UnixLineEndingInputStream lf = new UnixLineEndingInputStream(baos, ensure)) { - final byte[] buf = new byte[100]; - return new String(buf, 0, lf.read(buf), StandardCharsets.UTF_8); - } - } - @Test public void testSimpleString() throws Exception { assertEquals("abc\n", roundtrip("abc")); diff --git a/src/test/java/org/apache/commons/io/input/WindowsLineEndingInputStreamTest.java b/src/test/java/org/apache/commons/io/input/WindowsLineEndingInputStreamTest.java index e82edb9c..4c8dd150 100644 --- a/src/test/java/org/apache/commons/io/input/WindowsLineEndingInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/input/WindowsLineEndingInputStreamTest.java @@ -24,6 +24,19 @@ import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; public class WindowsLineEndingInputStreamTest { + private String roundtrip(final String msg) throws IOException { + return roundtrip(msg, true); + } + + private String roundtrip(final String msg, final boolean ensure) throws IOException { + try (WindowsLineEndingInputStream lf = new WindowsLineEndingInputStream( + CharSequenceInputStream.builder().setCharSequence(msg).setCharset(StandardCharsets.UTF_8).get(), ensure)) { + final byte[] buf = new byte[100]; + final int read = lf.read(buf); + return new String(buf, 0, read, StandardCharsets.UTF_8); + } + } + @Test public void testInTheMiddleOfTheLine() throws Exception { assertEquals("a\r\nbc\r\n", roundtrip("a\r\nbc")); @@ -51,19 +64,6 @@ public class WindowsLineEndingInputStreamTest { assertEquals("a", roundtrip("a", false)); } - private String roundtrip(final String msg) throws IOException { - return roundtrip(msg, true); - } - - private String roundtrip(final String msg, final boolean ensure) throws IOException { - try (WindowsLineEndingInputStream lf = new WindowsLineEndingInputStream( - CharSequenceInputStream.builder().setCharSequence(msg).setCharset(StandardCharsets.UTF_8).get(), ensure)) { - final byte[] buf = new byte[100]; - final int read = lf.read(buf); - return new String(buf, 0, read, StandardCharsets.UTF_8); - } - } - @Test public void testSimpleString() throws Exception { assertEquals("abc\r\n", roundtrip("abc")); diff --git a/src/test/java/org/apache/commons/io/output/FileWriterWithEncodingTest.java b/src/test/java/org/apache/commons/io/output/FileWriterWithEncodingTest.java index 22a26a82..12f6222e 100644 --- a/src/test/java/org/apache/commons/io/output/FileWriterWithEncodingTest.java +++ b/src/test/java/org/apache/commons/io/output/FileWriterWithEncodingTest.java @@ -51,6 +51,32 @@ public class FileWriterWithEncodingTest { private String textContent; private final char[] anotherTestContent = {'f', 'z', 'x'}; + @BeforeEach + public void setUp() throws Exception { + final File encodingFinder = new File(temporaryFolder, "finder.txt"); + try (OutputStreamWriter out = new OutputStreamWriter(Files.newOutputStream(encodingFinder.toPath()))) { + defaultEncoding = out.getEncoding(); + } + file1 = new File(temporaryFolder, "testfile1.txt"); + file2 = new File(temporaryFolder, "testfile2.txt"); + final char[] arr = new char[1024]; + final char[] chars = "ABCDEFGHIJKLMNOPQabcdefgihklmnopq".toCharArray(); + for (int i = 0; i < arr.length; i++) { + arr[i] = chars[i % chars.length]; + } + textContent = new String(arr); + } + + private void successfulRun(final FileWriterWithEncoding fw21) throws Exception { + try (FileWriter fw1 = new FileWriter(file1); // default encoding + FileWriterWithEncoding fw2 = fw21) { + writeTestPayload(fw1, fw2); + checkFile(file1, file2); + } + assertTrue(file1.exists()); + assertTrue(file2.exists()); + } + @Test public void testConstructor_File_directory() { assertThrows(IOException.class, () -> { @@ -144,6 +170,40 @@ public class FileWriterWithEncodingTest { assertEquals(10, file1.length()); } + @Test + public void testDifferentEncoding() throws Exception { + if (Charset.isSupported(StandardCharsets.UTF_16BE.name())) { + try (FileWriter fw1 = new FileWriter(file1); // default encoding + FileWriterWithEncoding fw2 = new FileWriterWithEncoding(file2, defaultEncoding)) { + writeTestPayload(fw1, fw2); + try { + checkFile(file1, file2); + fail(); + } catch (final AssertionError ex) { + // success + } + + } + assertTrue(file1.exists()); + assertTrue(file2.exists()); + } + if (Charset.isSupported(StandardCharsets.UTF_16LE.name())) { + try (FileWriter fw1 = new FileWriter(file1); // default encoding + FileWriterWithEncoding fw2 = new FileWriterWithEncoding(file2, defaultEncoding)) { + writeTestPayload(fw1, fw2); + try { + checkFile(file1, file2); + fail(); + } catch (final AssertionError ex) { + // success + } + + } + assertTrue(file1.exists()); + assertTrue(file2.exists()); + } + } + @Test public void testSameEncoding_Charset_constructor() throws Exception { try (FileWriterWithEncoding writer = new FileWriterWithEncoding(file2, Charset.defaultCharset())) { @@ -245,66 +305,6 @@ public class FileWriterWithEncodingTest { // @formatter:on } - @BeforeEach - public void setUp() throws Exception { - final File encodingFinder = new File(temporaryFolder, "finder.txt"); - try (OutputStreamWriter out = new OutputStreamWriter(Files.newOutputStream(encodingFinder.toPath()))) { - defaultEncoding = out.getEncoding(); - } - file1 = new File(temporaryFolder, "testfile1.txt"); - file2 = new File(temporaryFolder, "testfile2.txt"); - final char[] arr = new char[1024]; - final char[] chars = "ABCDEFGHIJKLMNOPQabcdefgihklmnopq".toCharArray(); - for (int i = 0; i < arr.length; i++) { - arr[i] = chars[i % chars.length]; - } - textContent = new String(arr); - } - - private void successfulRun(final FileWriterWithEncoding fw21) throws Exception { - try (FileWriter fw1 = new FileWriter(file1); // default encoding - FileWriterWithEncoding fw2 = fw21) { - writeTestPayload(fw1, fw2); - checkFile(file1, file2); - } - assertTrue(file1.exists()); - assertTrue(file2.exists()); - } - - @Test - public void testDifferentEncoding() throws Exception { - if (Charset.isSupported(StandardCharsets.UTF_16BE.name())) { - try (FileWriter fw1 = new FileWriter(file1); // default encoding - FileWriterWithEncoding fw2 = new FileWriterWithEncoding(file2, defaultEncoding)) { - writeTestPayload(fw1, fw2); - try { - checkFile(file1, file2); - fail(); - } catch (final AssertionError ex) { - // success - } - - } - assertTrue(file1.exists()); - assertTrue(file2.exists()); - } - if (Charset.isSupported(StandardCharsets.UTF_16LE.name())) { - try (FileWriter fw1 = new FileWriter(file1); // default encoding - FileWriterWithEncoding fw2 = new FileWriterWithEncoding(file2, defaultEncoding)) { - writeTestPayload(fw1, fw2); - try { - checkFile(file1, file2); - fail(); - } catch (final AssertionError ex) { - // success - } - - } - assertTrue(file1.exists()); - assertTrue(file2.exists()); - } - } - private void writeTestPayload(final FileWriter fw1, final FileWriterWithEncoding fw2) throws IOException { assertTrue(file1.exists()); assertTrue(file2.exists()); diff --git a/src/test/java/org/apache/commons/io/serialization/MoreComplexObjectTest.java b/src/test/java/org/apache/commons/io/serialization/MoreComplexObjectTest.java index 053f84dc..892b41fb 100644 --- a/src/test/java/org/apache/commons/io/serialization/MoreComplexObjectTest.java +++ b/src/test/java/org/apache/commons/io/serialization/MoreComplexObjectTest.java @@ -56,6 +56,27 @@ public class MoreComplexObjectTest extends AbstractCloseableListTest { inputStream = closeAfterEachTest(new ByteArrayInputStream(bos.toByteArray())); } + /** Here we accept everything but reject specific classes, using a pure + * blacklist mode. + * + * That's not as safe as it's hard to get an exhaustive blacklist, but + * might be ok in controlled environments. + */ + @Test + public void testUseBlacklist() throws IOException, ClassNotFoundException { + final String [] blacklist = { + "org.apache.commons.collections.functors.InvokerTransformer", + "org.codehaus.groovy.runtime.ConvertedClosure", + "org.codehaus.groovy.runtime.MethodClosure", + "org.springframework.beans.factory.ObjectFactory" + }; + assertSerialization(closeAfterEachTest( + new ValidatingObjectInputStream(inputStream) + .accept("*") + .reject(blacklist) + )); + } + /** Trusting java.* is probably reasonable and avoids having to be too * detailed in the accepts. */ @@ -80,25 +101,4 @@ public class MoreComplexObjectTest extends AbstractCloseableListTest { .accept("java.lang.*", "[Ljava.lang.*") )); } - - /** Here we accept everything but reject specific classes, using a pure - * blacklist mode. - * - * That's not as safe as it's hard to get an exhaustive blacklist, but - * might be ok in controlled environments. - */ - @Test - public void testUseBlacklist() throws IOException, ClassNotFoundException { - final String [] blacklist = { - "org.apache.commons.collections.functors.InvokerTransformer", - "org.codehaus.groovy.runtime.ConvertedClosure", - "org.codehaus.groovy.runtime.MethodClosure", - "org.springframework.beans.factory.ObjectFactory" - }; - assertSerialization(closeAfterEachTest( - new ValidatingObjectInputStream(inputStream) - .accept("*") - .reject(blacklist) - )); - } } \ No newline at end of file diff --git a/src/test/java/org/apache/commons/io/serialization/ValidatingObjectInputStreamTest.java b/src/test/java/org/apache/commons/io/serialization/ValidatingObjectInputStreamTest.java index 420e0b43..b13be8d5 100644 --- a/src/test/java/org/apache/commons/io/serialization/ValidatingObjectInputStreamTest.java +++ b/src/test/java/org/apache/commons/io/serialization/ValidatingObjectInputStreamTest.java @@ -45,6 +45,20 @@ public class ValidatingObjectInputStreamTest extends AbstractCloseableListTest { private InputStream testStream; + private void assertSerialization(final ObjectInputStream ois) throws ClassNotFoundException, IOException { + final MockSerializedClass result = (MockSerializedClass) ois.readObject(); + assertEquals(testObject, result); + } + + @BeforeEach + public void setupMockSerializedClass() throws IOException { + testObject = new MockSerializedClass(UUID.randomUUID().toString()); + final ByteArrayOutputStream bos = closeAfterEachTest(new ByteArrayOutputStream()); + final ObjectOutputStream oos = closeAfterEachTest(new ObjectOutputStream(bos)); + oos.writeObject(testObject); + testStream = closeAfterEachTest(new ByteArrayInputStream(bos.toByteArray())); + } + @Test public void testAcceptCustomMatcher() throws Exception { assertSerialization( @@ -69,11 +83,6 @@ public class ValidatingObjectInputStreamTest extends AbstractCloseableListTest { ); } - private void assertSerialization(final ObjectInputStream ois) throws ClassNotFoundException, IOException { - final MockSerializedClass result = (MockSerializedClass) ois.readObject(); - assertEquals(testObject, result); - } - @Test public void testCustomInvalidMethod() { class CustomVOIS extends ValidatingObjectInputStream { @@ -219,13 +228,4 @@ public class ValidatingObjectInputStreamTest extends AbstractCloseableListTest { .reject("org.*") )); } - - @BeforeEach - public void setupMockSerializedClass() throws IOException { - testObject = new MockSerializedClass(UUID.randomUUID().toString()); - final ByteArrayOutputStream bos = closeAfterEachTest(new ByteArrayOutputStream()); - final ObjectOutputStream oos = closeAfterEachTest(new ObjectOutputStream(bos)); - oos.writeObject(testObject); - testStream = closeAfterEachTest(new ByteArrayInputStream(bos.toByteArray())); - } } \ No newline at end of file
