You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2023/11/03 12:59:35 UTC
(commons-compress) 03/03: Sort test members
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-compress.git
commit f85f0098be13582a6dc6271d1efced7c555baa51
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Fri Nov 3 08:59:23 2023 -0400
Sort test members
---
.../apache/commons/compress/ArchiveUtilsTest.java | 60 +-
.../org/apache/commons/compress/OsgiITest.java | 10 +-
.../archivers/ArchiveStreamFactoryTest.java | 116 ++--
.../commons/compress/archivers/SevenZTestCase.java | 86 +--
.../commons/compress/archivers/ZipTestCase.java | 232 ++++----
.../archivers/ar/ArArchiveInputStreamTest.java | 54 +-
.../archivers/arj/ArjArchiveInputStreamTest.java | 46 +-
.../archivers/cpio/CpioArchiveInputStreamTest.java | 42 +-
.../compress/archivers/cpio/CpioUtilTest.java | 30 +-
.../archivers/dump/DumpArchiveInputStreamTest.java | 46 +-
.../compress/archivers/examples/ExpanderTest.java | 112 ++--
.../archivers/examples/SevenZArchiverTest.java | 30 +-
.../compress/archivers/sevenz/SevenZFileTest.java | 624 ++++++++++-----------
.../commons/compress/archivers/tar/BigFilesIT.java | 32 +-
.../compress/archivers/tar/SparseFilesTest.java | 20 +-
.../archivers/tar/TarArchiveEntryTest.java | 260 ++++-----
.../archivers/tar/TarArchiveInputStreamTest.java | 306 +++++-----
.../compress/archivers/tar/TarFileTest.java | 226 ++++----
.../archivers/tar/TarMemoryFileSystemTest.java | 60 +-
.../compress/archivers/tar/TarUtilsTest.java | 288 +++++-----
.../archivers/zip/ExtraFieldUtilsTest.java | 24 +-
.../zip/ParallelScatterZipCreatorTest.java | 130 ++---
.../archivers/zip/StreamCompressorTest.java | 16 +-
.../compress/archivers/zip/UTF8ZipFilesTest.java | 26 +-
.../archivers/zip/X5455_ExtendedTimestampTest.java | 18 +-
.../compress/archivers/zip/Zip64SupportIT.java | 68 +--
.../archivers/zip/ZipArchiveEntryTest.java | 110 ++--
.../archivers/zip/ZipArchiveInputStreamTest.java | 158 +++---
.../zip/ZipFileIgnoringLocalFileHeaderTest.java | 16 +-
.../compress/archivers/zip/ZipFileTest.java | 292 +++++-----
.../archivers/zip/ZipMemoryFileSystemTest.java | 34 +-
.../archivers/zip/ZipSplitOutputStreamTest.java | 24 +-
.../commons/compress/compressors/GZipTestCase.java | 46 +-
.../commons/compress/compressors/LZMATestCase.java | 42 +-
.../compress/compressors/Pack200TestCase.java | 40 +-
.../brotli/BrotliCompressorInputStreamTest.java | 76 +--
.../Deflate64CompressorInputStreamTest.java | 24 +-
.../lz4/BlockLZ4CompressorOutputStreamTest.java | 92 +--
.../compress/compressors/lz4/FactoryTest.java | 20 +-
.../lz4/FramedLZ4CompressorInputStreamTest.java | 62 +-
.../lz77support/LZ77CompressorTest.java | 46 +-
.../FramedSnappyCompressorInputStreamTest.java | 104 ++--
.../compressors/snappy/SnappyRoundtripTest.java | 74 +--
.../xz/XZCompressorInputStreamTest.java | 20 +-
.../compressors/z/ZCompressorInputStreamTest.java | 12 +-
.../zstandard/ZstdCompressorInputStreamTest.java | 34 +-
.../compressors/zstandard/ZstdRoundtripTest.java | 40 +-
.../commons/compress/utils/BitInputStreamTest.java | 74 +--
.../apache/commons/compress/utils/IOUtilsTest.java | 18 +-
.../MultiReadOnlySeekableByteChannelTest.java | 148 ++---
.../commons/compress/utils/TimeUtilsTest.java | 42 +-
.../ZipSplitReadOnlySeekableByteChannelTest.java | 28 +-
52 files changed, 2319 insertions(+), 2319 deletions(-)
diff --git a/src/test/java/org/apache/commons/compress/ArchiveUtilsTest.java b/src/test/java/org/apache/commons/compress/ArchiveUtilsTest.java
index 2b1020ea..87154918 100644
--- a/src/test/java/org/apache/commons/compress/ArchiveUtilsTest.java
+++ b/src/test/java/org/apache/commons/compress/ArchiveUtilsTest.java
@@ -49,36 +49,6 @@ public class ArchiveUtilsTest extends AbstractTestCase {
assertEquals(inputString, ArchiveUtils.toAsciiString(ArchiveUtils.toAsciiBytes(inputString)));
}
- @Test
- public void testSanitizeLeavesShortStringsAlone() {
- final String input = "012345678901234567890123456789012345678901234567890123456789";
- assertEquals(input, ArchiveUtils.sanitize(input));
- }
-
- @Test
- public void testSanitizeRemovesUnprintableCharacters() {
- final String input = "\b12345678901234567890123456789012345678901234567890123456789";
- final String expected = "?12345678901234567890123456789012345678901234567890123456789";
- assertEquals(expected, ArchiveUtils.sanitize(input));
- }
-
- @Test
- public void testSanitizeShortensString() {
- // @formatter:off
- final String input = "012345678901234567890123456789012345678901234567890123456789"
- + "012345678901234567890123456789012345678901234567890123456789"
- + "012345678901234567890123456789012345678901234567890123456789"
- + "012345678901234567890123456789012345678901234567890123456789"
- + "012345678901234567890123456789012345678901234567890123456789";
- final String expected = "012345678901234567890123456789012345678901234567890123456789"
- + "012345678901234567890123456789012345678901234567890123456789"
- + "012345678901234567890123456789012345678901234567890123456789"
- + "012345678901234567890123456789012345678901234567890123456789"
- + "012345678901...";
- // @formatter:on
- assertEquals(expected, ArchiveUtils.sanitize(input));
- }
-
@Test
public void testAsciiConversions() {
asciiToByteAndBackOK("");
@@ -123,6 +93,36 @@ public class ArchiveUtilsTest extends AbstractTestCase {
assertFalse(ArchiveUtils.isEqualWithNull(byteArray, 0, (byte) 0, byteArray, (byte) 0, (byte) 80));
}
+ @Test
+ public void testSanitizeLeavesShortStringsAlone() {
+ final String input = "012345678901234567890123456789012345678901234567890123456789";
+ assertEquals(input, ArchiveUtils.sanitize(input));
+ }
+
+ @Test
+ public void testSanitizeRemovesUnprintableCharacters() {
+ final String input = "\b12345678901234567890123456789012345678901234567890123456789";
+ final String expected = "?12345678901234567890123456789012345678901234567890123456789";
+ assertEquals(expected, ArchiveUtils.sanitize(input));
+ }
+
+ @Test
+ public void testSanitizeShortensString() {
+ // @formatter:off
+ final String input = "012345678901234567890123456789012345678901234567890123456789"
+ + "012345678901234567890123456789012345678901234567890123456789"
+ + "012345678901234567890123456789012345678901234567890123456789"
+ + "012345678901234567890123456789012345678901234567890123456789"
+ + "012345678901234567890123456789012345678901234567890123456789";
+ final String expected = "012345678901234567890123456789012345678901234567890123456789"
+ + "012345678901234567890123456789012345678901234567890123456789"
+ + "012345678901234567890123456789012345678901234567890123456789"
+ + "012345678901234567890123456789012345678901234567890123456789"
+ + "012345678901...";
+ // @formatter:on
+ assertEquals(expected, ArchiveUtils.sanitize(input));
+ }
+
@Test
public void testToAsciiBytes() {
final byte[] byteArray = ArchiveUtils.toAsciiBytes("SOCKET");
diff --git a/src/test/java/org/apache/commons/compress/OsgiITest.java b/src/test/java/org/apache/commons/compress/OsgiITest.java
index 337b7a15..6935181f 100644
--- a/src/test/java/org/apache/commons/compress/OsgiITest.java
+++ b/src/test/java/org/apache/commons/compress/OsgiITest.java
@@ -45,11 +45,6 @@ public class OsgiITest {
@Inject
private BundleContext ctx;
- @Test
- public void testCanLoadBundle() {
- assertNotNull("Expected to find bundle " + EXPECTED_BUNDLE_NAME, loadBundle());
- }
-
@Configuration
public Option[] config() {
return new Option[] {
@@ -78,6 +73,11 @@ public class OsgiITest {
return null;
}
+ @Test
+ public void testCanLoadBundle() {
+ assertNotNull("Expected to find bundle " + EXPECTED_BUNDLE_NAME, loadBundle());
+ }
+
@Test
public void testProperlyDetectsRunningInsideOsgiEnv() throws Exception {
final Class<?> osgiUtils = loadBundle().loadClass("org.apache.commons.compress.utils.OsgiUtils");
diff --git a/src/test/java/org/apache/commons/compress/archivers/ArchiveStreamFactoryTest.java b/src/test/java/org/apache/commons/compress/archivers/ArchiveStreamFactoryTest.java
index 79da242c..3b106b2b 100644
--- a/src/test/java/org/apache/commons/compress/archivers/ArchiveStreamFactoryTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/ArchiveStreamFactoryTest.java
@@ -197,56 +197,17 @@ public class ArchiveStreamFactoryTest extends AbstractTestCase {
}
}
}
- /**
- * see https://issues.apache.org/jira/browse/COMPRESS-191
- */
- @Test
- public void testAiffFilesAreNoTARs() throws Exception {
- try (final InputStream fis = newInputStream("testAIFF.aif");
- final InputStream is = new BufferedInputStream(fis)) {
- final ArchiveException ae = assertThrows(ArchiveException.class, () -> ArchiveStreamFactory.DEFAULT.createArchiveInputStream(is),
- "created an input stream for a non-archive");
- assertTrue(ae.getMessage().startsWith("No Archiver found"));
- }
- }
-
- @Test
- public void testCantRead7zFromStream() throws Exception {
- assertThrows(StreamingNotSupportedException.class,
- () -> ArchiveStreamFactory.DEFAULT.createArchiveInputStream(ArchiveStreamFactory.SEVEN_Z, new ByteArrayInputStream(ByteUtils.EMPTY_BYTE_ARRAY)));
- }
- @Test
- public void testCantWrite7zToStream() throws Exception {
- assertThrows(StreamingNotSupportedException.class,
- () -> ArchiveStreamFactory.DEFAULT.createArchiveOutputStream(ArchiveStreamFactory.SEVEN_Z, new ByteArrayOutputStream()));
- }
-
private String detect(final String resource) throws IOException, ArchiveException {
try (InputStream in = new BufferedInputStream(newInputStream(resource))) {
return ArchiveStreamFactory.detect(in);
}
}
- /**
- * Test case for
- * <a href="https://issues.apache.org/jira/browse/COMPRESS-267"
- * >COMPRESS-267</a>.
- */
- @Test
- public void testDetectsAndThrowsFor7z() throws Exception {
- try (final InputStream fis = newInputStream("bla.7z");
- final InputStream bis = new BufferedInputStream(fis)) {
- final StreamingNotSupportedException ex = assertThrows(StreamingNotSupportedException.class, () -> ArchiveStreamFactory.DEFAULT.createArchiveInputStream(bis),
- "Expected a StreamingNotSupportedException");
- assertEquals(ArchiveStreamFactory.SEVEN_Z, ex.getFormat());
- }
- }
@SuppressWarnings("resource")
private <T extends ArchiveInputStream<? extends E>, E extends ArchiveEntry> T getInputStream(final String resource, final ArchiveStreamFactory factory)
throws IOException, ArchiveException {
return factory.createArchiveInputStream(new BufferedInputStream(newInputStream(resource)));
}
-
@SuppressWarnings("resource")
private <T extends ArchiveInputStream<? extends E>, E extends ArchiveEntry> T getInputStream(final String type, final String resource,
final ArchiveStreamFactory factory) throws IOException, ArchiveException {
@@ -257,31 +218,29 @@ public class ArchiveStreamFactoryTest extends AbstractTestCase {
throws ArchiveException {
return factory.createArchiveOutputStream(type, new ByteArrayOutputStream());
}
-
/**
- * see https://issues.apache.org/jira/browse/COMPRESS-171
+ * see https://issues.apache.org/jira/browse/COMPRESS-191
*/
@Test
- public void testShortTextFilesAreNoTARs() {
- final ArchiveException ae = assertThrows(ArchiveException.class, () -> ArchiveStreamFactory.DEFAULT.createArchiveInputStream(
- new ByteArrayInputStream("This certainly is not a tar archive, really, no kidding".getBytes())), "created an input stream for a non-archive");
- assertTrue(ae.getMessage().startsWith("No Archiver found"));
+ public void testAiffFilesAreNoTARs() throws Exception {
+ try (final InputStream fis = newInputStream("testAIFF.aif");
+ final InputStream is = new BufferedInputStream(fis)) {
+ final ArchiveException ae = assertThrows(ArchiveException.class, () -> ArchiveStreamFactory.DEFAULT.createArchiveInputStream(is),
+ "created an input stream for a non-archive");
+ assertTrue(ae.getMessage().startsWith("No Archiver found"));
+ }
}
- /**
- * Test case for
- * <a href="https://issues.apache.org/jira/browse/COMPRESS-208"
- * >COMPRESS-208</a>.
- */
@Test
- public void testSkipsPK00Prefix() throws Exception {
- try (InputStream fis = newInputStream("COMPRESS-208.zip")) {
- try (InputStream bis = new BufferedInputStream(fis)) {
- try (ArchiveInputStream<?> ais = ArchiveStreamFactory.DEFAULT.createArchiveInputStream(bis)) {
- assertTrue(ais instanceof ZipArchiveInputStream);
- }
- }
- }
+ public void testCantRead7zFromStream() throws Exception {
+ assertThrows(StreamingNotSupportedException.class,
+ () -> ArchiveStreamFactory.DEFAULT.createArchiveInputStream(ArchiveStreamFactory.SEVEN_Z, new ByteArrayInputStream(ByteUtils.EMPTY_BYTE_ARRAY)));
+ }
+
+ @Test
+ public void testCantWrite7zToStream() throws Exception {
+ assertThrows(StreamingNotSupportedException.class,
+ () -> ArchiveStreamFactory.DEFAULT.createArchiveOutputStream(ArchiveStreamFactory.SEVEN_Z, new ByteArrayOutputStream()));
}
@Test
@@ -324,6 +283,21 @@ public class ArchiveStreamFactoryTest extends AbstractTestCase {
assertEquals("IOException while reading signature.", e3.getMessage());
}
+ /**
+ * Test case for
+ * <a href="https://issues.apache.org/jira/browse/COMPRESS-267"
+ * >COMPRESS-267</a>.
+ */
+ @Test
+ public void testDetectsAndThrowsFor7z() throws Exception {
+ try (final InputStream fis = newInputStream("bla.7z");
+ final InputStream bis = new BufferedInputStream(fis)) {
+ final StreamingNotSupportedException ex = assertThrows(StreamingNotSupportedException.class, () -> ArchiveStreamFactory.DEFAULT.createArchiveInputStream(bis),
+ "Expected a StreamingNotSupportedException");
+ assertEquals(ArchiveStreamFactory.SEVEN_Z, ex.getFormat());
+ }
+ }
+
@Test
public void testEncodingCtor() {
ArchiveStreamFactory fac = new ArchiveStreamFactory();
@@ -403,4 +377,30 @@ public class ArchiveStreamFactoryTest extends AbstractTestCase {
fail("Tests failed: " + failed + " out of " + TESTS.length);
}
}
+
+ /**
+ * see https://issues.apache.org/jira/browse/COMPRESS-171
+ */
+ @Test
+ public void testShortTextFilesAreNoTARs() {
+ final ArchiveException ae = assertThrows(ArchiveException.class, () -> ArchiveStreamFactory.DEFAULT.createArchiveInputStream(
+ new ByteArrayInputStream("This certainly is not a tar archive, really, no kidding".getBytes())), "created an input stream for a non-archive");
+ assertTrue(ae.getMessage().startsWith("No Archiver found"));
+ }
+
+ /**
+ * Test case for
+ * <a href="https://issues.apache.org/jira/browse/COMPRESS-208"
+ * >COMPRESS-208</a>.
+ */
+ @Test
+ public void testSkipsPK00Prefix() throws Exception {
+ try (InputStream fis = newInputStream("COMPRESS-208.zip")) {
+ try (InputStream bis = new BufferedInputStream(fis)) {
+ try (ArchiveInputStream<?> ais = ArchiveStreamFactory.DEFAULT.createArchiveInputStream(bis)) {
+ assertTrue(ais instanceof ZipArchiveInputStream);
+ }
+ }
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/SevenZTestCase.java b/src/test/java/org/apache/commons/compress/archivers/SevenZTestCase.java
index 0aa99f5e..f87266b8 100644
--- a/src/test/java/org/apache/commons/compress/archivers/SevenZTestCase.java
+++ b/src/test/java/org/apache/commons/compress/archivers/SevenZTestCase.java
@@ -96,34 +96,6 @@ public class SevenZTestCase extends AbstractTestCase {
}
}
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingAES() throws Exception {
- assumeStrongCryptoIsAvailable();
- try (SevenZFile archive = new SevenZFile(getFile("bla.encrypted.7z"), "foo".toCharArray())) {
- multiByteReadConsistentlyReturnsMinusOneAtEof(archive);
- }
- }
-
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingBZIP2() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.BZIP2);
- }
-
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.DEFLATE);
- }
-
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingLZMA() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.LZMA);
- }
-
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingLZMA2() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.LZMA2);
- }
-
private void readFully(final SevenZFile archive) throws IOException {
final byte[] buf = new byte[1024];
int x = 0;
@@ -155,36 +127,31 @@ public class SevenZTestCase extends AbstractTestCase {
}
@Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingAES() throws Exception {
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingAES() throws Exception {
assumeStrongCryptoIsAvailable();
try (SevenZFile archive = new SevenZFile(getFile("bla.encrypted.7z"), "foo".toCharArray())) {
- singleByteReadConsistentlyReturnsMinusOneAtEof(archive);
+ multiByteReadConsistentlyReturnsMinusOneAtEof(archive);
}
}
@Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingBZIP2() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.BZIP2);
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingCopy() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.COPY);
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingBZIP2() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.BZIP2);
}
@Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.DEFLATE);
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.DEFLATE);
}
@Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingLZMA() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.LZMA);
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingLZMA() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.LZMA);
}
@Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingLZMA2() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.LZMA2);
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingLZMA2() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.LZMA2);
}
private void testSevenZArchiveCreation(final SevenZMethod method) throws Exception {
@@ -236,4 +203,37 @@ public class SevenZTestCase extends AbstractTestCase {
public void testSevenZArchiveCreationUsingLZMA2() throws Exception {
testSevenZArchiveCreation(SevenZMethod.LZMA2);
}
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingAES() throws Exception {
+ assumeStrongCryptoIsAvailable();
+ try (SevenZFile archive = new SevenZFile(getFile("bla.encrypted.7z"), "foo".toCharArray())) {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(archive);
+ }
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingBZIP2() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.BZIP2);
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingCopy() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.COPY);
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.DEFLATE);
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingLZMA() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.LZMA);
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingLZMA2() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(SevenZMethod.LZMA2);
+ }
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/ZipTestCase.java b/src/test/java/org/apache/commons/compress/archivers/ZipTestCase.java
index 09551287..9a816424 100644
--- a/src/test/java/org/apache/commons/compress/archivers/ZipTestCase.java
+++ b/src/test/java/org/apache/commons/compress/archivers/ZipTestCase.java
@@ -120,79 +120,6 @@ public final class ZipTestCase extends AbstractTestCase {
}
}
- @Test
- public void testBuildSplitZipTest() throws IOException {
- final File directoryToZip = getFilesToZip();
- createTestSplitZipSegments();
-
- final File lastFile = new File(dir, "splitZip.zip");
- try (SeekableByteChannel channel = ZipSplitReadOnlySeekableByteChannel.buildFromLastSplitSegment(lastFile);
- InputStream inputStream = Channels.newInputStream(channel);
- ZipArchiveInputStream splitInputStream = new ZipArchiveInputStream(inputStream,
- UTF_8.toString(), true, false, true)) {
-
- ArchiveEntry entry;
- final int filesNum = countNonDirectories(directoryToZip);
- int filesCount = 0;
- while ((entry = splitInputStream.getNextEntry()) != null) {
- if (entry.isDirectory()) {
- continue;
- }
- // compare all files one by one
- final File fileToCompare = new File(entry.getName());
- try (InputStream inputStreamToCompare = Files.newInputStream(fileToCompare.toPath())) {
- assertArrayEquals(IOUtils.toByteArray(splitInputStream),
- IOUtils.toByteArray(inputStreamToCompare));
- }
- filesCount++;
- }
- // and the number of files should equal
- assertEquals(filesCount, filesNum);
- }
- }
-
- @Test
- public void testBuildSplitZipWithSegmentAlreadyExistThrowsException() throws IOException {
- final File directoryToZip = getFilesToZip();
- final File outputZipFile = new File(dir, "splitZip.zip");
- final long splitSize = 100 * 1024L; /* 100 KB */
- try (final ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(outputZipFile,
- splitSize)) {
-
- // create a file that has the same name of one of the created split segments
- final File sameNameFile = new File(dir, "splitZip.z01");
- sameNameFile.createNewFile();
-
- assertThrows(IOException.class, () -> addFilesToZip(zipArchiveOutputStream, directoryToZip));
- } catch (final Exception e) {
- // Ignore:
- // java.io.IOException: This archive contains unclosed entries.
- // at org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream.finish(ZipArchiveOutputStream.java:563)
- // at org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream.close(ZipArchiveOutputStream.java:1119)
- // at org.apache.commons.compress.archivers.ZipTestCase.buildSplitZipWithSegmentAlreadyExistThrowsException(ZipTestCase.java:715)
- }
- }
-
- @Test
- public void testBuildSplitZipWithTooLargeSizeThrowsException() throws IOException {
- final Path file = Files.createTempFile("temp", "zip");
- try {
- assertThrows(IllegalArgumentException.class, () -> new ZipArchiveOutputStream(file, 4294967295L + 1));
- } finally {
- Files.delete(file);
- }
- }
-
- @Test
- public void testBuildSplitZipWithTooSmallSizeThrowsException() throws IOException {
- final Path file = Files.createTempFile("temp", "zip");
- try {
- assertThrows(IllegalArgumentException.class, () -> new ZipArchiveOutputStream(File.createTempFile("temp", "zip"), 64 * 1024 - 1));
- } finally {
- Files.delete(file);
- }
- }
-
private int countNonDirectories(final File file) {
if (!file.isDirectory()) {
return 1;
@@ -279,64 +206,92 @@ public final class ZipTestCase extends AbstractTestCase {
return dir.listFiles()[0];
}
- @Test
- public void testInputStreamStatisticsForBzip2Entry() throws IOException, ArchiveException {
- final Map<String, List<Long>> expected = new HashMap<>();
- expected.put("lots-of-as", Arrays.asList(42L, 39L));
- testInputStreamStatistics("bzip2-zip.zip", expected);
+ private void readStream(final InputStream in, final ArchiveEntry entry, final Map<String,List<List<Long>>> map) throws IOException {
+ final byte[] buf = new byte[4096];
+ final InputStreamStatistics stats = (InputStreamStatistics) in;
+ while (in.read(buf) != -1) {
+ // consume all.
+ }
+
+ final String name = entry.getName();
+ final List<List<Long>> list = map.computeIfAbsent(name, k -> new ArrayList<>());
+
+ final long t = stats.getUncompressedCount();
+ final long b = stats.getCompressedCount();
+ list.add(Arrays.asList(t, b));
}
@Test
- public void testInputStreamStatisticsForDeflate64Entry() throws IOException, ArchiveException {
- final Map<String, List<Long>> expected = new HashMap<>();
- expected.put("input2", Arrays.asList(3072L, 2111L));
- testInputStreamStatistics("COMPRESS-380/COMPRESS-380.zip", expected);
- }
+ public void testBuildSplitZipTest() throws IOException {
+ final File directoryToZip = getFilesToZip();
+ createTestSplitZipSegments();
+ final File lastFile = new File(dir, "splitZip.zip");
+ try (SeekableByteChannel channel = ZipSplitReadOnlySeekableByteChannel.buildFromLastSplitSegment(lastFile);
+ InputStream inputStream = Channels.newInputStream(channel);
+ ZipArchiveInputStream splitInputStream = new ZipArchiveInputStream(inputStream,
+ UTF_8.toString(), true, false, true)) {
- @Test
- public void testInputStreamStatisticsForImplodedEntry() throws IOException, ArchiveException {
- final Map<String, List<Long>> expected = new HashMap<>();
- expected.put("LICENSE.TXT", Arrays.asList(11560L, 4131L));
- testInputStreamStatistics("imploding-8Kdict-3trees.zip", expected);
+ ArchiveEntry entry;
+ final int filesNum = countNonDirectories(directoryToZip);
+ int filesCount = 0;
+ while ((entry = splitInputStream.getNextEntry()) != null) {
+ if (entry.isDirectory()) {
+ continue;
+ }
+ // compare all files one by one
+ final File fileToCompare = new File(entry.getName());
+ try (InputStream inputStreamToCompare = Files.newInputStream(fileToCompare.toPath())) {
+ assertArrayEquals(IOUtils.toByteArray(splitInputStream),
+ IOUtils.toByteArray(inputStreamToCompare));
+ }
+ filesCount++;
+ }
+ // and the number of files should equal
+ assertEquals(filesCount, filesNum);
+ }
}
@Test
- public void testInputStreamStatisticsForShrunkEntry() throws IOException, ArchiveException {
- final Map<String, List<Long>> expected = new HashMap<>();
- expected.put("TEST1.XML", Arrays.asList(76L, 66L));
- expected.put("TEST2.XML", Arrays.asList(81L, 76L));
- testInputStreamStatistics("SHRUNK.ZIP", expected);
- }
+ public void testBuildSplitZipWithSegmentAlreadyExistThrowsException() throws IOException {
+ final File directoryToZip = getFilesToZip();
+ final File outputZipFile = new File(dir, "splitZip.zip");
+ final long splitSize = 100 * 1024L; /* 100 KB */
+ try (final ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(outputZipFile,
+ splitSize)) {
- @Test
- public void testInputStreamStatisticsForStoredEntry() throws IOException, ArchiveException {
- final Map<String, List<Long>> expected = new HashMap<>();
- expected.put("test.txt", Arrays.asList(5L, 5L));
- testInputStreamStatistics("COMPRESS-264.zip", expected);
+ // create a file that has the same name of one of the created split segments
+ final File sameNameFile = new File(dir, "splitZip.z01");
+ sameNameFile.createNewFile();
+
+ assertThrows(IOException.class, () -> addFilesToZip(zipArchiveOutputStream, directoryToZip));
+ } catch (final Exception e) {
+ // Ignore:
+ // java.io.IOException: This archive contains unclosed entries.
+ // at org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream.finish(ZipArchiveOutputStream.java:563)
+ // at org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream.close(ZipArchiveOutputStream.java:1119)
+ // at org.apache.commons.compress.archivers.ZipTestCase.buildSplitZipWithSegmentAlreadyExistThrowsException(ZipTestCase.java:715)
+ }
}
@Test
- public void testInputStreamStatisticsOfZipBombExcel() throws IOException, ArchiveException {
- final Map<String, List<Long>> expected = new HashMap<>();
- expected.put("[Content_Types].xml", Arrays.asList(8390036L, 8600L));
- expected.put("xl/worksheets/sheet1.xml", Arrays.asList(1348L, 508L));
- testInputStreamStatistics("zipbomb.xlsx", expected);
+ public void testBuildSplitZipWithTooLargeSizeThrowsException() throws IOException {
+ final Path file = Files.createTempFile("temp", "zip");
+ try {
+ assertThrows(IllegalArgumentException.class, () -> new ZipArchiveOutputStream(file, 4294967295L + 1));
+ } finally {
+ Files.delete(file);
+ }
}
- private void readStream(final InputStream in, final ArchiveEntry entry, final Map<String,List<List<Long>>> map) throws IOException {
- final byte[] buf = new byte[4096];
- final InputStreamStatistics stats = (InputStreamStatistics) in;
- while (in.read(buf) != -1) {
- // consume all.
+ @Test
+ public void testBuildSplitZipWithTooSmallSizeThrowsException() throws IOException {
+ final Path file = Files.createTempFile("temp", "zip");
+ try {
+ assertThrows(IllegalArgumentException.class, () -> new ZipArchiveOutputStream(File.createTempFile("temp", "zip"), 64 * 1024 - 1));
+ } finally {
+ Files.delete(file);
}
-
- final String name = entry.getName();
- final List<List<Long>> list = map.computeIfAbsent(name, k -> new ArrayList<>());
-
- final long t = stats.getUncompressedCount();
- final long b = stats.getCompressedCount();
- list.add(Arrays.asList(t, b));
}
@Test
@@ -371,6 +326,7 @@ public final class ZipTestCase extends AbstractTestCase {
}
}
+
@Test
public void testCopyRawZip64EntryFromFile()
throws IOException {
@@ -601,6 +557,50 @@ public final class ZipTestCase extends AbstractTestCase {
}
}
+ @Test
+ public void testInputStreamStatisticsForBzip2Entry() throws IOException, ArchiveException {
+ final Map<String, List<Long>> expected = new HashMap<>();
+ expected.put("lots-of-as", Arrays.asList(42L, 39L));
+ testInputStreamStatistics("bzip2-zip.zip", expected);
+ }
+
+ @Test
+ public void testInputStreamStatisticsForDeflate64Entry() throws IOException, ArchiveException {
+ final Map<String, List<Long>> expected = new HashMap<>();
+ expected.put("input2", Arrays.asList(3072L, 2111L));
+ testInputStreamStatistics("COMPRESS-380/COMPRESS-380.zip", expected);
+ }
+
+ @Test
+ public void testInputStreamStatisticsForImplodedEntry() throws IOException, ArchiveException {
+ final Map<String, List<Long>> expected = new HashMap<>();
+ expected.put("LICENSE.TXT", Arrays.asList(11560L, 4131L));
+ testInputStreamStatistics("imploding-8Kdict-3trees.zip", expected);
+ }
+
+ @Test
+ public void testInputStreamStatisticsForShrunkEntry() throws IOException, ArchiveException {
+ final Map<String, List<Long>> expected = new HashMap<>();
+ expected.put("TEST1.XML", Arrays.asList(76L, 66L));
+ expected.put("TEST2.XML", Arrays.asList(81L, 76L));
+ testInputStreamStatistics("SHRUNK.ZIP", expected);
+ }
+
+ @Test
+ public void testInputStreamStatisticsForStoredEntry() throws IOException, ArchiveException {
+ final Map<String, List<Long>> expected = new HashMap<>();
+ expected.put("test.txt", Arrays.asList(5L, 5L));
+ testInputStreamStatistics("COMPRESS-264.zip", expected);
+ }
+
+ @Test
+ public void testInputStreamStatisticsOfZipBombExcel() throws IOException, ArchiveException {
+ final Map<String, List<Long>> expected = new HashMap<>();
+ expected.put("[Content_Types].xml", Arrays.asList(8390036L, 8600L));
+ expected.put("xl/worksheets/sheet1.xml", Arrays.asList(1348L, 508L));
+ testInputStreamStatistics("zipbomb.xlsx", expected);
+ }
+
/**
* Checks if all entries from a nested archive can be read.
* The archive: OSX_ArchiveWithNestedArchive.zip contains:
diff --git a/src/test/java/org/apache/commons/compress/archivers/ar/ArArchiveInputStreamTest.java b/src/test/java/org/apache/commons/compress/archivers/ar/ArArchiveInputStreamTest.java
index 17639c98..e5d5b5b5 100644
--- a/src/test/java/org/apache/commons/compress/archivers/ar/ArArchiveInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/ar/ArArchiveInputStreamTest.java
@@ -37,23 +37,6 @@ import org.junit.jupiter.api.Test;
public class ArArchiveInputStreamTest extends AbstractTestCase {
- @Test
- public void testCantReadAfterClose() throws Exception {
- try (InputStream in = newInputStream("bla.ar");
- ArArchiveInputStream archive = new ArArchiveInputStream(in)) {
- archive.close();
- assertThrows(IllegalStateException.class, () -> archive.read());
- }
- }
-
- @Test
- public void testCantReadWithoutOpeningAnEntry() throws Exception {
- try (InputStream in = newInputStream("bla.ar");
- ArArchiveInputStream archive = new ArArchiveInputStream(in)) {
- assertThrows(IllegalStateException.class, () -> archive.read());
- }
- }
-
private void checkLongNameEntry(final String archive) throws Exception {
try (final InputStream fis = newInputStream(archive);
final ArArchiveInputStream s = new ArArchiveInputStream(new BufferedInputStream(fis))) {
@@ -73,6 +56,23 @@ public class ArArchiveInputStreamTest extends AbstractTestCase {
}
}
+ @Test
+ public void testCantReadAfterClose() throws Exception {
+ try (InputStream in = newInputStream("bla.ar");
+ ArArchiveInputStream archive = new ArArchiveInputStream(in)) {
+ archive.close();
+ assertThrows(IllegalStateException.class, () -> archive.read());
+ }
+ }
+
+ @Test
+ public void testCantReadWithoutOpeningAnEntry() throws Exception {
+ try (InputStream in = newInputStream("bla.ar");
+ ArArchiveInputStream archive = new ArArchiveInputStream(in)) {
+ assertThrows(IllegalStateException.class, () -> archive.read());
+ }
+ }
+
@Test
public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
final byte[] buf = new byte[2];
@@ -85,6 +85,16 @@ public class ArArchiveInputStreamTest extends AbstractTestCase {
}
}
+ @Test
+ public void testReadLongNamesBSD() throws Exception {
+ checkLongNameEntry("longfile_bsd.ar");
+ }
+
+ @Test
+ public void testReadLongNamesGNU() throws Exception {
+ checkLongNameEntry("longfile_gnu.ar");
+ }
+
@Test
public void testSimpleInputStream() throws IOException {
try (final InputStream fileInputStream = newInputStream("bla.ar")) {
@@ -124,14 +134,4 @@ public class ArArchiveInputStreamTest extends AbstractTestCase {
assertEquals(-1, archive.read());
}
}
-
- @Test
- public void testReadLongNamesBSD() throws Exception {
- checkLongNameEntry("longfile_bsd.ar");
- }
-
- @Test
- public void testReadLongNamesGNU() throws Exception {
- checkLongNameEntry("longfile_gnu.ar");
- }
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/arj/ArjArchiveInputStreamTest.java b/src/test/java/org/apache/commons/compress/archivers/arj/ArjArchiveInputStreamTest.java
index 9710116c..334e8260 100644
--- a/src/test/java/org/apache/commons/compress/archivers/arj/ArjArchiveInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/arj/ArjArchiveInputStreamTest.java
@@ -33,29 +33,6 @@ import org.junit.jupiter.api.Test;
public class ArjArchiveInputStreamTest extends AbstractTestCase {
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
- final byte[] buf = new byte[2];
- try (InputStream in = newInputStream("bla.arj");
- ArjArchiveInputStream archive = new ArjArchiveInputStream(in)) {
- final ArchiveEntry e = archive.getNextEntry();
- IOUtils.toByteArray(archive);
- assertEquals(-1, archive.read(buf));
- assertEquals(-1, archive.read(buf));
- }
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
- try (InputStream in = newInputStream("bla.arj");
- ArjArchiveInputStream archive = new ArjArchiveInputStream(in)) {
- final ArchiveEntry e = archive.getNextEntry();
- IOUtils.toByteArray(archive);
- assertEquals(-1, archive.read());
- assertEquals(-1, archive.read());
- }
- }
-
@Test
public void testArjUnarchive() throws Exception {
final StringBuilder expected = new StringBuilder();
@@ -79,6 +56,18 @@ public class ArjArchiveInputStreamTest extends AbstractTestCase {
assertEquals(result.toString(), expected.toString());
}
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
+ final byte[] buf = new byte[2];
+ try (InputStream in = newInputStream("bla.arj");
+ ArjArchiveInputStream archive = new ArjArchiveInputStream(in)) {
+ final ArchiveEntry e = archive.getNextEntry();
+ IOUtils.toByteArray(archive);
+ assertEquals(-1, archive.read(buf));
+ assertEquals(-1, archive.read(buf));
+ }
+ }
+
@Test
public void testReadingOfAttributesDosVersion() throws Exception {
try (final ArjArchiveInputStream in = new ArjArchiveInputStream(newInputStream("bla.arj"))) {
@@ -107,4 +96,15 @@ public class ArjArchiveInputStreamTest extends AbstractTestCase {
}
}
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
+ try (InputStream in = newInputStream("bla.arj");
+ ArjArchiveInputStream archive = new ArjArchiveInputStream(in)) {
+ final ArchiveEntry e = archive.getNextEntry();
+ IOUtils.toByteArray(archive);
+ assertEquals(-1, archive.read());
+ assertEquals(-1, archive.read());
+ }
+ }
+
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/cpio/CpioArchiveInputStreamTest.java b/src/test/java/org/apache/commons/compress/archivers/cpio/CpioArchiveInputStreamTest.java
index c20b2c87..c88f2c02 100644
--- a/src/test/java/org/apache/commons/compress/archivers/cpio/CpioArchiveInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/cpio/CpioArchiveInputStreamTest.java
@@ -30,27 +30,6 @@ import org.junit.jupiter.api.Test;
public class CpioArchiveInputStreamTest extends AbstractTestCase {
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
- final byte[] buf = new byte[2];
- try (InputStream in = newInputStream("bla.cpio"); CpioArchiveInputStream archive = new CpioArchiveInputStream(in)) {
- final ArchiveEntry e = archive.getNextEntry();
- IOUtils.toByteArray(archive);
- assertEquals(-1, archive.read(buf));
- assertEquals(-1, archive.read(buf));
- }
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
- try (InputStream in = newInputStream("bla.cpio"); CpioArchiveInputStream archive = new CpioArchiveInputStream(in)) {
- final ArchiveEntry e = archive.getNextEntry();
- IOUtils.toByteArray(archive);
- assertEquals(-1, archive.read());
- assertEquals(-1, archive.read());
- }
- }
-
@Test
public void testCpioUnarchive() throws Exception {
final StringBuilder expected = new StringBuilder();
@@ -103,4 +82,25 @@ public class CpioArchiveInputStreamTest extends AbstractTestCase {
assertEquals(2, count);
}
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
+ final byte[] buf = new byte[2];
+ try (InputStream in = newInputStream("bla.cpio"); CpioArchiveInputStream archive = new CpioArchiveInputStream(in)) {
+ final ArchiveEntry e = archive.getNextEntry();
+ IOUtils.toByteArray(archive);
+ assertEquals(-1, archive.read(buf));
+ assertEquals(-1, archive.read(buf));
+ }
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
+ try (InputStream in = newInputStream("bla.cpio"); CpioArchiveInputStream archive = new CpioArchiveInputStream(in)) {
+ final ArchiveEntry e = archive.getNextEntry();
+ IOUtils.toByteArray(archive);
+ assertEquals(-1, archive.read());
+ assertEquals(-1, archive.read());
+ }
+ }
+
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/cpio/CpioUtilTest.java b/src/test/java/org/apache/commons/compress/archivers/cpio/CpioUtilTest.java
index a93c0fb3..2989ddeb 100644
--- a/src/test/java/org/apache/commons/compress/archivers/cpio/CpioUtilTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/cpio/CpioUtilTest.java
@@ -27,39 +27,39 @@ import org.junit.jupiter.api.Test;
public class CpioUtilTest {
@Test
- public void testOldBinMagic2ByteArrayNotSwapped() {
- assertArrayEquals(new byte[] {(byte) 0xc7, 0x71}, CpioUtil.long2byteArray(CpioConstants.MAGIC_OLD_BINARY, 2, false));
+ public void testByteArray2longThrowsUnsupportedOperationException() {
+ assertThrows(UnsupportedOperationException.class, () -> CpioUtil.byteArray2long(new byte[1], true));
+
}
@Test
- public void testOldBinMagic2ByteArraySwapped() {
- assertArrayEquals(new byte[] {0x71, (byte) 0xc7,}, CpioUtil.long2byteArray(CpioConstants.MAGIC_OLD_BINARY, 2, true));
+ public void testLong2byteArrayWithPositiveThrowsUnsupportedOperationException() {
+ assertThrows(UnsupportedOperationException.class, () -> CpioUtil.long2byteArray(0L, 1021, false));
}
@Test
- public void testOldBinMagicFromByteArrayNotSwapped() {
- assertEquals(CpioConstants.MAGIC_OLD_BINARY, CpioUtil.byteArray2long(new byte[] {(byte) 0xc7, 0x71}, false));
+ public void testLong2byteArrayWithZeroThrowsUnsupportedOperationException() {
+ assertThrows(UnsupportedOperationException.class, () -> CpioUtil.long2byteArray(0L, 0, false));
}
@Test
- public void testOldBinMagicFromByteArraySwapped() {
- assertEquals(CpioConstants.MAGIC_OLD_BINARY, CpioUtil.byteArray2long(new byte[] {0x71, (byte) 0xc7}, true));
+ public void testOldBinMagic2ByteArrayNotSwapped() {
+ assertArrayEquals(new byte[] {(byte) 0xc7, 0x71}, CpioUtil.long2byteArray(CpioConstants.MAGIC_OLD_BINARY, 2, false));
}
@Test
- public void testByteArray2longThrowsUnsupportedOperationException() {
- assertThrows(UnsupportedOperationException.class, () -> CpioUtil.byteArray2long(new byte[1], true));
-
+ public void testOldBinMagic2ByteArraySwapped() {
+ assertArrayEquals(new byte[] {0x71, (byte) 0xc7,}, CpioUtil.long2byteArray(CpioConstants.MAGIC_OLD_BINARY, 2, true));
}
@Test
- public void testLong2byteArrayWithPositiveThrowsUnsupportedOperationException() {
- assertThrows(UnsupportedOperationException.class, () -> CpioUtil.long2byteArray(0L, 1021, false));
+ public void testOldBinMagicFromByteArrayNotSwapped() {
+ assertEquals(CpioConstants.MAGIC_OLD_BINARY, CpioUtil.byteArray2long(new byte[] {(byte) 0xc7, 0x71}, false));
}
@Test
- public void testLong2byteArrayWithZeroThrowsUnsupportedOperationException() {
- assertThrows(UnsupportedOperationException.class, () -> CpioUtil.long2byteArray(0L, 0, false));
+ public void testOldBinMagicFromByteArraySwapped() {
+ assertEquals(CpioConstants.MAGIC_OLD_BINARY, CpioUtil.byteArray2long(new byte[] {0x71, (byte) 0xc7}, true));
}
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/dump/DumpArchiveInputStreamTest.java b/src/test/java/org/apache/commons/compress/archivers/dump/DumpArchiveInputStreamTest.java
index 0c46a2b5..070de92f 100644
--- a/src/test/java/org/apache/commons/compress/archivers/dump/DumpArchiveInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/dump/DumpArchiveInputStreamTest.java
@@ -34,29 +34,6 @@ import org.junit.jupiter.api.Test;
public class DumpArchiveInputStreamTest extends AbstractTestCase {
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
- final byte[] buf = new byte[2];
- try (InputStream in = newInputStream("bla.dump");
- DumpArchiveInputStream archive = new DumpArchiveInputStream(in)) {
- final ArchiveEntry e = archive.getNextEntry();
- IOUtils.toByteArray(archive);
- assertEquals(-1, archive.read(buf));
- assertEquals(-1, archive.read(buf));
- }
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
- try (InputStream in = newInputStream("bla.dump");
- DumpArchiveInputStream archive = new DumpArchiveInputStream(in)) {
- final ArchiveEntry e = archive.getNextEntry();
- IOUtils.toByteArray(archive);
- assertEquals(-1, archive.read());
- assertEquals(-1, archive.read());
- }
- }
-
@Test
public void testConsumesArchiveCompletely() throws Exception {
try (final InputStream is = DumpArchiveInputStreamTest.class.getResourceAsStream("/archive_with_trailer.dump");
@@ -71,6 +48,18 @@ public class DumpArchiveInputStreamTest extends AbstractTestCase {
}
}
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
+ final byte[] buf = new byte[2];
+ try (InputStream in = newInputStream("bla.dump");
+ DumpArchiveInputStream archive = new DumpArchiveInputStream(in)) {
+ final ArchiveEntry e = archive.getNextEntry();
+ IOUtils.toByteArray(archive);
+ assertEquals(-1, archive.read(buf));
+ assertEquals(-1, archive.read(buf));
+ }
+ }
+
@Test
public void testNotADumpArchive() throws Exception {
try (InputStream is = newInputStream("bla.zip")) {
@@ -89,4 +78,15 @@ public class DumpArchiveInputStreamTest extends AbstractTestCase {
}
}
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
+ try (InputStream in = newInputStream("bla.dump");
+ DumpArchiveInputStream archive = new DumpArchiveInputStream(in)) {
+ final ArchiveEntry e = archive.getNextEntry();
+ IOUtils.toByteArray(archive);
+ assertEquals(-1, archive.read());
+ assertEquals(-1, archive.read());
+ }
+ }
+
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/examples/ExpanderTest.java b/src/test/java/org/apache/commons/compress/archivers/examples/ExpanderTest.java
index 52bd8da5..1c041483 100644
--- a/src/test/java/org/apache/commons/compress/archivers/examples/ExpanderTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/examples/ExpanderTest.java
@@ -62,41 +62,6 @@ public class ExpanderTest extends AbstractTestCase {
}
}
- @Test
- public void testFileCantEscapeDoubleDotPath() throws IOException, ArchiveException {
- setupZip("../foo");
- try (ZipFile f = new ZipFile(archive)) {
- assertThrows(IOException.class, () -> new Expander().expand(f, resultDir));
- }
- }
-
- @Test
- public void testFileCantEscapeDoubleDotPathWithSimilarSibling() throws IOException, ArchiveException {
- final String sibling = resultDir.getName() + "x";
- final File s = new File(resultDir.getParentFile(), sibling);
- assumeFalse(s.exists());
- s.mkdirs();
- assumeTrue(s.exists());
- s.deleteOnExit();
- try {
- setupZip("../" + sibling + "/a");
- try (ZipFile f = new ZipFile(archive)) {
- assertThrows(IOException.class, () -> new Expander().expand(f, resultDir));
- }
- } finally {
- forceDelete(s);
- }
- }
-
- @Test
- public void testFileCantEscapeViaAbsolutePath() throws IOException, ArchiveException {
- setupZip("/tmp/foo");
- try (ZipFile f = new ZipFile(archive)) {
- assertThrows(IOException.class, () -> new Expander().expand(f, resultDir));
- }
- assertFalse(new File(resultDir, "tmp/foo").isFile());
- }
-
private void setup7z() throws IOException {
archive = new File(dir, "test.7z");
final File dummy = new File(dir, "x");
@@ -209,6 +174,59 @@ public class ExpanderTest extends AbstractTestCase {
}
}
+ @Test
+ public void tarFileVersion() throws IOException, ArchiveException {
+ setupTar();
+ try (TarFile f = new TarFile(archive)) {
+ new Expander().expand(f, resultDir);
+ }
+ verifyTargetDir();
+ }
+
+ @Test
+ public void testCompress603Tar() throws IOException, ArchiveException {
+ setupTarForCompress603();
+ try (TarFile f = new TarFile(archive)) {
+ new Expander().expand(f, resultDir);
+ }
+ verifyTargetDir();
+ }
+
+ @Test
+ public void testFileCantEscapeDoubleDotPath() throws IOException, ArchiveException {
+ setupZip("../foo");
+ try (ZipFile f = new ZipFile(archive)) {
+ assertThrows(IOException.class, () -> new Expander().expand(f, resultDir));
+ }
+ }
+
+ @Test
+ public void testFileCantEscapeDoubleDotPathWithSimilarSibling() throws IOException, ArchiveException {
+ final String sibling = resultDir.getName() + "x";
+ final File s = new File(resultDir.getParentFile(), sibling);
+ assumeFalse(s.exists());
+ s.mkdirs();
+ assumeTrue(s.exists());
+ s.deleteOnExit();
+ try {
+ setupZip("../" + sibling + "/a");
+ try (ZipFile f = new ZipFile(archive)) {
+ assertThrows(IOException.class, () -> new Expander().expand(f, resultDir));
+ }
+ } finally {
+ forceDelete(s);
+ }
+ }
+
+ @Test
+ public void testFileCantEscapeViaAbsolutePath() throws IOException, ArchiveException {
+ setupZip("/tmp/foo");
+ try (ZipFile f = new ZipFile(archive)) {
+ assertThrows(IOException.class, () -> new Expander().expand(f, resultDir));
+ }
+ assertFalse(new File(resultDir, "tmp/foo").isFile());
+ }
+
@Test
public void testSevenZChannelVersion() throws IOException, ArchiveException {
setup7z();
@@ -258,18 +276,9 @@ public class ExpanderTest extends AbstractTestCase {
}
@Test
- public void tarFileVersion() throws IOException, ArchiveException {
- setupTar();
- try (TarFile f = new TarFile(archive)) {
- new Expander().expand(f, resultDir);
- }
- verifyTargetDir();
- }
-
- @Test
- public void testCompress603Tar() throws IOException, ArchiveException {
- setupTarForCompress603();
- try (TarFile f = new TarFile(archive)) {
+ public void testZipFileVersion() throws IOException, ArchiveException {
+ setupZip();
+ try (ZipFile f = new ZipFile(archive)) {
new Expander().expand(f, resultDir);
}
verifyTargetDir();
@@ -283,13 +292,4 @@ public class ExpanderTest extends AbstractTestCase {
assertHelloWorld("a/b/c/e.txt", "2");
}
- @Test
- public void testZipFileVersion() throws IOException, ArchiveException {
- setupZip();
- try (ZipFile f = new ZipFile(archive)) {
- new Expander().expand(f, resultDir);
- }
- verifyTargetDir();
- }
-
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/examples/SevenZArchiverTest.java b/src/test/java/org/apache/commons/compress/archivers/examples/SevenZArchiverTest.java
index 40e6e9cd..a9721b75 100644
--- a/src/test/java/org/apache/commons/compress/archivers/examples/SevenZArchiverTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/examples/SevenZArchiverTest.java
@@ -63,6 +63,21 @@ public class SevenZArchiverTest extends AbstractTestCase {
assertArrayEquals(expected, actual);
}
+ @BeforeEach
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ final File c = new File(dir, "a/b/c");
+ c.mkdirs();
+ try (OutputStream os = Files.newOutputStream(new File(dir, "a/b/d.txt").toPath())) {
+ os.write("Hello, world 1".getBytes(UTF_8));
+ }
+ try (OutputStream os = Files.newOutputStream(new File(dir, "a/b/c/e.txt").toPath())) {
+ os.write("Hello, world 2".getBytes(UTF_8));
+ }
+ target = new File(resultDir, "test.7z");
+ }
+
@Test
public void testChannelVersion() throws IOException, ArchiveException {
try (SeekableByteChannel c = FileChannel.open(target.toPath(), StandardOpenOption.WRITE,
@@ -85,21 +100,6 @@ public class SevenZArchiverTest extends AbstractTestCase {
}
}
- @BeforeEach
- @Override
- public void setUp() throws Exception {
- super.setUp();
- final File c = new File(dir, "a/b/c");
- c.mkdirs();
- try (OutputStream os = Files.newOutputStream(new File(dir, "a/b/d.txt").toPath())) {
- os.write("Hello, world 1".getBytes(UTF_8));
- }
- try (OutputStream os = Files.newOutputStream(new File(dir, "a/b/c/e.txt").toPath())) {
- os.write("Hello, world 2".getBytes(UTF_8));
- }
- target = new File(resultDir, "test.7z");
- }
-
// not really a 7z test, but I didn't feel like adding a new test just for this
@Test
public void testUnknownFormat() throws IOException {
diff --git a/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZFileTest.java b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZFileTest.java
index 5cee9c96..5b9a22ba 100644
--- a/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZFileTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZFileTest.java
@@ -106,200 +106,6 @@ public class SevenZFileTest extends AbstractTestCase {
}
}
- @Test
- public void testExtractNonExistSpecifiedFile() throws Exception {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-256.7z")); SevenZFile anotherSevenZFile = new SevenZFile(getFile("bla.7z"))) {
- for (final SevenZArchiveEntry nonExistEntry : anotherSevenZFile.getEntries()) {
- assertThrows(IllegalArgumentException.class, () -> sevenZFile.getInputStream(nonExistEntry));
- }
- }
- }
-
- @Test
- public void testExtractSpecifiedFile() throws Exception {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-256.7z"))) {
- final String testTxtContents = "111111111111111111111111111000101011\n" +
- "111111111111111111111111111000101011\n" +
- "111111111111111111111111111000101011\n" +
- "111111111111111111111111111000101011\n" +
- "111111111111111111111111111000101011\n" +
- "111111111111111111111111111000101011\n" +
- "111111111111111111111111111000101011\n" +
- "111111111111111111111111111000101011\n" +
- "111111111111111111111111111000101011\n" +
- "111111111111111111111111111000101011";
-
- for(final SevenZArchiveEntry entry : sevenZFile.getEntries()) {
- if (entry.getName().equals("commons-compress-1.7-src/src/test/resources/test.txt")) {
- final byte[] contents = new byte[(int) entry.getSize()];
- int off = 0;
- final InputStream inputStream = sevenZFile.getInputStream(entry);
- while (off < contents.length) {
- final int bytesRead = inputStream.read(contents, off, contents.length - off);
- assert bytesRead >= 0;
- off += bytesRead;
- }
- assertEquals(testTxtContents, new String(contents, UTF_8));
- break;
- }
- }
- }
- }
-
- @Test
- public void testGetDefaultNameWorksAsExpected() throws Exception {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("bla.deflate64.7z"))) {
- assertEquals("bla.deflate64", sevenZFile.getDefaultName());
- }
- try (SevenZFile sevenZFile = new SevenZFile(Files.newByteChannel(getFile("bla.deflate64.7z").toPath()))) {
- assertNull(sevenZFile.getDefaultName());
- }
- try (SevenZFile sevenZFile = new SevenZFile(Files.newByteChannel(getFile("bla.deflate64.7z").toPath()), "foo")) {
- assertEquals("foo~", sevenZFile.getDefaultName());
- }
- try (SevenZFile sevenZFile = new SevenZFile(Files.newByteChannel(getFile("bla.deflate64.7z").toPath()), ".foo")) {
- assertEquals(".foo~", sevenZFile.getDefaultName());
- }
- }
-
- @Test
- public void testGetEntriesOfUnarchiveInMemoryTest() throws IOException {
- final byte[] data = Files.readAllBytes(getFile("bla.7z").toPath());
- try (SevenZFile sevenZFile = new SevenZFile(new SeekableInMemoryByteChannel(data))) {
- final Iterable<SevenZArchiveEntry> entries = sevenZFile.getEntries();
- final Iterator<SevenZArchiveEntry> iter = entries.iterator();
- SevenZArchiveEntry entry = iter.next();
- assertEquals("test1.xml", entry.getName());
- entry = iter.next();
- assertEquals("test2.xml", entry.getName());
- assertFalse(iter.hasNext());
- }
- }
-
- @Test
- public void testGetEntriesOfUnarchiveTest() throws IOException {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("bla.7z"))) {
- final Iterable<SevenZArchiveEntry> entries = sevenZFile.getEntries();
- final Iterator<SevenZArchiveEntry> iter = entries.iterator();
- SevenZArchiveEntry entry = iter.next();
- assertEquals("test1.xml", entry.getName());
- entry = iter.next();
- assertEquals("test2.xml", entry.getName());
- assertFalse(iter.hasNext());
- }
- }
-
- @Test
- public void testGivenNameWinsOverDefaultName() throws Exception {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("bla.7z"),
- SevenZFileOptions.builder().withUseDefaultNameForUnnamedEntries(true).build())) {
- SevenZArchiveEntry ae = sevenZFile.getNextEntry();
- assertNotNull(ae);
- assertEquals("test1.xml", ae.getName());
- ae = sevenZFile.getNextEntry();
- assertNotNull(ae);
- assertEquals("test2.xml", ae.getName());
- assertNull(sevenZFile.getNextEntry());
- }
- }
-
- /**
- * @see <a href="https://issues.apache.org/jira/browse/COMPRESS-492">COMPRESS-492</a>
- */
- @Test
- public void testHandlesEmptyArchiveWithFilesInfo() throws Exception {
- final File f = new File(dir, "empty.7z");
- try (SevenZOutputFile s = new SevenZOutputFile(f)) {
- }
- try (SevenZFile z = new SevenZFile(f)) {
- assertFalse(z.getEntries().iterator().hasNext());
- assertNull(z.getNextEntry());
- }
- }
-
- /**
- * @see <a href="https://issues.apache.org/jira/browse/COMPRESS-492">COMPRESS-492</a>
- */
- @Test
- public void testHandlesEmptyArchiveWithoutFilesInfo() throws Exception {
- try (SevenZFile z = new SevenZFile(getFile("COMPRESS-492.7z"))) {
- assertFalse(z.getEntries().iterator().hasNext());
- assertNull(z.getNextEntry());
- }
- }
-
- @Test
- public void testLimitExtractionMemory() {
- assertThrows(MemoryLimitException.class, () -> {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("bla.7z"), SevenZFileOptions.builder().withMaxMemoryLimitInKb(1).build())) {
- // Do nothing. Exception should be thrown
- }
- });
- }
-
- @Test
- public void testNoNameCanBeReplacedByDefaultName() throws Exception {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("bla-nonames.7z"),
- SevenZFileOptions.builder().withUseDefaultNameForUnnamedEntries(true).build())) {
- SevenZArchiveEntry ae = sevenZFile.getNextEntry();
- assertNotNull(ae);
- assertEquals("bla-nonames", ae.getName());
- ae = sevenZFile.getNextEntry();
- assertNotNull(ae);
- assertEquals("bla-nonames", ae.getName());
- assertNull(sevenZFile.getNextEntry());
- }
- }
-
- @Test
- public void testNoNameMeansNoNameByDefault() throws Exception {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("bla-nonames.7z"))) {
- SevenZArchiveEntry ae = sevenZFile.getNextEntry();
- assertNotNull(ae);
- assertNull(ae.getName());
- ae = sevenZFile.getNextEntry();
- assertNotNull(ae);
- assertNull(ae.getName());
- assertNull(sevenZFile.getNextEntry());
- }
- }
-
- @Test
- public void testReadBigSevenZipFile() throws IOException {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-592.7z"))) {
- SevenZArchiveEntry entry = sevenZFile.getNextEntry();
- while (entry != null) {
- if (entry.hasStream()) {
- final byte[] content = new byte[(int) entry.getSize()];
- sevenZFile.read(content);
- }
- entry = sevenZFile.getNextEntry();
- }
- }
- }
-
- /**
- * @see "https://issues.apache.org/jira/browse/COMPRESS-348"
- */
- @Test
- public void testReadEntriesOfSize0() throws IOException {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-348.7z"))) {
- int entries = 0;
- SevenZArchiveEntry entry = sevenZFile.getNextEntry();
- while (entry != null) {
- entries++;
- final int b = sevenZFile.read();
- if ("2.txt".equals(entry.getName()) || "5.txt".equals(entry.getName())) {
- assertEquals(-1, b);
- } else {
- assertNotEquals(-1, b);
- }
- entry = sevenZFile.getNextEntry();
- }
- assertEquals(5, entries);
- }
- }
-
private byte[] readFully(final SevenZFile archive) throws IOException {
final byte [] buf = new byte [1024];
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -309,76 +115,6 @@ public class SevenZFileTest extends AbstractTestCase {
return baos.toByteArray();
}
- @Test
- public void testReadTimesFromFile() throws IOException {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("times.7z"))) {
- SevenZArchiveEntry entry = sevenZFile.getNextEntry();
- assertNotNull(entry);
- assertEquals("test", entry.getName());
- assertTrue(entry.isDirectory());
- assertDates(entry, "2022-03-21T14:50:46.2099751Z", "2022-03-21T14:50:46.2099751Z", "2022-03-16T10:19:24.1051115Z");
-
- entry = sevenZFile.getNextEntry();
- assertNotNull(entry);
- assertEquals("test/test-times.txt", entry.getName());
- assertFalse(entry.isDirectory());
- assertDates(entry, "2022-03-18T10:00:15Z", "2022-03-18T10:14:37.8130002Z", "2022-03-18T10:14:37.8110032Z");
-
- entry = sevenZFile.getNextEntry();
- assertNotNull(entry);
- assertEquals("test/test-times2.txt", entry.getName());
- assertFalse(entry.isDirectory());
- assertDates(entry, "2022-03-18T10:00:19Z", "2022-03-18T10:14:37.8170038Z", "2022-03-18T10:14:37.8140004Z");
-
- entry = sevenZFile.getNextEntry();
- assertNull(entry);
- }
- }
-
- @Test
- public void testRetrieveInputStreamForAllEntriesMultipleTimes() throws IOException {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("bla.7z"))) {
- for (final SevenZArchiveEntry entry : sevenZFile.getEntries()) {
- final byte[] firstRead = IOUtils.toByteArray(sevenZFile.getInputStream(entry));
- final byte[] secondRead = IOUtils.toByteArray(sevenZFile.getInputStream(entry));
- assertArrayEquals(firstRead, secondRead);
- }
- }
- }
-
- @Test
- public void testRetrieveInputStreamForAllEntriesWithoutCRCMultipleTimes() throws IOException {
- try (final SevenZOutputFile out = new SevenZOutputFile(new File(dir, "test.7z"))) {
- final Path inputFile = Files.createTempFile("SevenZTestTemp", "");
-
- final SevenZArchiveEntry entry = out.createArchiveEntry(inputFile.toFile(), "test.txt");
- out.putArchiveEntry(entry);
- out.write("Test".getBytes(UTF_8));
- out.closeArchiveEntry();
-
- Files.deleteIfExists(inputFile);
- }
-
- try (SevenZFile sevenZFile = new SevenZFile(new File(dir, "test.7z"))) {
- for (final SevenZArchiveEntry entry : sevenZFile.getEntries()) {
- final byte[] firstRead = IOUtils.toByteArray(sevenZFile.getInputStream(entry));
- final byte[] secondRead = IOUtils.toByteArray(sevenZFile.getInputStream(entry));
- assertArrayEquals(firstRead, secondRead);
- }
- }
- }
-
- @Test
- public void testRetrieveInputStreamForShuffledEntries() throws IOException {
- try (final SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-348.7z"))) {
- final List<SevenZArchiveEntry> entries = (List<SevenZArchiveEntry>) sevenZFile.getEntries();
- Collections.shuffle(entries);
- for (final SevenZArchiveEntry entry : entries) {
- IOUtils.toByteArray(sevenZFile.getInputStream(entry));
- }
- }
- }
-
@Test
public void test7zDecryptUnarchive() throws Exception {
if (isStrongCryptoAvailable()) {
@@ -445,73 +181,195 @@ public class SevenZFileTest extends AbstractTestCase {
}
}
- private void test7zUnarchive(final SevenZFile sevenZFile, final SevenZMethod m) throws Exception {
- SevenZArchiveEntry entry = sevenZFile.getNextEntry();
- assertEquals("test1.xml", entry.getName());
- assertDates(entry, "2007-11-14T10:19:02Z", null, null);
- assertEquals(m, entry.getContentMethods().iterator().next().getMethod());
- entry = sevenZFile.getNextEntry();
- assertEquals("test2.xml", entry.getName());
- assertDates(entry, "2007-11-14T10:19:02Z", null, null);
- assertEquals(m, entry.getContentMethods().iterator().next().getMethod());
- final byte[] contents = new byte[(int) entry.getSize()];
- int off = 0;
- while (off < contents.length) {
- final int bytesRead = sevenZFile.read(contents, off, contents.length - off);
- assert bytesRead >= 0;
- off += bytesRead;
+ private void test7zUnarchive(final SevenZFile sevenZFile, final SevenZMethod m) throws Exception {
+ SevenZArchiveEntry entry = sevenZFile.getNextEntry();
+ assertEquals("test1.xml", entry.getName());
+ assertDates(entry, "2007-11-14T10:19:02Z", null, null);
+ assertEquals(m, entry.getContentMethods().iterator().next().getMethod());
+ entry = sevenZFile.getNextEntry();
+ assertEquals("test2.xml", entry.getName());
+ assertDates(entry, "2007-11-14T10:19:02Z", null, null);
+ assertEquals(m, entry.getContentMethods().iterator().next().getMethod());
+ final byte[] contents = new byte[(int) entry.getSize()];
+ int off = 0;
+ while (off < contents.length) {
+ final int bytesRead = sevenZFile.read(contents, off, contents.length - off);
+ assert bytesRead >= 0;
+ off += bytesRead;
+ }
+ assertEquals(TEST2_CONTENT, new String(contents, UTF_8));
+ assertNull(sevenZFile.getNextEntry());
+ }
+
+ @Test
+ public void test7zUnarchiveWithDefectHeader() throws Exception {
+ test7zUnarchive(getFile("bla.noendheaderoffset.7z"), SevenZMethod.LZMA, true);
+ }
+
+ @Test
+ public void test7zUnarchiveWithDefectHeaderFailsByDefault() throws Exception {
+ assertThrows(IOException.class, () -> test7zUnarchive(getFile("bla.noendheaderoffset.7z"), SevenZMethod.LZMA));
+ }
+
+ @Test
+ public void testAllEmptyFilesArchive() throws Exception {
+ try (SevenZFile archive = new SevenZFile(getFile("7z-empty-mhc-off.7z"))) {
+ final SevenZArchiveEntry e = archive.getNextEntry();
+ assertNotNull(e);
+ assertEquals("empty", e.getName());
+ assertDates(e, "2013-05-14T17:50:19Z", null, null);
+ assertNull(archive.getNextEntry());
+ }
+ }
+
+ /**
+ * @see "https://issues.apache.org/jira/browse/COMPRESS-256"
+ */
+ @Test
+ public void testCompressedHeaderWithNonDefaultDictionarySize() throws Exception {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-256.7z"))) {
+ int count = 0;
+ while (sevenZFile.getNextEntry() != null) {
+ count++;
+ }
+ assertEquals(446, count);
+ }
+ }
+
+ @Test
+ public void testEncryptedArchiveRequiresPassword() throws Exception {
+ final PasswordRequiredException ex = assertThrows(PasswordRequiredException.class,
+ () -> new SevenZFile(getFile("bla.encrypted.7z")).close(),
+ "shouldn't decrypt without a password");
+ final String msg = ex.getMessage();
+ assertTrue(msg.startsWith("Cannot read encrypted content from "),
+ "Should start with whining about being unable to decrypt");
+ assertTrue(msg.endsWith(" without a password."),
+ "Should finish the sentence properly");
+ assertTrue(msg.contains("bla.encrypted.7z"),
+ "Should contain archive's name");
+ }
+
+ @Test
+ public void testExtractNonExistSpecifiedFile() throws Exception {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-256.7z")); SevenZFile anotherSevenZFile = new SevenZFile(getFile("bla.7z"))) {
+ for (final SevenZArchiveEntry nonExistEntry : anotherSevenZFile.getEntries()) {
+ assertThrows(IllegalArgumentException.class, () -> sevenZFile.getInputStream(nonExistEntry));
+ }
+ }
+ }
+
+ @Test
+ public void testExtractSpecifiedFile() throws Exception {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-256.7z"))) {
+ final String testTxtContents = "111111111111111111111111111000101011\n" +
+ "111111111111111111111111111000101011\n" +
+ "111111111111111111111111111000101011\n" +
+ "111111111111111111111111111000101011\n" +
+ "111111111111111111111111111000101011\n" +
+ "111111111111111111111111111000101011\n" +
+ "111111111111111111111111111000101011\n" +
+ "111111111111111111111111111000101011\n" +
+ "111111111111111111111111111000101011\n" +
+ "111111111111111111111111111000101011";
+
+ for(final SevenZArchiveEntry entry : sevenZFile.getEntries()) {
+ if (entry.getName().equals("commons-compress-1.7-src/src/test/resources/test.txt")) {
+ final byte[] contents = new byte[(int) entry.getSize()];
+ int off = 0;
+ final InputStream inputStream = sevenZFile.getInputStream(entry);
+ while (off < contents.length) {
+ final int bytesRead = inputStream.read(contents, off, contents.length - off);
+ assert bytesRead >= 0;
+ off += bytesRead;
+ }
+ assertEquals(testTxtContents, new String(contents, UTF_8));
+ break;
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testGetDefaultNameWorksAsExpected() throws Exception {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("bla.deflate64.7z"))) {
+ assertEquals("bla.deflate64", sevenZFile.getDefaultName());
+ }
+ try (SevenZFile sevenZFile = new SevenZFile(Files.newByteChannel(getFile("bla.deflate64.7z").toPath()))) {
+ assertNull(sevenZFile.getDefaultName());
+ }
+ try (SevenZFile sevenZFile = new SevenZFile(Files.newByteChannel(getFile("bla.deflate64.7z").toPath()), "foo")) {
+ assertEquals("foo~", sevenZFile.getDefaultName());
+ }
+ try (SevenZFile sevenZFile = new SevenZFile(Files.newByteChannel(getFile("bla.deflate64.7z").toPath()), ".foo")) {
+ assertEquals(".foo~", sevenZFile.getDefaultName());
}
- assertEquals(TEST2_CONTENT, new String(contents, UTF_8));
- assertNull(sevenZFile.getNextEntry());
}
@Test
- public void test7zUnarchiveWithDefectHeader() throws Exception {
- test7zUnarchive(getFile("bla.noendheaderoffset.7z"), SevenZMethod.LZMA, true);
+ public void testGetEntriesOfUnarchiveInMemoryTest() throws IOException {
+ final byte[] data = Files.readAllBytes(getFile("bla.7z").toPath());
+ try (SevenZFile sevenZFile = new SevenZFile(new SeekableInMemoryByteChannel(data))) {
+ final Iterable<SevenZArchiveEntry> entries = sevenZFile.getEntries();
+ final Iterator<SevenZArchiveEntry> iter = entries.iterator();
+ SevenZArchiveEntry entry = iter.next();
+ assertEquals("test1.xml", entry.getName());
+ entry = iter.next();
+ assertEquals("test2.xml", entry.getName());
+ assertFalse(iter.hasNext());
+ }
}
@Test
- public void test7zUnarchiveWithDefectHeaderFailsByDefault() throws Exception {
- assertThrows(IOException.class, () -> test7zUnarchive(getFile("bla.noendheaderoffset.7z"), SevenZMethod.LZMA));
+ public void testGetEntriesOfUnarchiveTest() throws IOException {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("bla.7z"))) {
+ final Iterable<SevenZArchiveEntry> entries = sevenZFile.getEntries();
+ final Iterator<SevenZArchiveEntry> iter = entries.iterator();
+ SevenZArchiveEntry entry = iter.next();
+ assertEquals("test1.xml", entry.getName());
+ entry = iter.next();
+ assertEquals("test2.xml", entry.getName());
+ assertFalse(iter.hasNext());
+ }
}
@Test
- public void testAllEmptyFilesArchive() throws Exception {
- try (SevenZFile archive = new SevenZFile(getFile("7z-empty-mhc-off.7z"))) {
- final SevenZArchiveEntry e = archive.getNextEntry();
- assertNotNull(e);
- assertEquals("empty", e.getName());
- assertDates(e, "2013-05-14T17:50:19Z", null, null);
- assertNull(archive.getNextEntry());
+ public void testGivenNameWinsOverDefaultName() throws Exception {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("bla.7z"),
+ SevenZFileOptions.builder().withUseDefaultNameForUnnamedEntries(true).build())) {
+ SevenZArchiveEntry ae = sevenZFile.getNextEntry();
+ assertNotNull(ae);
+ assertEquals("test1.xml", ae.getName());
+ ae = sevenZFile.getNextEntry();
+ assertNotNull(ae);
+ assertEquals("test2.xml", ae.getName());
+ assertNull(sevenZFile.getNextEntry());
}
}
/**
- * @see "https://issues.apache.org/jira/browse/COMPRESS-256"
+ * @see <a href="https://issues.apache.org/jira/browse/COMPRESS-492">COMPRESS-492</a>
*/
@Test
- public void testCompressedHeaderWithNonDefaultDictionarySize() throws Exception {
- try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-256.7z"))) {
- int count = 0;
- while (sevenZFile.getNextEntry() != null) {
- count++;
- }
- assertEquals(446, count);
+ public void testHandlesEmptyArchiveWithFilesInfo() throws Exception {
+ final File f = new File(dir, "empty.7z");
+ try (SevenZOutputFile s = new SevenZOutputFile(f)) {
+ }
+ try (SevenZFile z = new SevenZFile(f)) {
+ assertFalse(z.getEntries().iterator().hasNext());
+ assertNull(z.getNextEntry());
}
}
+ /**
+ * @see <a href="https://issues.apache.org/jira/browse/COMPRESS-492">COMPRESS-492</a>
+ */
@Test
- public void testEncryptedArchiveRequiresPassword() throws Exception {
- final PasswordRequiredException ex = assertThrows(PasswordRequiredException.class,
- () -> new SevenZFile(getFile("bla.encrypted.7z")).close(),
- "shouldn't decrypt without a password");
- final String msg = ex.getMessage();
- assertTrue(msg.startsWith("Cannot read encrypted content from "),
- "Should start with whining about being unable to decrypt");
- assertTrue(msg.endsWith(" without a password."),
- "Should finish the sentence properly");
- assertTrue(msg.contains("bla.encrypted.7z"),
- "Should contain archive's name");
+ public void testHandlesEmptyArchiveWithoutFilesInfo() throws Exception {
+ try (SevenZFile z = new SevenZFile(getFile("COMPRESS-492.7z"))) {
+ assertFalse(z.getEntries().iterator().hasNext());
+ assertNull(z.getNextEntry());
+ }
}
@Test
@@ -524,6 +382,42 @@ public class SevenZFileTest extends AbstractTestCase {
checkHelloWorld("7z-hello-mhc-off-lzma2.7z");
}
+ @Test
+ public void testLimitExtractionMemory() {
+ assertThrows(MemoryLimitException.class, () -> {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("bla.7z"), SevenZFileOptions.builder().withMaxMemoryLimitInKb(1).build())) {
+ // Do nothing. Exception should be thrown
+ }
+ });
+ }
+
+ @Test
+ public void testNoNameCanBeReplacedByDefaultName() throws Exception {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("bla-nonames.7z"),
+ SevenZFileOptions.builder().withUseDefaultNameForUnnamedEntries(true).build())) {
+ SevenZArchiveEntry ae = sevenZFile.getNextEntry();
+ assertNotNull(ae);
+ assertEquals("bla-nonames", ae.getName());
+ ae = sevenZFile.getNextEntry();
+ assertNotNull(ae);
+ assertEquals("bla-nonames", ae.getName());
+ assertNull(sevenZFile.getNextEntry());
+ }
+ }
+
+ @Test
+ public void testNoNameMeansNoNameByDefault() throws Exception {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("bla-nonames.7z"))) {
+ SevenZArchiveEntry ae = sevenZFile.getNextEntry();
+ assertNotNull(ae);
+ assertNull(ae.getName());
+ ae = sevenZFile.getNextEntry();
+ assertNotNull(ae);
+ assertNull(ae.getName());
+ assertNull(sevenZFile.getNextEntry());
+ }
+ }
+
@Test
public void testNoOOMOnCorruptedHeader() throws IOException {
final List<Path> testFiles = new ArrayList<>();
@@ -583,7 +477,6 @@ public class SevenZFileTest extends AbstractTestCase {
}
}
-
@Test
public void testRandomAccessTogetherWithSequentialAccess() throws Exception {
try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-256.7z"))) {
@@ -822,6 +715,43 @@ public class SevenZFileTest extends AbstractTestCase {
}
}
+ @Test
+ public void testReadBigSevenZipFile() throws IOException {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-592.7z"))) {
+ SevenZArchiveEntry entry = sevenZFile.getNextEntry();
+ while (entry != null) {
+ if (entry.hasStream()) {
+ final byte[] content = new byte[(int) entry.getSize()];
+ sevenZFile.read(content);
+ }
+ entry = sevenZFile.getNextEntry();
+ }
+ }
+ }
+
+ /**
+ * @see "https://issues.apache.org/jira/browse/COMPRESS-348"
+ */
+ @Test
+ public void testReadEntriesOfSize0() throws IOException {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-348.7z"))) {
+ int entries = 0;
+ SevenZArchiveEntry entry = sevenZFile.getNextEntry();
+ while (entry != null) {
+ entries++;
+ final int b = sevenZFile.read();
+ if ("2.txt".equals(entry.getName()) || "5.txt".equals(entry.getName())) {
+ assertEquals(-1, b);
+ } else {
+ assertNotEquals(-1, b);
+ }
+ entry = sevenZFile.getNextEntry();
+ }
+ assertEquals(5, entries);
+ }
+ }
+
+
@Test
public void testReadingBackDeltaDistance() throws Exception {
final File output = new File(dir, "delta-distance.7z");
@@ -863,6 +793,76 @@ public class SevenZFileTest extends AbstractTestCase {
}
}
+ @Test
+ public void testReadTimesFromFile() throws IOException {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("times.7z"))) {
+ SevenZArchiveEntry entry = sevenZFile.getNextEntry();
+ assertNotNull(entry);
+ assertEquals("test", entry.getName());
+ assertTrue(entry.isDirectory());
+ assertDates(entry, "2022-03-21T14:50:46.2099751Z", "2022-03-21T14:50:46.2099751Z", "2022-03-16T10:19:24.1051115Z");
+
+ entry = sevenZFile.getNextEntry();
+ assertNotNull(entry);
+ assertEquals("test/test-times.txt", entry.getName());
+ assertFalse(entry.isDirectory());
+ assertDates(entry, "2022-03-18T10:00:15Z", "2022-03-18T10:14:37.8130002Z", "2022-03-18T10:14:37.8110032Z");
+
+ entry = sevenZFile.getNextEntry();
+ assertNotNull(entry);
+ assertEquals("test/test-times2.txt", entry.getName());
+ assertFalse(entry.isDirectory());
+ assertDates(entry, "2022-03-18T10:00:19Z", "2022-03-18T10:14:37.8170038Z", "2022-03-18T10:14:37.8140004Z");
+
+ entry = sevenZFile.getNextEntry();
+ assertNull(entry);
+ }
+ }
+
+ @Test
+ public void testRetrieveInputStreamForAllEntriesMultipleTimes() throws IOException {
+ try (SevenZFile sevenZFile = new SevenZFile(getFile("bla.7z"))) {
+ for (final SevenZArchiveEntry entry : sevenZFile.getEntries()) {
+ final byte[] firstRead = IOUtils.toByteArray(sevenZFile.getInputStream(entry));
+ final byte[] secondRead = IOUtils.toByteArray(sevenZFile.getInputStream(entry));
+ assertArrayEquals(firstRead, secondRead);
+ }
+ }
+ }
+
+ @Test
+ public void testRetrieveInputStreamForAllEntriesWithoutCRCMultipleTimes() throws IOException {
+ try (final SevenZOutputFile out = new SevenZOutputFile(new File(dir, "test.7z"))) {
+ final Path inputFile = Files.createTempFile("SevenZTestTemp", "");
+
+ final SevenZArchiveEntry entry = out.createArchiveEntry(inputFile.toFile(), "test.txt");
+ out.putArchiveEntry(entry);
+ out.write("Test".getBytes(UTF_8));
+ out.closeArchiveEntry();
+
+ Files.deleteIfExists(inputFile);
+ }
+
+ try (SevenZFile sevenZFile = new SevenZFile(new File(dir, "test.7z"))) {
+ for (final SevenZArchiveEntry entry : sevenZFile.getEntries()) {
+ final byte[] firstRead = IOUtils.toByteArray(sevenZFile.getInputStream(entry));
+ final byte[] secondRead = IOUtils.toByteArray(sevenZFile.getInputStream(entry));
+ assertArrayEquals(firstRead, secondRead);
+ }
+ }
+ }
+
+ @Test
+ public void testRetrieveInputStreamForShuffledEntries() throws IOException {
+ try (final SevenZFile sevenZFile = new SevenZFile(getFile("COMPRESS-348.7z"))) {
+ final List<SevenZArchiveEntry> entries = (List<SevenZArchiveEntry>) sevenZFile.getEntries();
+ Collections.shuffle(entries);
+ for (final SevenZArchiveEntry entry : entries) {
+ IOUtils.toByteArray(sevenZFile.getInputStream(entry));
+ }
+ }
+ }
+
@Test
public void testSevenZWithEOS() throws IOException {
try(final SevenZFile sevenZFile = new SevenZFile(getFile("lzma-with-eos.7z"))) {
diff --git a/src/test/java/org/apache/commons/compress/archivers/tar/BigFilesIT.java b/src/test/java/org/apache/commons/compress/archivers/tar/BigFilesIT.java
index 3be814aa..007becb7 100644
--- a/src/test/java/org/apache/commons/compress/archivers/tar/BigFilesIT.java
+++ b/src/test/java/org/apache/commons/compress/archivers/tar/BigFilesIT.java
@@ -61,6 +61,22 @@ public class BigFilesIT extends AbstractTestCase {
}
}
+ @Test
+ public void tarFileReadFileHeadersOfArchiveBiggerThan8GByte() throws Exception {
+ final Path file = getPath("8.posix.tar.gz");
+ final Path output = resultDir.toPath().resolve("8.posix.tar");
+ try (InputStream in = new BufferedInputStream(Files.newInputStream(file));
+ GzipCompressorInputStream gzin = new GzipCompressorInputStream(in)) {
+ Files.copy(gzin, output, StandardCopyOption.REPLACE_EXISTING);
+ }
+
+ try (final TarFile tarFile = new TarFile(output)) {
+ final List<TarArchiveEntry> entries = tarFile.getEntries();
+ assertEquals(1, entries.size());
+ assertNotNull(entries.get(0));
+ }
+ }
+
@Test
public void testReadFileBiggerThan8GBytePosix() throws Exception {
readFileBiggerThan8GByte("8.posix.tar.gz");
@@ -82,20 +98,4 @@ public class BigFilesIT extends AbstractTestCase {
}
}
- @Test
- public void tarFileReadFileHeadersOfArchiveBiggerThan8GByte() throws Exception {
- final Path file = getPath("8.posix.tar.gz");
- final Path output = resultDir.toPath().resolve("8.posix.tar");
- try (InputStream in = new BufferedInputStream(Files.newInputStream(file));
- GzipCompressorInputStream gzin = new GzipCompressorInputStream(in)) {
- Files.copy(gzin, output, StandardCopyOption.REPLACE_EXISTING);
- }
-
- try (final TarFile tarFile = new TarFile(output)) {
- final List<TarArchiveEntry> entries = tarFile.getEntries();
- assertEquals(1, entries.size());
- assertNotNull(entries.get(0));
- }
- }
-
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/tar/SparseFilesTest.java b/src/test/java/org/apache/commons/compress/archivers/tar/SparseFilesTest.java
index 076ca2ad..cdae0cb8 100644
--- a/src/test/java/org/apache/commons/compress/archivers/tar/SparseFilesTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/tar/SparseFilesTest.java
@@ -83,16 +83,6 @@ public class SparseFilesTest extends AbstractTestCase {
assertEquals(0, sparseHeaders.get(2).getNumbytes());
}
- @Test
- public void testCompareTarArchiveInputStreamWithTarFile() throws IOException {
- final Path file = getPath("oldgnu_sparse.tar");
- try (TarArchiveInputStream tarIn = new TarArchiveInputStream(new BufferedInputStream(Files.newInputStream(file)));
- TarFile tarFile = new TarFile(file)) {
- final TarArchiveEntry tarInEntry = tarIn.getNextTarEntry();
- assertArrayEquals(IOUtils.toByteArray(tarIn), IOUtils.toByteArray(tarFile.getInputStream(tarFile.getEntries().get(0))));
- }
- }
-
private InputStream extractTarAndGetInputStream(final File tarFile, final String sparseFileName) throws IOException, InterruptedException {
final ProcessBuilder pb = new ProcessBuilder("tar", "-xf", tarFile.getPath(), "-C", resultDir.getPath());
pb.redirectErrorStream(true);
@@ -117,6 +107,16 @@ public class SparseFilesTest extends AbstractTestCase {
return new String(IOUtils.toByteArray(process.getInputStream()));
}
+ @Test
+ public void testCompareTarArchiveInputStreamWithTarFile() throws IOException {
+ final Path file = getPath("oldgnu_sparse.tar");
+ try (TarArchiveInputStream tarIn = new TarArchiveInputStream(new BufferedInputStream(Files.newInputStream(file)));
+ TarFile tarFile = new TarFile(file)) {
+ final TarArchiveEntry tarInEntry = tarIn.getNextTarEntry();
+ assertArrayEquals(IOUtils.toByteArray(tarIn), IOUtils.toByteArray(tarFile.getInputStream(tarFile.getEntries().get(0))));
+ }
+ }
+
@Test
@DisabledOnOs(OS.WINDOWS)
public void testExtractExtendedOldGNU() throws IOException, InterruptedException {
diff --git a/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveEntryTest.java b/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveEntryTest.java
index 2bf55bb0..57675e1e 100644
--- a/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveEntryTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveEntryTest.java
@@ -72,6 +72,60 @@ public class TarArchiveEntryTest implements TarConstants {
return entry;
}
+ private String readMagic(final TarArchiveEntry t) {
+ final byte[] buf = new byte[512];
+ t.writeEntryHeader(buf);
+ return new String(buf, MAGIC_OFFSET, MAGICLEN + VERSIONLEN);
+ }
+
+ @Test
+ public void testExtraPaxHeaders() throws IOException {
+ final ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos);
+
+ TarArchiveEntry entry = new TarArchiveEntry("./weasels");
+ entry.addPaxHeader("APACHE.mustelida", "true");
+ entry.addPaxHeader("SCHILY.xattr.user.org.apache.weasels", "maximum weasels");
+ entry.addPaxHeader("size", "1");
+ assertEquals(2, entry.getExtraPaxHeaders().size(), "extra header count");
+ assertEquals("true", entry.getExtraPaxHeader("APACHE.mustelida"), "APACHE.mustelida");
+ assertEquals("maximum weasels", entry.getExtraPaxHeader("SCHILY.xattr.user.org.apache.weasels"), "SCHILY.xattr.user.org.apache.weasels");
+ assertEquals(entry.getSize(), 1, "size");
+
+ tos.putArchiveEntry(entry);
+ tos.write('W');
+ tos.closeArchiveEntry();
+ tos.close();
+ assertNotEquals(0, entry.getExtraPaxHeaders().size(), "should have extra headers before clear");
+ entry.clearExtraPaxHeaders();
+ assertEquals(0, entry.getExtraPaxHeaders().size(), "extra headers should be empty after clear");
+ final TarArchiveInputStream tis = new TarArchiveInputStream(new ByteArrayInputStream(bos.toByteArray()));
+ entry = tis.getNextTarEntry();
+ assertNotNull(entry, "couldn't get entry");
+
+ assertEquals(2, entry.getExtraPaxHeaders().size(), "extra header count");
+ assertEquals("true", entry.getExtraPaxHeader("APACHE.mustelida"), "APACHE.mustelida");
+ assertEquals("maximum weasels", entry.getExtraPaxHeader("SCHILY.xattr.user.org.apache.weasels"), "user.org.apache.weasels");
+
+ assertEquals('W', tis.read());
+ assertTrue(tis.read() < 0, "should be at end of entry");
+
+ assertNull(tis.getNextTarEntry(), "should be at end of file");
+ tis.close();
+ }
+
+ /**
+ * JIRA issue SANDBOX-284
+ *
+ * @see "https://issues.apache.org/jira/browse/SANDBOX-284"
+ */
+ @Test
+ public void testFileSystemRoot() {
+ final TarArchiveEntry t = new TarArchiveEntry(new File(ROOT));
+ assertEquals("/", t.getName());
+ assertEquals(TarConstants.LF_DIR, t.getLinkFlag());
+ }
+
@Test
public void testGetFileFromNonFileEntry() {
final TarArchiveEntry entry = new TarArchiveEntry("test.txt");
@@ -117,6 +171,59 @@ public class TarArchiveEntryTest implements TarConstants {
assertEquals(20, strs.get(2).getOffset());
}
+ @Test
+ public void testLinkFlagConstructor() {
+ final TarArchiveEntry t = new TarArchiveEntry("/foo", LF_GNUTYPE_LONGNAME);
+ assertGnuMagic(t);
+ assertEquals("foo", t.getName());
+ assertEquals(TarConstants.LF_GNUTYPE_LONGNAME, t.getLinkFlag());
+ }
+
+ @Test
+ public void testLinkFlagConstructorWithFileFlag() {
+ final TarArchiveEntry t = new TarArchiveEntry("/foo", LF_NORMAL);
+ assertPosixMagic(t);
+ assertEquals("foo", t.getName());
+ assertEquals(TarConstants.LF_NORMAL, t.getLinkFlag());
+ }
+
+ @Test
+ public void testLinkFlagConstructorWithPreserve() {
+ final TarArchiveEntry t = new TarArchiveEntry("/foo", LF_GNUTYPE_LONGNAME,
+ true);
+ assertGnuMagic(t);
+ assertEquals("/foo", t.getName());
+ assertEquals(TarConstants.LF_GNUTYPE_LONGNAME, t.getLinkFlag());
+ }
+
+ @Test
+ @EnabledOnOs(org.junit.jupiter.api.condition.OS.LINUX)
+ public void testLinuxFileInformationFromFile() throws IOException {
+ final TarArchiveEntry entry = new TarArchiveEntry(getFile("test1.xml"));
+ assertNotEquals(0, entry.getLongUserId());
+ assertNotEquals(0, entry.getLongGroupId());
+ assertNotEquals("", entry.getUserName());
+ }
+
+ @Test
+ @EnabledOnOs(org.junit.jupiter.api.condition.OS.LINUX)
+ public void testLinuxFileInformationFromPath() throws IOException {
+ final TarArchiveEntry entry = new TarArchiveEntry(getPath("test1.xml"));
+ assertNotEquals(0, entry.getLongUserId());
+ assertNotEquals(0, entry.getLongGroupId());
+ assertNotEquals("", entry.getUserName());
+ }
+
+ @Test
+ public void testMaxFileSize(){
+ final TarArchiveEntry t = new TarArchiveEntry("");
+ t.setSize(0);
+ t.setSize(1);
+ assertThrows(IllegalArgumentException.class, () -> t.setSize(-1));
+ t.setSize(077777777777L);
+ t.setSize(0100000000000L);
+ }
+
@Test
public void testNegativeOffsetInConstructorNotAllowed() {
// @formatter:off
@@ -149,6 +256,29 @@ public class TarArchiveEntryTest implements TarConstants {
assertThrows(IllegalArgumentException.class, () -> new TarArchiveEntry("test").setDataOffset(-1));
}
+ @Test
+ public void testPaxTimeFieldsForInvalidValues() {
+ final String[] headerNames = { "LIBARCHIVE.creationtime", "atime", "mtime", "ctime" };
+ // @formatter:off
+ final String[] testValues = {
+ // Generate a number with a very large integer or fractional component
+ new Random().nextLong() + "." + String.join("",
+ Collections.nCopies(15000, String.valueOf(Long.MAX_VALUE))),
+ // These two examples use the exponent notation
+ "9e9999999",
+ "9E9999999"
+ };
+ // @formatter:on
+
+ final TarArchiveEntry entry = new TarArchiveEntry("test.txt");
+ for (String name : headerNames) {
+ for (String value : testValues) {
+ final Exception exp = assertThrows(IllegalArgumentException.class, () -> entry.addPaxHeader(name, value));
+ assert exp.getCause().getMessage().startsWith("Corrupted PAX header. Time field value is invalid");
+ }
+ }
+ }
+
@Test
public void testPreservesDriveSpecOnWindowsAndNetwareIfAskedTo() {
assumeTrue("C:\\".equals(ROOT));
@@ -160,12 +290,6 @@ public class TarArchiveEntryTest implements TarConstants {
assertEquals(TarConstants.LF_GNUTYPE_LONGNAME, t.getLinkFlag());
}
- private String readMagic(final TarArchiveEntry t) {
- final byte[] buf = new byte[512];
- t.writeEntryHeader(buf);
- return new String(buf, MAGIC_OFFSET, MAGICLEN + VERSIONLEN);
- }
-
@Test
public void testShouldNotWriteTimePaxHeadersByDefault() throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
@@ -306,130 +430,6 @@ public class TarArchiveEntryTest implements TarConstants {
}
}
- @Test
- public void testExtraPaxHeaders() throws IOException {
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos);
-
- TarArchiveEntry entry = new TarArchiveEntry("./weasels");
- entry.addPaxHeader("APACHE.mustelida", "true");
- entry.addPaxHeader("SCHILY.xattr.user.org.apache.weasels", "maximum weasels");
- entry.addPaxHeader("size", "1");
- assertEquals(2, entry.getExtraPaxHeaders().size(), "extra header count");
- assertEquals("true", entry.getExtraPaxHeader("APACHE.mustelida"), "APACHE.mustelida");
- assertEquals("maximum weasels", entry.getExtraPaxHeader("SCHILY.xattr.user.org.apache.weasels"), "SCHILY.xattr.user.org.apache.weasels");
- assertEquals(entry.getSize(), 1, "size");
-
- tos.putArchiveEntry(entry);
- tos.write('W');
- tos.closeArchiveEntry();
- tos.close();
- assertNotEquals(0, entry.getExtraPaxHeaders().size(), "should have extra headers before clear");
- entry.clearExtraPaxHeaders();
- assertEquals(0, entry.getExtraPaxHeaders().size(), "extra headers should be empty after clear");
- final TarArchiveInputStream tis = new TarArchiveInputStream(new ByteArrayInputStream(bos.toByteArray()));
- entry = tis.getNextTarEntry();
- assertNotNull(entry, "couldn't get entry");
-
- assertEquals(2, entry.getExtraPaxHeaders().size(), "extra header count");
- assertEquals("true", entry.getExtraPaxHeader("APACHE.mustelida"), "APACHE.mustelida");
- assertEquals("maximum weasels", entry.getExtraPaxHeader("SCHILY.xattr.user.org.apache.weasels"), "user.org.apache.weasels");
-
- assertEquals('W', tis.read());
- assertTrue(tis.read() < 0, "should be at end of entry");
-
- assertNull(tis.getNextTarEntry(), "should be at end of file");
- tis.close();
- }
-
- /**
- * JIRA issue SANDBOX-284
- *
- * @see "https://issues.apache.org/jira/browse/SANDBOX-284"
- */
- @Test
- public void testFileSystemRoot() {
- final TarArchiveEntry t = new TarArchiveEntry(new File(ROOT));
- assertEquals("/", t.getName());
- assertEquals(TarConstants.LF_DIR, t.getLinkFlag());
- }
-
- @Test
- public void testLinkFlagConstructor() {
- final TarArchiveEntry t = new TarArchiveEntry("/foo", LF_GNUTYPE_LONGNAME);
- assertGnuMagic(t);
- assertEquals("foo", t.getName());
- assertEquals(TarConstants.LF_GNUTYPE_LONGNAME, t.getLinkFlag());
- }
-
- @Test
- public void testLinkFlagConstructorWithFileFlag() {
- final TarArchiveEntry t = new TarArchiveEntry("/foo", LF_NORMAL);
- assertPosixMagic(t);
- assertEquals("foo", t.getName());
- assertEquals(TarConstants.LF_NORMAL, t.getLinkFlag());
- }
-
- @Test
- public void testLinkFlagConstructorWithPreserve() {
- final TarArchiveEntry t = new TarArchiveEntry("/foo", LF_GNUTYPE_LONGNAME,
- true);
- assertGnuMagic(t);
- assertEquals("/foo", t.getName());
- assertEquals(TarConstants.LF_GNUTYPE_LONGNAME, t.getLinkFlag());
- }
-
- @Test
- @EnabledOnOs(org.junit.jupiter.api.condition.OS.LINUX)
- public void testLinuxFileInformationFromFile() throws IOException {
- final TarArchiveEntry entry = new TarArchiveEntry(getFile("test1.xml"));
- assertNotEquals(0, entry.getLongUserId());
- assertNotEquals(0, entry.getLongGroupId());
- assertNotEquals("", entry.getUserName());
- }
-
- @Test
- @EnabledOnOs(org.junit.jupiter.api.condition.OS.LINUX)
- public void testLinuxFileInformationFromPath() throws IOException {
- final TarArchiveEntry entry = new TarArchiveEntry(getPath("test1.xml"));
- assertNotEquals(0, entry.getLongUserId());
- assertNotEquals(0, entry.getLongGroupId());
- assertNotEquals("", entry.getUserName());
- }
-
- @Test
- public void testMaxFileSize(){
- final TarArchiveEntry t = new TarArchiveEntry("");
- t.setSize(0);
- t.setSize(1);
- assertThrows(IllegalArgumentException.class, () -> t.setSize(-1));
- t.setSize(077777777777L);
- t.setSize(0100000000000L);
- }
-
- @Test
- public void testPaxTimeFieldsForInvalidValues() {
- final String[] headerNames = { "LIBARCHIVE.creationtime", "atime", "mtime", "ctime" };
- // @formatter:off
- final String[] testValues = {
- // Generate a number with a very large integer or fractional component
- new Random().nextLong() + "." + String.join("",
- Collections.nCopies(15000, String.valueOf(Long.MAX_VALUE))),
- // These two examples use the exponent notation
- "9e9999999",
- "9E9999999"
- };
- // @formatter:on
-
- final TarArchiveEntry entry = new TarArchiveEntry("test.txt");
- for (String name : headerNames) {
- for (String value : testValues) {
- final Exception exp = assertThrows(IllegalArgumentException.class, () -> entry.addPaxHeader(name, value));
- assert exp.getCause().getMessage().startsWith("Corrupted PAX header. Time field value is invalid");
- }
- }
- }
-
@Test
public void testTarFileWithFSRoot() throws IOException {
final File f = File.createTempFile("taetest", ".tar");
diff --git a/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java b/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
index 65442df1..24601544 100644
--- a/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java
@@ -62,28 +62,140 @@ public class TarArchiveInputStreamTest extends AbstractTestCase {
}
}
+ private void getNextEntryUntilIOException(final TarArchiveInputStream archive) {
+ assertThrows(IOException.class, () -> {
+ while (archive.getNextTarEntry() != null) {
+ // noop
+ }
+ });
+ }
+
+
+ private TarArchiveInputStream getTestStream(final String name) {
+ return new TarArchiveInputStream(
+ TarArchiveInputStreamTest.class.getResourceAsStream(name));
+ }
+
+ @Test
+ public void testCompress197() {
+ try (TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar")) {
+ TarArchiveEntry entry = tar.getNextTarEntry();
+ while (entry != null) {
+ entry = tar.getNextTarEntry();
+ }
+ } catch (final IOException e) {
+ fail("COMPRESS-197: " + e.getMessage());
+ }
+ }
+
+ @Test
+ public void testCompress558() throws IOException {
+ final String folderName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/";
+ final String consumerJavaName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/java/example/queue/exclusive/Consumer.java";
+ final String producerJavaName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/java/example/queue/exclusive/Producer.java";
+
+ final ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ try (final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos)) {
+ tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
+ final TarArchiveEntry rootfolder = new TarArchiveEntry(folderName);
+ tos.putArchiveEntry(rootfolder);
+ final TarArchiveEntry consumerJava = new TarArchiveEntry(consumerJavaName);
+ tos.putArchiveEntry(consumerJava);
+ final TarArchiveEntry producerJava = new TarArchiveEntry(producerJavaName);
+ tos.putArchiveEntry(producerJava);
+ tos.closeArchiveEntry();
+ }
+ final byte[] data = bos.toByteArray();
+ try (final ByteArrayInputStream bis = new ByteArrayInputStream(data);
+ final TarArchiveInputStream tis = new TarArchiveInputStream(bis)) {
+ assertEquals(folderName, tis.getNextTarEntry().getName());
+ assertEquals(TarConstants.LF_DIR, tis.getCurrentEntry().getLinkFlag());
+ assertEquals(consumerJavaName, tis.getNextTarEntry().getName());
+ assertEquals(TarConstants.LF_NORMAL, tis.getCurrentEntry().getLinkFlag());
+ assertEquals(producerJavaName, tis.getNextTarEntry().getName());
+ assertEquals(TarConstants.LF_NORMAL, tis.getCurrentEntry().getLinkFlag());
+ }
+ }
+
@Test
public void testDatePriorToEpochInGNUFormat() throws Exception {
datePriorToEpoch("preepoch-star.tar");
}
-
@Test
public void testDatePriorToEpochInPAXFormat() throws Exception {
datePriorToEpoch("preepoch-posix.tar");
}
- private void getNextEntryUntilIOException(final TarArchiveInputStream archive) {
- assertThrows(IOException.class, () -> {
- while (archive.getNextTarEntry() != null) {
- // noop
+ @Test
+ public void testDirectoryWithLongNameEndsWithSlash() throws IOException, ArchiveException {
+ final String rootPath = dir.getAbsolutePath();
+ final String dirDirectory = "COMPRESS-509";
+ final int count = 100;
+ final File root = new File(rootPath + "/" + dirDirectory);
+ root.mkdirs();
+ for (int i = 1; i < count; i++) {
+ // -----------------------
+ // create empty dirs with incremental length
+ // -----------------------
+ String subDir = "";
+ for (int j = 0; j < i; j++) {
+ subDir += "a";
}
- });
+ final File dir = new File(rootPath + "/" + dirDirectory, "/" + subDir);
+ dir.mkdir();
+
+ // -----------------------
+ // tar these dirs
+ // -----------------------
+ final String fileName = "/" + dirDirectory + "/" + subDir;
+ final File tarF = new File(rootPath + "/tar" + i + ".tar");
+ try (final OutputStream dest = Files.newOutputStream(tarF.toPath())) {
+ final TarArchiveOutputStream out = new TarArchiveOutputStream(new BufferedOutputStream(dest));
+ out.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
+ out.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
+
+ final File file = new File(rootPath, fileName);
+ final TarArchiveEntry entry = new TarArchiveEntry(file);
+ entry.setName(fileName);
+ out.putArchiveEntry(entry);
+ out.closeArchiveEntry();
+ out.flush();
+ }
+
+ // -----------------------
+ // untar these tars
+ // -----------------------
+ try (final InputStream is = Files.newInputStream(tarF.toPath());
+ final TarArchiveInputStream debInputStream = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("tar", is)) {
+ TarArchiveEntry outEntry;
+ while ((outEntry = debInputStream.getNextEntry()) != null) {
+ assertTrue(outEntry.getName().endsWith("/"), outEntry.getName());
+ }
+ }
+ }
}
- private TarArchiveInputStream getTestStream(final String name) {
- return new TarArchiveInputStream(
- TarArchiveInputStreamTest.class.getResourceAsStream(name));
+ @Test
+ public void testGetAndSetOfPaxEntry() throws Exception {
+ try (TarArchiveInputStream is = getTestStream("/COMPRESS-356.tar")) {
+ final TarArchiveEntry entry = is.getNextTarEntry();
+ assertEquals("package/package.json", entry.getName());
+ assertEquals(TarConstants.LF_NORMAL, entry.getLinkFlag());
+ assertEquals(is.getCurrentEntry(), entry);
+ final TarArchiveEntry weaselEntry = new TarArchiveEntry(entry.getName());
+ weaselEntry.setSize(entry.getSize());
+ is.setCurrentEntry(weaselEntry);
+ assertEquals(entry, is.getCurrentEntry());
+ assertNotSame(entry, is.getCurrentEntry());
+ assertSame(weaselEntry, is.getCurrentEntry());
+ assertThrows(IllegalStateException.class, () -> {
+ is.setCurrentEntry(null);
+ is.read();
+ }, "should abort because current entry is nulled");
+ is.setCurrentEntry(entry);
+ is.read();
+ }
}
@Test
@@ -98,6 +210,37 @@ public class TarArchiveInputStreamTest extends AbstractTestCase {
}
}
+ @Test
+ public void testParseTarTruncatedInContent() throws IOException {
+ try (InputStream in = newInputStream("COMPRESS-544_truncated_in_content.tar");
+ TarArchiveInputStream archive = new TarArchiveInputStream(in)) {
+ getNextEntryUntilIOException(archive);
+ }
+ }
+
+ @Test
+ public void testParseTarTruncatedInPadding() throws IOException {
+ try (InputStream in = newInputStream("COMPRESS-544_truncated_in_padding.tar");
+ TarArchiveInputStream archive = new TarArchiveInputStream(in)) {
+ getNextEntryUntilIOException(archive);
+ }
+ }
+
+ @Test
+ public void testParseTarWithNonNumberPaxHeaders() throws IOException {
+ try (InputStream in = newInputStream("COMPRESS-529.tar"); TarArchiveInputStream archive = new TarArchiveInputStream(in)) {
+ assertThrows(IOException.class, () -> archive.getNextEntry());
+ }
+ }
+ @Test
+ public void testParseTarWithSpecialPaxHeaders() throws IOException {
+ try (InputStream in = newInputStream("COMPRESS-530.tar");
+ TarArchiveInputStream archive = new TarArchiveInputStream(in)) {
+ assertThrows(IOException.class, () -> archive.getNextEntry());
+ assertThrows(IOException.class, () -> IOUtils.toByteArray(archive));
+ }
+ }
+
@Test
public void testReadsArchiveCompletely_COMPRESS245() {
try (InputStream is = TarArchiveInputStreamTest.class.getResourceAsStream("/COMPRESS-245.tar.gz")) {
@@ -216,6 +359,7 @@ public class TarArchiveInputStreamTest extends AbstractTestCase {
assertEquals(name, t.getName());
}
}
+
@Test
public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
try (InputStream in = newInputStream("bla.tar");
@@ -267,150 +411,6 @@ public class TarArchiveInputStreamTest extends AbstractTestCase {
}
}
- @Test
- public void testCompress197() {
- try (TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar")) {
- TarArchiveEntry entry = tar.getNextTarEntry();
- while (entry != null) {
- entry = tar.getNextTarEntry();
- }
- } catch (final IOException e) {
- fail("COMPRESS-197: " + e.getMessage());
- }
- }
-
- @Test
- public void testCompress558() throws IOException {
- final String folderName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/";
- final String consumerJavaName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/java/example/queue/exclusive/Consumer.java";
- final String producerJavaName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/java/example/queue/exclusive/Producer.java";
-
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- try (final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos)) {
- tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
- final TarArchiveEntry rootfolder = new TarArchiveEntry(folderName);
- tos.putArchiveEntry(rootfolder);
- final TarArchiveEntry consumerJava = new TarArchiveEntry(consumerJavaName);
- tos.putArchiveEntry(consumerJava);
- final TarArchiveEntry producerJava = new TarArchiveEntry(producerJavaName);
- tos.putArchiveEntry(producerJava);
- tos.closeArchiveEntry();
- }
- final byte[] data = bos.toByteArray();
- try (final ByteArrayInputStream bis = new ByteArrayInputStream(data);
- final TarArchiveInputStream tis = new TarArchiveInputStream(bis)) {
- assertEquals(folderName, tis.getNextTarEntry().getName());
- assertEquals(TarConstants.LF_DIR, tis.getCurrentEntry().getLinkFlag());
- assertEquals(consumerJavaName, tis.getNextTarEntry().getName());
- assertEquals(TarConstants.LF_NORMAL, tis.getCurrentEntry().getLinkFlag());
- assertEquals(producerJavaName, tis.getNextTarEntry().getName());
- assertEquals(TarConstants.LF_NORMAL, tis.getCurrentEntry().getLinkFlag());
- }
- }
-
- @Test
- public void testDirectoryWithLongNameEndsWithSlash() throws IOException, ArchiveException {
- final String rootPath = dir.getAbsolutePath();
- final String dirDirectory = "COMPRESS-509";
- final int count = 100;
- final File root = new File(rootPath + "/" + dirDirectory);
- root.mkdirs();
- for (int i = 1; i < count; i++) {
- // -----------------------
- // create empty dirs with incremental length
- // -----------------------
- String subDir = "";
- for (int j = 0; j < i; j++) {
- subDir += "a";
- }
- final File dir = new File(rootPath + "/" + dirDirectory, "/" + subDir);
- dir.mkdir();
-
- // -----------------------
- // tar these dirs
- // -----------------------
- final String fileName = "/" + dirDirectory + "/" + subDir;
- final File tarF = new File(rootPath + "/tar" + i + ".tar");
- try (final OutputStream dest = Files.newOutputStream(tarF.toPath())) {
- final TarArchiveOutputStream out = new TarArchiveOutputStream(new BufferedOutputStream(dest));
- out.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
- out.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
-
- final File file = new File(rootPath, fileName);
- final TarArchiveEntry entry = new TarArchiveEntry(file);
- entry.setName(fileName);
- out.putArchiveEntry(entry);
- out.closeArchiveEntry();
- out.flush();
- }
-
- // -----------------------
- // untar these tars
- // -----------------------
- try (final InputStream is = Files.newInputStream(tarF.toPath());
- final TarArchiveInputStream debInputStream = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("tar", is)) {
- TarArchiveEntry outEntry;
- while ((outEntry = debInputStream.getNextEntry()) != null) {
- assertTrue(outEntry.getName().endsWith("/"), outEntry.getName());
- }
- }
- }
- }
-
- @Test
- public void testGetAndSetOfPaxEntry() throws Exception {
- try (TarArchiveInputStream is = getTestStream("/COMPRESS-356.tar")) {
- final TarArchiveEntry entry = is.getNextTarEntry();
- assertEquals("package/package.json", entry.getName());
- assertEquals(TarConstants.LF_NORMAL, entry.getLinkFlag());
- assertEquals(is.getCurrentEntry(), entry);
- final TarArchiveEntry weaselEntry = new TarArchiveEntry(entry.getName());
- weaselEntry.setSize(entry.getSize());
- is.setCurrentEntry(weaselEntry);
- assertEquals(entry, is.getCurrentEntry());
- assertNotSame(entry, is.getCurrentEntry());
- assertSame(weaselEntry, is.getCurrentEntry());
- assertThrows(IllegalStateException.class, () -> {
- is.setCurrentEntry(null);
- is.read();
- }, "should abort because current entry is nulled");
- is.setCurrentEntry(entry);
- is.read();
- }
- }
-
- @Test
- public void testParseTarTruncatedInContent() throws IOException {
- try (InputStream in = newInputStream("COMPRESS-544_truncated_in_content.tar");
- TarArchiveInputStream archive = new TarArchiveInputStream(in)) {
- getNextEntryUntilIOException(archive);
- }
- }
-
- @Test
- public void testParseTarTruncatedInPadding() throws IOException {
- try (InputStream in = newInputStream("COMPRESS-544_truncated_in_padding.tar");
- TarArchiveInputStream archive = new TarArchiveInputStream(in)) {
- getNextEntryUntilIOException(archive);
- }
- }
-
- @Test
- public void testParseTarWithNonNumberPaxHeaders() throws IOException {
- try (InputStream in = newInputStream("COMPRESS-529.tar"); TarArchiveInputStream archive = new TarArchiveInputStream(in)) {
- assertThrows(IOException.class, () -> archive.getNextEntry());
- }
- }
-
- @Test
- public void testParseTarWithSpecialPaxHeaders() throws IOException {
- try (InputStream in = newInputStream("COMPRESS-530.tar");
- TarArchiveInputStream archive = new TarArchiveInputStream(in)) {
- assertThrows(IOException.class, () -> archive.getNextEntry());
- assertThrows(IOException.class, () -> IOUtils.toByteArray(archive));
- }
- }
-
@Test
public void testThrowException() throws IOException {
try (InputStream in = newInputStream("COMPRESS-553.tar");
diff --git a/src/test/java/org/apache/commons/compress/archivers/tar/TarFileTest.java b/src/test/java/org/apache/commons/compress/archivers/tar/TarFileTest.java
index 6def3bf9..b4f506fb 100644
--- a/src/test/java/org/apache/commons/compress/archivers/tar/TarFileTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/tar/TarFileTest.java
@@ -44,6 +44,19 @@ import org.junit.jupiter.api.Test;
public class TarFileTest extends AbstractTestCase {
+ private void datePriorToEpoch(final String archive) throws Exception {
+ try (final TarFile tarFile = new TarFile(getPath(archive))) {
+ final TarArchiveEntry entry = tarFile.getEntries().get(0);
+ assertEquals("foo", entry.getName());
+ assertEquals(TarConstants.LF_NORMAL, entry.getLinkFlag());
+ final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+ cal.set(1969, 11, 31, 23, 59, 59);
+ cal.set(Calendar.MILLISECOND, 0);
+ assertEquals(cal.getTime(), entry.getLastModifiedDate());
+ assertTrue(entry.isCheckSumOK());
+ }
+ }
+
/**
* This test ensures the implementation is reading the padded last block if a tool has added one to an archive
*/
@@ -58,16 +71,39 @@ public class TarFileTest extends AbstractTestCase {
}
}
- private void datePriorToEpoch(final String archive) throws Exception {
- try (final TarFile tarFile = new TarFile(getPath(archive))) {
- final TarArchiveEntry entry = tarFile.getEntries().get(0);
- assertEquals("foo", entry.getName());
- assertEquals(TarConstants.LF_NORMAL, entry.getLinkFlag());
- final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
- cal.set(1969, 11, 31, 23, 59, 59);
- cal.set(Calendar.MILLISECOND, 0);
- assertEquals(cal.getTime(), entry.getLastModifiedDate());
- assertTrue(entry.isCheckSumOK());
+ @Test
+ public void testCompress197() throws IOException {
+ try (final TarFile tarFile = new TarFile(getPath("COMPRESS-197.tar"))) {
+ // noop
+ }
+ }
+
+ @Test
+ public void testCompress558() throws IOException {
+ final String folderName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/";
+ final String consumerJavaName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/java/example/queue/exclusive/Consumer.java";
+ final String producerJavaName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/java/example/queue/exclusive/Producer.java";
+
+ final ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ try (final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos)) {
+ tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
+ final TarArchiveEntry rootfolder = new TarArchiveEntry(folderName);
+ tos.putArchiveEntry(rootfolder);
+ final TarArchiveEntry consumerJava = new TarArchiveEntry(consumerJavaName);
+ tos.putArchiveEntry(consumerJava);
+ final TarArchiveEntry producerJava = new TarArchiveEntry(producerJavaName);
+ tos.putArchiveEntry(producerJava);
+ tos.closeArchiveEntry();
+ }
+ final byte[] data = bos.toByteArray();
+ try (final TarFile tarFile = new TarFile(data)) {
+ final List<TarArchiveEntry> entries = tarFile.getEntries();
+ assertEquals(folderName, entries.get(0).getName());
+ assertEquals(TarConstants.LF_DIR, entries.get(0).getLinkFlag());
+ assertEquals(consumerJavaName, entries.get(1).getName());
+ assertEquals(TarConstants.LF_NORMAL, entries.get(1).getLinkFlag());
+ assertEquals(producerJavaName, entries.get(2).getName());
+ assertEquals(TarConstants.LF_NORMAL, entries.get(2).getLinkFlag());
}
}
@@ -81,6 +117,53 @@ public class TarFileTest extends AbstractTestCase {
datePriorToEpoch("preepoch-posix.tar");
}
+ @Test
+ public void testDirectoryWithLongNameEndsWithSlash() throws IOException {
+ final String rootPath = dir.getAbsolutePath();
+ final String dirDirectory = "COMPRESS-509";
+ final int count = 100;
+ final File root = new File(rootPath + "/" + dirDirectory);
+ root.mkdirs();
+ for (int i = 1; i < count; i++) {
+ // -----------------------
+ // create empty dirs with incremental length
+ // -----------------------
+ final StringBuilder subDirBuilder = new StringBuilder();
+ for (int j = 0; j < i; j++) {
+ subDirBuilder.append("a");
+ }
+ final String subDir = subDirBuilder.toString();
+ final File dir = new File(rootPath + "/" + dirDirectory, "/" + subDir);
+ dir.mkdir();
+
+ // -----------------------
+ // tar these dirs
+ // -----------------------
+ final String fileName = "/" + dirDirectory + "/" + subDir;
+ final File tarF = new File(rootPath + "/tar" + i + ".tar");
+ try (OutputStream dest = Files.newOutputStream(tarF.toPath());
+ TarArchiveOutputStream out = new TarArchiveOutputStream(new BufferedOutputStream(dest))) {
+ out.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
+ out.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
+
+ final File file = new File(rootPath, fileName);
+ final TarArchiveEntry entry = new TarArchiveEntry(file);
+ entry.setName(fileName);
+ out.putArchiveEntry(entry);
+ out.closeArchiveEntry();
+ out.flush();
+ }
+ // -----------------------
+ // untar these tars
+ // -----------------------
+ try (TarFile tarFile = new TarFile(tarF)) {
+ for (final TarArchiveEntry entry : tarFile.getEntries()) {
+ assertTrue(entry.getName().endsWith("/"), "Entry name: " + entry.getName());
+ }
+ }
+ }
+ }
+
@Test
public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
final byte[] buf = new byte[2];
@@ -92,6 +175,26 @@ public class TarFileTest extends AbstractTestCase {
}
}
+ @Test
+ public void testParseTarTruncatedInContent() {
+ assertThrows(IOException.class, () -> new TarFile(getPath("COMPRESS-544_truncated_in_content.tar")));
+ }
+
+ @Test
+ public void testParseTarTruncatedInPadding() {
+ assertThrows(IOException.class, () -> new TarFile(getPath("COMPRESS-544_truncated_in_padding.tar")));
+ }
+
+ @Test
+ public void testParseTarWithNonNumberPaxHeaders() {
+ assertThrows(IOException.class, () -> new TarFile(getPath("COMPRESS-529.tar")));
+ }
+
+ @Test
+ public void testParseTarWithSpecialPaxHeaders() {
+ assertThrows(IOException.class, () -> new TarFile(getPath("COMPRESS-530.tar")));
+ }
+
@Test
public void testReadsArchiveCompletely_COMPRESS245() {
try {
@@ -229,109 +332,6 @@ public class TarFileTest extends AbstractTestCase {
}
}
- @Test
- public void testCompress197() throws IOException {
- try (final TarFile tarFile = new TarFile(getPath("COMPRESS-197.tar"))) {
- // noop
- }
- }
-
- @Test
- public void testCompress558() throws IOException {
- final String folderName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/";
- final String consumerJavaName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/java/example/queue/exclusive/Consumer.java";
- final String producerJavaName = "apache-activemq-5.16.0/examples/openwire/advanced-scenarios/jms-example-exclusive-consumer/src/main/java/example/queue/exclusive/Producer.java";
-
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- try (final TarArchiveOutputStream tos = new TarArchiveOutputStream(bos)) {
- tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
- final TarArchiveEntry rootfolder = new TarArchiveEntry(folderName);
- tos.putArchiveEntry(rootfolder);
- final TarArchiveEntry consumerJava = new TarArchiveEntry(consumerJavaName);
- tos.putArchiveEntry(consumerJava);
- final TarArchiveEntry producerJava = new TarArchiveEntry(producerJavaName);
- tos.putArchiveEntry(producerJava);
- tos.closeArchiveEntry();
- }
- final byte[] data = bos.toByteArray();
- try (final TarFile tarFile = new TarFile(data)) {
- final List<TarArchiveEntry> entries = tarFile.getEntries();
- assertEquals(folderName, entries.get(0).getName());
- assertEquals(TarConstants.LF_DIR, entries.get(0).getLinkFlag());
- assertEquals(consumerJavaName, entries.get(1).getName());
- assertEquals(TarConstants.LF_NORMAL, entries.get(1).getLinkFlag());
- assertEquals(producerJavaName, entries.get(2).getName());
- assertEquals(TarConstants.LF_NORMAL, entries.get(2).getLinkFlag());
- }
- }
-
- @Test
- public void testDirectoryWithLongNameEndsWithSlash() throws IOException {
- final String rootPath = dir.getAbsolutePath();
- final String dirDirectory = "COMPRESS-509";
- final int count = 100;
- final File root = new File(rootPath + "/" + dirDirectory);
- root.mkdirs();
- for (int i = 1; i < count; i++) {
- // -----------------------
- // create empty dirs with incremental length
- // -----------------------
- final StringBuilder subDirBuilder = new StringBuilder();
- for (int j = 0; j < i; j++) {
- subDirBuilder.append("a");
- }
- final String subDir = subDirBuilder.toString();
- final File dir = new File(rootPath + "/" + dirDirectory, "/" + subDir);
- dir.mkdir();
-
- // -----------------------
- // tar these dirs
- // -----------------------
- final String fileName = "/" + dirDirectory + "/" + subDir;
- final File tarF = new File(rootPath + "/tar" + i + ".tar");
- try (OutputStream dest = Files.newOutputStream(tarF.toPath());
- TarArchiveOutputStream out = new TarArchiveOutputStream(new BufferedOutputStream(dest))) {
- out.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
- out.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
-
- final File file = new File(rootPath, fileName);
- final TarArchiveEntry entry = new TarArchiveEntry(file);
- entry.setName(fileName);
- out.putArchiveEntry(entry);
- out.closeArchiveEntry();
- out.flush();
- }
- // -----------------------
- // untar these tars
- // -----------------------
- try (TarFile tarFile = new TarFile(tarF)) {
- for (final TarArchiveEntry entry : tarFile.getEntries()) {
- assertTrue(entry.getName().endsWith("/"), "Entry name: " + entry.getName());
- }
- }
- }
- }
-
- @Test
- public void testParseTarTruncatedInContent() {
- assertThrows(IOException.class, () -> new TarFile(getPath("COMPRESS-544_truncated_in_content.tar")));
- }
-
- @Test
- public void testParseTarTruncatedInPadding() {
- assertThrows(IOException.class, () -> new TarFile(getPath("COMPRESS-544_truncated_in_padding.tar")));
- }
-
- @Test
- public void testParseTarWithNonNumberPaxHeaders() {
- assertThrows(IOException.class, () -> new TarFile(getPath("COMPRESS-529.tar")));
- }
-
- @Test
- public void testParseTarWithSpecialPaxHeaders() {
- assertThrows(IOException.class, () -> new TarFile(getPath("COMPRESS-530.tar")));
- }
-
@Test
public void testThrowException() {
assertThrows(IOException.class, () -> new TarFile(getPath("COMPRESS-553.tar")));
diff --git a/src/test/java/org/apache/commons/compress/archivers/tar/TarMemoryFileSystemTest.java b/src/test/java/org/apache/commons/compress/archivers/tar/TarMemoryFileSystemTest.java
index 076ddbb2..d97fda02 100644
--- a/src/test/java/org/apache/commons/compress/archivers/tar/TarMemoryFileSystemTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/tar/TarMemoryFileSystemTest.java
@@ -41,36 +41,6 @@ import com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder;
public class TarMemoryFileSystemTest {
- @Test
- public void testCheckUserInformationInTarEntry() throws IOException, ArchiveException {
- final String user = "commons";
- final String group = "compress";
- try (FileSystem fileSystem = MemoryFileSystemBuilder.newLinux().addUser(user).addGroup(group).build()) {
- final Path source = fileSystem.getPath("original-file.txt");
- Files.write(source, "Test".getBytes(UTF_8));
- Files.setAttribute(source, "posix:owner", (UserPrincipal) () -> user);
- Files.setAttribute(source, "posix:group", (GroupPrincipal) () -> group);
-
- final Path target = fileSystem.getPath("original-file.tar");
- try (final OutputStream out = Files.newOutputStream(target);
- final ArchiveOutputStream<ArchiveEntry> tarOut = ArchiveStreamFactory.DEFAULT.createArchiveOutputStream(ArchiveStreamFactory.TAR, out)) {
- final TarArchiveEntry entry = new TarArchiveEntry(source);
- tarOut.putArchiveEntry(entry);
-
- Files.copy(source, tarOut);
- tarOut.closeArchiveEntry();
- }
-
- try (final InputStream input = Files.newInputStream(target);
- final TarArchiveInputStream tarIn = new TarArchiveInputStream(input)) {
- final TarArchiveEntry nextTarEntry = tarIn.getNextTarEntry();
-
- assertEquals(user, nextTarEntry.getUserName());
- assertEquals(group, nextTarEntry.getGroupName());
- }
- }
- }
-
@Test
public void tarFromMemoryFileSystem() throws IOException, ArchiveException {
try (FileSystem fileSystem = MemoryFileSystemBuilder.newLinux().build()) {
@@ -110,4 +80,34 @@ public class TarMemoryFileSystemTest {
}
}
}
+
+ @Test
+ public void testCheckUserInformationInTarEntry() throws IOException, ArchiveException {
+ final String user = "commons";
+ final String group = "compress";
+ try (FileSystem fileSystem = MemoryFileSystemBuilder.newLinux().addUser(user).addGroup(group).build()) {
+ final Path source = fileSystem.getPath("original-file.txt");
+ Files.write(source, "Test".getBytes(UTF_8));
+ Files.setAttribute(source, "posix:owner", (UserPrincipal) () -> user);
+ Files.setAttribute(source, "posix:group", (GroupPrincipal) () -> group);
+
+ final Path target = fileSystem.getPath("original-file.tar");
+ try (final OutputStream out = Files.newOutputStream(target);
+ final ArchiveOutputStream<ArchiveEntry> tarOut = ArchiveStreamFactory.DEFAULT.createArchiveOutputStream(ArchiveStreamFactory.TAR, out)) {
+ final TarArchiveEntry entry = new TarArchiveEntry(source);
+ tarOut.putArchiveEntry(entry);
+
+ Files.copy(source, tarOut);
+ tarOut.closeArchiveEntry();
+ }
+
+ try (final InputStream input = Files.newInputStream(target);
+ final TarArchiveInputStream tarIn = new TarArchiveInputStream(input)) {
+ final TarArchiveEntry nextTarEntry = tarIn.getNextTarEntry();
+
+ assertEquals(user, nextTarEntry.getUserName());
+ assertEquals(group, nextTarEntry.getGroupName());
+ }
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java b/src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
index 314b52be..76c0c6dc 100644
--- a/src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/tar/TarUtilsTest.java
@@ -68,6 +68,42 @@ public class TarUtilsTest extends AbstractTestCase {
assertEquals(value, parseValue);
}
+ @Test
+ public void testName() {
+ byte[] buff = new byte[20];
+ final String sb1 = "abcdefghijklmnopqrstuvwxyz";
+ int off = TarUtils.formatNameBytes(sb1, buff, 1, buff.length - 1);
+ assertEquals(off, 20);
+ String sb2 = TarUtils.parseName(buff, 1, 10);
+ assertEquals(sb2, sb1.substring(0, 10));
+ sb2 = TarUtils.parseName(buff, 1, 19);
+ assertEquals(sb2, sb1.substring(0, 19));
+ buff = new byte[30];
+ off = TarUtils.formatNameBytes(sb1, buff, 1, buff.length - 1);
+ assertEquals(off, 30);
+ sb2 = TarUtils.parseName(buff, 1, buff.length - 1);
+ assertEquals(sb1, sb2);
+ buff = new byte[] { 0, 1, 0 };
+ sb2 = TarUtils.parseName(buff, 0, 3);
+ assertEquals("", sb2);
+ }
+
+ @Test
+ public void testNegative() {
+ final byte [] buffer = new byte[22];
+ TarUtils.formatUnsignedOctalString(-1, buffer, 0, buffer.length);
+ assertEquals("1777777777777777777777", new String(buffer, UTF_8));
+ }
+
+ @Test
+ public void testOverflow() {
+ final byte [] buffer = new byte[8-1]; // a lot of the numbers have 8-byte buffers (nul term)
+ TarUtils.formatUnsignedOctalString(07777777L, buffer, 0, buffer.length);
+ assertEquals("7777777", new String(buffer, UTF_8));
+ assertThrows(IllegalArgumentException.class, () -> TarUtils.formatUnsignedOctalString(017777777L, buffer, 0, buffer.length),
+ "Should have cause IllegalArgumentException");
+ }
+
@Test
public void testParseFromPAX01SparseHeaders() throws Exception {
final String map = "0,10,20,0,20,5";
@@ -107,6 +143,65 @@ public class TarUtilsTest extends AbstractTestCase {
assertThrows(IOException.class, () -> TarUtils.parseFromPAX01SparseHeaders(map));
}
+ @Test
+ public void testParseOctal() {
+ long value;
+ byte [] buffer;
+ final long MAX_OCTAL = 077777777777L; // Allowed 11 digits
+ final long MAX_OCTAL_OVERFLOW = 0777777777777L; // in fact 12 for some implementations
+ final String maxOctal = "777777777777"; // Maximum valid octal
+ buffer = maxOctal.getBytes(UTF_8);
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(MAX_OCTAL_OVERFLOW, value);
+ buffer[buffer.length - 1] = ' ';
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(MAX_OCTAL, value);
+ buffer[buffer.length-1]=0;
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(MAX_OCTAL, value);
+ buffer=new byte[]{0,0};
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(0, value);
+ buffer=new byte[]{0,' '};
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(0, value);
+ buffer=new byte[]{' ',0};
+ value = TarUtils.parseOctal(buffer,0, buffer.length);
+ assertEquals(0, value);
+ }
+
+ @Test
+ public void testParseOctalCompress330() {
+ final long expected = 0100000;
+ final byte [] buffer = {
+ 32, 32, 32, 32, 32, 49, 48, 48, 48, 48, 48, 32
+ };
+ assertEquals(expected, TarUtils.parseOctalOrBinary(buffer, 0, buffer.length));
+ }
+
+ @Test
+ public void testParseOctalInvalid() {
+ final byte[] buffer1 = ByteUtils.EMPTY_BYTE_ARRAY;
+ assertThrows(IllegalArgumentException.class, () -> TarUtils.parseOctal(buffer1, 0, buffer1.length),
+ "Expected IllegalArgumentException - should be at least 2 bytes long");
+
+ final byte[] buffer2 = {0}; // 1-byte array
+ assertThrows(IllegalArgumentException.class, () -> TarUtils.parseOctal(buffer2, 0, buffer2.length),
+ "Expected IllegalArgumentException - should be at least 2 bytes long");
+
+ final byte[] buffer3 = "abcdef ".getBytes(UTF_8); // Invalid input
+ assertThrows(IllegalArgumentException.class, () -> TarUtils.parseOctal(buffer3, 0, buffer3.length),
+ "Expected IllegalArgumentException");
+
+ final byte[] buffer4 = " 0 07 ".getBytes(UTF_8); // Invalid - embedded space
+ assertThrows(IllegalArgumentException.class, () -> TarUtils.parseOctal(buffer3, 0, buffer3.length),
+ "Expected IllegalArgumentException - embedded space");
+
+ final byte[] buffer5 = " 0\00007 ".getBytes(UTF_8); // Invalid - embedded NUL
+ assertThrows(IllegalArgumentException.class, () -> TarUtils.parseOctal(buffer5, 0, buffer5.length),
+ "Expected IllegalArgumentException - embedded NUL");
+ }
+
@Test
public void testParsePAX01SparseHeadersRejectsOddNumberOfEntries() {
final String map = "0,10,20,0,20";
@@ -130,6 +225,7 @@ public class TarUtilsTest extends AbstractTestCase {
}
}
+
@Test
public void testParsePAX1XSparseHeadersRejectsIncompleteLastLine() throws Exception {
final byte[] header = ("1\n"
@@ -206,7 +302,6 @@ public class TarUtilsTest extends AbstractTestCase {
}
}
-
@Test
public void testParsePAX1XSparseHeadersRejectsNonNumericOffset() throws Exception {
final byte[] header = ("1\n"
@@ -220,6 +315,27 @@ public class TarUtilsTest extends AbstractTestCase {
}
}
+ @Test
+ public void testParseSparse() {
+ final long expectedOffset = 0100000;
+ final long expectedNumbytes = 0111000;
+ final byte [] buffer = {
+ ' ', ' ', ' ', ' ', ' ', '0', '1', '0', '0', '0', '0', '0', // sparseOffset
+ ' ', ' ', ' ', ' ', ' ', '0', '1', '1', '1', '0', '0', '0'};
+ final TarArchiveStructSparse sparse = TarUtils.parseSparse(buffer, 0);
+ assertEquals(sparse.getOffset(), expectedOffset);
+ assertEquals(sparse.getNumbytes(), expectedNumbytes);
+ }
+
+ @Test
+ public void testParseTarWithSpecialPaxHeaders() throws IOException {
+ try (InputStream in = newInputStream("COMPRESS-530.tar");
+ TarArchiveInputStream archive = new TarArchiveInputStream(in)) {
+ assertThrows(IOException.class, () -> archive.getNextEntry());
+ // IOUtils.toByteArray(archive);
+ }
+ }
+
@Test
public void testPaxHeaderEntryWithEmptyValueRemovesKey() throws Exception {
final Map<String, String> headers = TarUtils
@@ -228,6 +344,25 @@ public class TarUtilsTest extends AbstractTestCase {
assertEquals(0, headers.size());
}
+ @Test
+ public void testReadNegativeBinary12Byte() {
+ final byte[] b = {
+ (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+ (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+ (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef,
+ };
+ assertEquals(-3601L, TarUtils.parseOctalOrBinary(b, 0, 12));
+ }
+
+ @Test
+ public void testReadNegativeBinary8Byte() {
+ final byte[] b = {
+ (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+ (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef,
+ };
+ assertEquals(-3601L, TarUtils.parseOctalOrBinary(b, 0, 8));
+ }
+
@Test
public void testReadNonAsciiPaxHeader() throws Exception {
final String ae = "\u00e4";
@@ -377,149 +512,6 @@ public class TarUtilsTest extends AbstractTestCase {
assertThrows(IOException.class, () -> TarUtils.readSparseStructs(header, 0, 1));
}
- @Test
- public void testSecondEntryWinsWhenPaxHeaderContainsDuplicateKey() throws Exception {
- final Map<String, String> headers = TarUtils.parsePaxHeaders(new ByteArrayInputStream("11 foo=bar\n11 foo=baz\n"
- .getBytes(UTF_8)), null, new HashMap<>());
- assertEquals(1, headers.size());
- assertEquals("baz", headers.get("foo"));
- }
-
- @Test
- public void testName() {
- byte[] buff = new byte[20];
- final String sb1 = "abcdefghijklmnopqrstuvwxyz";
- int off = TarUtils.formatNameBytes(sb1, buff, 1, buff.length - 1);
- assertEquals(off, 20);
- String sb2 = TarUtils.parseName(buff, 1, 10);
- assertEquals(sb2, sb1.substring(0, 10));
- sb2 = TarUtils.parseName(buff, 1, 19);
- assertEquals(sb2, sb1.substring(0, 19));
- buff = new byte[30];
- off = TarUtils.formatNameBytes(sb1, buff, 1, buff.length - 1);
- assertEquals(off, 30);
- sb2 = TarUtils.parseName(buff, 1, buff.length - 1);
- assertEquals(sb1, sb2);
- buff = new byte[] { 0, 1, 0 };
- sb2 = TarUtils.parseName(buff, 0, 3);
- assertEquals("", sb2);
- }
-
- @Test
- public void testNegative() {
- final byte [] buffer = new byte[22];
- TarUtils.formatUnsignedOctalString(-1, buffer, 0, buffer.length);
- assertEquals("1777777777777777777777", new String(buffer, UTF_8));
- }
-
- @Test
- public void testOverflow() {
- final byte [] buffer = new byte[8-1]; // a lot of the numbers have 8-byte buffers (nul term)
- TarUtils.formatUnsignedOctalString(07777777L, buffer, 0, buffer.length);
- assertEquals("7777777", new String(buffer, UTF_8));
- assertThrows(IllegalArgumentException.class, () -> TarUtils.formatUnsignedOctalString(017777777L, buffer, 0, buffer.length),
- "Should have cause IllegalArgumentException");
- }
-
- @Test
- public void testParseOctal() {
- long value;
- byte [] buffer;
- final long MAX_OCTAL = 077777777777L; // Allowed 11 digits
- final long MAX_OCTAL_OVERFLOW = 0777777777777L; // in fact 12 for some implementations
- final String maxOctal = "777777777777"; // Maximum valid octal
- buffer = maxOctal.getBytes(UTF_8);
- value = TarUtils.parseOctal(buffer,0, buffer.length);
- assertEquals(MAX_OCTAL_OVERFLOW, value);
- buffer[buffer.length - 1] = ' ';
- value = TarUtils.parseOctal(buffer,0, buffer.length);
- assertEquals(MAX_OCTAL, value);
- buffer[buffer.length-1]=0;
- value = TarUtils.parseOctal(buffer,0, buffer.length);
- assertEquals(MAX_OCTAL, value);
- buffer=new byte[]{0,0};
- value = TarUtils.parseOctal(buffer,0, buffer.length);
- assertEquals(0, value);
- buffer=new byte[]{0,' '};
- value = TarUtils.parseOctal(buffer,0, buffer.length);
- assertEquals(0, value);
- buffer=new byte[]{' ',0};
- value = TarUtils.parseOctal(buffer,0, buffer.length);
- assertEquals(0, value);
- }
-
- @Test
- public void testParseOctalCompress330() {
- final long expected = 0100000;
- final byte [] buffer = {
- 32, 32, 32, 32, 32, 49, 48, 48, 48, 48, 48, 32
- };
- assertEquals(expected, TarUtils.parseOctalOrBinary(buffer, 0, buffer.length));
- }
-
- @Test
- public void testParseOctalInvalid() {
- final byte[] buffer1 = ByteUtils.EMPTY_BYTE_ARRAY;
- assertThrows(IllegalArgumentException.class, () -> TarUtils.parseOctal(buffer1, 0, buffer1.length),
- "Expected IllegalArgumentException - should be at least 2 bytes long");
-
- final byte[] buffer2 = {0}; // 1-byte array
- assertThrows(IllegalArgumentException.class, () -> TarUtils.parseOctal(buffer2, 0, buffer2.length),
- "Expected IllegalArgumentException - should be at least 2 bytes long");
-
- final byte[] buffer3 = "abcdef ".getBytes(UTF_8); // Invalid input
- assertThrows(IllegalArgumentException.class, () -> TarUtils.parseOctal(buffer3, 0, buffer3.length),
- "Expected IllegalArgumentException");
-
- final byte[] buffer4 = " 0 07 ".getBytes(UTF_8); // Invalid - embedded space
- assertThrows(IllegalArgumentException.class, () -> TarUtils.parseOctal(buffer3, 0, buffer3.length),
- "Expected IllegalArgumentException - embedded space");
-
- final byte[] buffer5 = " 0\00007 ".getBytes(UTF_8); // Invalid - embedded NUL
- assertThrows(IllegalArgumentException.class, () -> TarUtils.parseOctal(buffer5, 0, buffer5.length),
- "Expected IllegalArgumentException - embedded NUL");
- }
-
- @Test
- public void testParseSparse() {
- final long expectedOffset = 0100000;
- final long expectedNumbytes = 0111000;
- final byte [] buffer = {
- ' ', ' ', ' ', ' ', ' ', '0', '1', '0', '0', '0', '0', '0', // sparseOffset
- ' ', ' ', ' ', ' ', ' ', '0', '1', '1', '1', '0', '0', '0'};
- final TarArchiveStructSparse sparse = TarUtils.parseSparse(buffer, 0);
- assertEquals(sparse.getOffset(), expectedOffset);
- assertEquals(sparse.getNumbytes(), expectedNumbytes);
- }
-
- @Test
- public void testParseTarWithSpecialPaxHeaders() throws IOException {
- try (InputStream in = newInputStream("COMPRESS-530.tar");
- TarArchiveInputStream archive = new TarArchiveInputStream(in)) {
- assertThrows(IOException.class, () -> archive.getNextEntry());
- // IOUtils.toByteArray(archive);
- }
- }
-
- @Test
- public void testReadNegativeBinary12Byte() {
- final byte[] b = {
- (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
- (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
- (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef,
- };
- assertEquals(-3601L, TarUtils.parseOctalOrBinary(b, 0, 12));
- }
-
- @Test
- public void testReadNegativeBinary8Byte() {
- final byte[] b = {
- (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
- (byte) 0xff, (byte) 0xff, (byte) 0xf1, (byte) 0xef,
- };
- assertEquals(-3601L, TarUtils.parseOctalOrBinary(b, 0, 8));
- }
-
@Test
public void testRoundEncoding() throws Exception {
// COMPRESS-114
@@ -578,6 +570,14 @@ public class TarUtilsTest extends AbstractTestCase {
"Should throw exception - value is too long to fit buffer of this len");
assertEquals("Value 9223372036854775807 is too large for 8 byte field.", e.getMessage());
}
+
+ @Test
+ public void testSecondEntryWinsWhenPaxHeaderContainsDuplicateKey() throws Exception {
+ final Map<String, String> headers = TarUtils.parsePaxHeaders(new ByteArrayInputStream("11 foo=bar\n11 foo=baz\n"
+ .getBytes(UTF_8)), null, new HashMap<>());
+ assertEquals(1, headers.size());
+ assertEquals("baz", headers.get("foo"));
+ }
// Check correct trailing bytes are generated
@Test
public void testTrailers() {
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/ExtraFieldUtilsTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/ExtraFieldUtilsTest.java
index a006aa4a..6d9ed6b6 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/ExtraFieldUtilsTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/ExtraFieldUtilsTest.java
@@ -87,18 +87,6 @@ public class ExtraFieldUtilsTest implements UnixStat {
private byte[] aLocal;
- @Test
- public void testParseTurnsArrayIndexOutOfBoundsIntoZipException() {
- ExtraFieldUtils.register(AiobThrowingExtraField.class);
- final AiobThrowingExtraField f = new AiobThrowingExtraField();
- final byte[] d = new byte[4 + AiobThrowingExtraField.LENGTH];
- System.arraycopy(f.getHeaderId().getBytes(), 0, d, 0, 2);
- System.arraycopy(f.getLocalFileDataLength().getBytes(), 0, d, 2, 2);
- System.arraycopy(f.getLocalFileDataData(), 0, d, 4, AiobThrowingExtraField.LENGTH);
- final ZipException e = assertThrows(ZipException.class, () -> ExtraFieldUtils.parse(d), "data should be invalid");
- assertEquals("Failed to parse corrupt ZIP extra field of type 1000", e.getMessage(), "message");
- }
-
@BeforeEach
public void setUp() {
a = new AsiExtraField();
@@ -212,6 +200,18 @@ public class ExtraFieldUtilsTest implements UnixStat {
}
+ @Test
+ public void testParseTurnsArrayIndexOutOfBoundsIntoZipException() {
+ ExtraFieldUtils.register(AiobThrowingExtraField.class);
+ final AiobThrowingExtraField f = new AiobThrowingExtraField();
+ final byte[] d = new byte[4 + AiobThrowingExtraField.LENGTH];
+ System.arraycopy(f.getHeaderId().getBytes(), 0, d, 0, 2);
+ System.arraycopy(f.getLocalFileDataLength().getBytes(), 0, d, 2, 2);
+ System.arraycopy(f.getLocalFileDataData(), 0, d, 4, AiobThrowingExtraField.LENGTH);
+ final ZipException e = assertThrows(ZipException.class, () -> ExtraFieldUtils.parse(d), "data should be invalid");
+ assertEquals("Failed to parse corrupt ZIP extra field of type 1000", e.getMessage(), "message");
+ }
+
@Test
public void testParseWithRead() throws Exception {
ZipExtraField[] ze =
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/ParallelScatterZipCreatorTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/ParallelScatterZipCreatorTest.java
index 0e615479..9177d6b3 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/ParallelScatterZipCreatorTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/ParallelScatterZipCreatorTest.java
@@ -95,25 +95,6 @@ public class ParallelScatterZipCreatorTest {
assertNotNull(zipCreator.getStatisticsMessage());
}
- @Test
- public void testCallableApiUsingSubmit() throws Exception {
- result = File.createTempFile("parallelScatterGather2", "");
- callableApi(zipCreator -> zipCreator::submit);
- }
-
- @Test
- public void testCallableApiUsingSubmitStreamAwareCallable() throws Exception {
- result = File.createTempFile("parallelScatterGather3", "");
- callableApi(zipCreator -> zipCreator::submitStreamAwareCallable);
- }
-
-
- @Test
- public void testCallableApiWithHighestLevelUsingSubmitStreamAwareCallable() throws Exception {
- result = File.createTempFile("parallelScatterGather5", "");
- callableApiWithTestFiles(zipCreator -> zipCreator::submitStreamAwareCallable, Deflater.BEST_COMPRESSION);
- }
-
private void callableApiWithTestFiles(final CallableConsumerSupplier consumerSupplier, final int compressionLevel) throws Exception {
final ParallelScatterZipCreator zipCreator;
final Map<String, byte[]> entries;
@@ -143,58 +124,12 @@ public class ParallelScatterZipCreatorTest {
assertNotNull(zipCreator.getStatisticsMessage());
}
- @Test
- public void testCallableWithLowestLevelApiUsingSubmit() throws Exception {
- result = File.createTempFile("parallelScatterGather4", "");
- callableApiWithTestFiles(zipCreator -> zipCreator::submit, Deflater.NO_COMPRESSION);
- }
-
@AfterEach
public void cleanup() {
AbstractTestCase.forceDelete(result);
AbstractTestCase.forceDelete(tmp);
}
- @Test
- public void testConcurrentCustomTempFolder()
- throws Exception {
- result = File.createTempFile("parallelScatterGather1", "");
- final ParallelScatterZipCreator zipCreator;
- final Map<String, byte[]> entries;
- try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(result)) {
- zos.setEncoding("UTF-8");
-
- // Formatter:off
- final Path dir = Paths.get("target/custom-temp-dir");
- Files.createDirectories(dir);
- zipCreator = new ParallelScatterZipCreator(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()),
- new DefaultBackingStoreSupplier(dir));
- // Formatter:on
-
- entries = writeEntries(zipCreator);
- zipCreator.writeTo(zos);
- }
- removeEntriesFoundInZipFile(result, entries);
- assertTrue(entries.isEmpty());
- assertNotNull(zipCreator.getStatisticsMessage());
- }
-
- @Test
- public void testConcurrentDefaultTempFolder() throws Exception {
- result = File.createTempFile("parallelScatterGather1", "");
- final ParallelScatterZipCreator zipCreator;
- final Map<String, byte[]> entries;
- try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(result)) {
- zos.setEncoding("UTF-8");
- zipCreator = new ParallelScatterZipCreator();
-
- entries = writeEntries(zipCreator);
- zipCreator.writeTo(zos);
- }
- removeEntriesFoundInZipFile(result, entries);
- assertTrue(entries.isEmpty());
- assertNotNull(zipCreator.getStatisticsMessage());
- }
private ZipArchiveEntry createZipArchiveEntry(final Map<String, byte[]> entries, final int i, final byte[] payloadBytes) {
final ZipArchiveEntry za = new ZipArchiveEntry( "file" + i);
@@ -248,6 +183,71 @@ public class ParallelScatterZipCreatorTest {
} // Throws NullPointerException on close()
}
+ @Test
+ public void testCallableApiUsingSubmit() throws Exception {
+ result = File.createTempFile("parallelScatterGather2", "");
+ callableApi(zipCreator -> zipCreator::submit);
+ }
+
+ @Test
+ public void testCallableApiUsingSubmitStreamAwareCallable() throws Exception {
+ result = File.createTempFile("parallelScatterGather3", "");
+ callableApi(zipCreator -> zipCreator::submitStreamAwareCallable);
+ }
+
+ @Test
+ public void testCallableApiWithHighestLevelUsingSubmitStreamAwareCallable() throws Exception {
+ result = File.createTempFile("parallelScatterGather5", "");
+ callableApiWithTestFiles(zipCreator -> zipCreator::submitStreamAwareCallable, Deflater.BEST_COMPRESSION);
+ }
+
+ @Test
+ public void testCallableWithLowestLevelApiUsingSubmit() throws Exception {
+ result = File.createTempFile("parallelScatterGather4", "");
+ callableApiWithTestFiles(zipCreator -> zipCreator::submit, Deflater.NO_COMPRESSION);
+ }
+
+ @Test
+ public void testConcurrentCustomTempFolder()
+ throws Exception {
+ result = File.createTempFile("parallelScatterGather1", "");
+ final ParallelScatterZipCreator zipCreator;
+ final Map<String, byte[]> entries;
+ try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(result)) {
+ zos.setEncoding("UTF-8");
+
+ // Formatter:off
+ final Path dir = Paths.get("target/custom-temp-dir");
+ Files.createDirectories(dir);
+ zipCreator = new ParallelScatterZipCreator(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()),
+ new DefaultBackingStoreSupplier(dir));
+ // Formatter:on
+
+ entries = writeEntries(zipCreator);
+ zipCreator.writeTo(zos);
+ }
+ removeEntriesFoundInZipFile(result, entries);
+ assertTrue(entries.isEmpty());
+ assertNotNull(zipCreator.getStatisticsMessage());
+ }
+
+ @Test
+ public void testConcurrentDefaultTempFolder() throws Exception {
+ result = File.createTempFile("parallelScatterGather1", "");
+ final ParallelScatterZipCreator zipCreator;
+ final Map<String, byte[]> entries;
+ try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(result)) {
+ zos.setEncoding("UTF-8");
+ zipCreator = new ParallelScatterZipCreator();
+
+ entries = writeEntries(zipCreator);
+ zipCreator.writeTo(zos);
+ }
+ removeEntriesFoundInZipFile(result, entries);
+ assertTrue(entries.isEmpty());
+ assertNotNull(zipCreator.getStatisticsMessage());
+ }
+
@Test
public void throwsExceptionWithCompressionLevelTooBig() {
final int compressLevelTooBig = Deflater.BEST_COMPRESSION + 1;
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/StreamCompressorTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/StreamCompressorTest.java
index 5ec1a238..90d2a0af 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/StreamCompressorTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/StreamCompressorTest.java
@@ -32,6 +32,14 @@ import org.junit.jupiter.api.Test;
public class StreamCompressorTest {
+ @Test
+ public void testCreateDataOutputCompressor() throws IOException {
+ final DataOutput dataOutputStream = new DataOutputStream(new ByteArrayOutputStream());
+ try (StreamCompressor streamCompressor = StreamCompressor.create(dataOutputStream, new Deflater(9))) {
+ assertNotNull(streamCompressor);
+ }
+ }
+
@Test
public void testDeflatedEntries() throws Exception {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -61,12 +69,4 @@ public class StreamCompressorTest {
assertEquals("ABADCAFE", baos.toString());
}
}
-
- @Test
- public void testCreateDataOutputCompressor() throws IOException {
- final DataOutput dataOutputStream = new DataOutputStream(new ByteArrayOutputStream());
- try (StreamCompressor streamCompressor = StreamCompressor.create(dataOutputStream, new Deflater(9))) {
- assertNotNull(streamCompressor);
- }
- }
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/UTF8ZipFilesTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/UTF8ZipFilesTest.java
index 407b9927..c9ad9654 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/UTF8ZipFilesTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/UTF8ZipFilesTest.java
@@ -199,19 +199,6 @@ public class UTF8ZipFilesTest extends AbstractTestCase {
}
}
- /**
- * @see <a href="https://issues.apache.org/jira/browse/COMPRESS-479">COMPRESS-479</a>
- */
- @Test
- public void testStreamSkipsOverUnicodeExtraFieldWithUnsupportedVersion() throws IOException {
- try (InputStream archive = newInputStream("COMPRESS-479.zip");
- ZipArchiveInputStream zi = new ZipArchiveInputStream(archive)) {
- assertEquals(OIL_BARREL_TXT, zi.getNextEntry().getName());
- assertEquals("%U20AC_for_Dollar.txt", zi.getNextEntry().getName());
- assertEquals(ASCII_TXT, zi.getNextEntry().getName());
- }
- }
-
@Test
public void testASCIIFileRoundtripExplicitUnicodeExtra()
throws IOException {
@@ -324,6 +311,19 @@ public class UTF8ZipFilesTest extends AbstractTestCase {
}
}
+ /**
+ * @see <a href="https://issues.apache.org/jira/browse/COMPRESS-479">COMPRESS-479</a>
+ */
+ @Test
+ public void testStreamSkipsOverUnicodeExtraFieldWithUnsupportedVersion() throws IOException {
+ try (InputStream archive = newInputStream("COMPRESS-479.zip");
+ ZipArchiveInputStream zi = new ZipArchiveInputStream(archive)) {
+ assertEquals(OIL_BARREL_TXT, zi.getNextEntry().getName());
+ assertEquals("%U20AC_for_Dollar.txt", zi.getNextEntry().getName());
+ assertEquals(ASCII_TXT, zi.getNextEntry().getName());
+ }
+ }
+
@Test
public void testUtf8FileRoundtripExplicitUnicodeExtra()
throws IOException {
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestampTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestampTest.java
index 2b4a3c5e..dced22b8 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestampTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestampTest.java
@@ -159,15 +159,6 @@ public class X5455_ExtendedTimestampTest {
}
}
- @Test
- public void testResetsFlagsWhenLocalFileArrayIsTooShort() throws Exception {
- final byte[] local = {
- 7
- }; // claims all three time values would be present, but they are not
- xf.parseFromLocalFileData(local, 0, 1);
- assertArrayEquals(new byte[1], xf.getLocalFileDataData());
- }
-
@Test
public void testBitsAreSetWithTime() {
xf.setModifyJavaTime(new Date(1111));
@@ -467,6 +458,15 @@ public class X5455_ExtendedTimestampTest {
parseReparse((byte) -1, MAX_TIME_SECONDS, (byte) 7, MOD_AC_CR_MAX, MOD_MAX);
}
+ @Test
+ public void testResetsFlagsWhenLocalFileArrayIsTooShort() throws Exception {
+ final byte[] local = {
+ 7
+ }; // claims all three time values would be present, but they are not
+ xf.parseFromLocalFileData(local, 0, 1);
+ assertArrayEquals(new byte[1], xf.getLocalFileDataData());
+ }
+
@Test
public void testSampleFile() throws Exception {
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/Zip64SupportIT.java b/src/test/java/org/apache/commons/compress/archivers/zip/Zip64SupportIT.java
index 9f352a83..6f05b58b 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/Zip64SupportIT.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/Zip64SupportIT.java
@@ -2202,40 +2202,6 @@ public class Zip64SupportIT {
true);
}
- @Test
- public void testZip64ModeAlwaysWithCompatibility() throws Throwable {
- final File inputFile = getFile("test3.xml");
-
- // with Zip64Mode.AlwaysWithCompatibility, the relative header offset and disk number
- // start will not be set in extra fields
- final File zipUsingModeAlwaysWithCompatibility = buildZipWithZip64Mode("testZip64ModeAlwaysWithCompatibility-output-1",
- Zip64Mode.AlwaysWithCompatibility, inputFile);
- final ZipFile zipFileWithAlwaysWithCompatibility = new ZipFile(zipUsingModeAlwaysWithCompatibility);
- ZipArchiveEntry entry = zipFileWithAlwaysWithCompatibility.getEntries().nextElement();
- for (final ZipExtraField extraField : entry.getExtraFields()) {
- if (!(extraField instanceof Zip64ExtendedInformationExtraField)) {
- continue;
- }
-
- assertNull(((Zip64ExtendedInformationExtraField) extraField).getRelativeHeaderOffset());
- assertNull(((Zip64ExtendedInformationExtraField) extraField).getDiskStartNumber());
- }
-
- // with Zip64Mode.Always, the relative header offset and disk number start will be
- // set in extra fields
- final File zipUsingModeAlways = buildZipWithZip64Mode("testZip64ModeAlwaysWithCompatibility-output-2", Zip64Mode.Always, inputFile);
- final ZipFile zipFileWithAlways = new ZipFile(zipUsingModeAlways);
- entry = zipFileWithAlways.getEntries().nextElement();
- for (final ZipExtraField extraField : entry.getExtraFields()) {
- if (!(extraField instanceof Zip64ExtendedInformationExtraField)) {
- continue;
- }
-
- assertNotNull(((Zip64ExtendedInformationExtraField) extraField).getRelativeHeaderOffset());
- assertNotNull(((Zip64ExtendedInformationExtraField) extraField).getDiskStartNumber());
- }
- }
-
@Test public void testWrite100KFilesFile() throws Throwable {
withTemporaryArchive("write100KFilesFile", write100KFiles(), true);
}
@@ -2642,4 +2608,38 @@ public class Zip64SupportIT {
writeSmallStoredEntry(false, Zip64Mode.Never),
true);
}
+
+ @Test
+ public void testZip64ModeAlwaysWithCompatibility() throws Throwable {
+ final File inputFile = getFile("test3.xml");
+
+ // with Zip64Mode.AlwaysWithCompatibility, the relative header offset and disk number
+ // start will not be set in extra fields
+ final File zipUsingModeAlwaysWithCompatibility = buildZipWithZip64Mode("testZip64ModeAlwaysWithCompatibility-output-1",
+ Zip64Mode.AlwaysWithCompatibility, inputFile);
+ final ZipFile zipFileWithAlwaysWithCompatibility = new ZipFile(zipUsingModeAlwaysWithCompatibility);
+ ZipArchiveEntry entry = zipFileWithAlwaysWithCompatibility.getEntries().nextElement();
+ for (final ZipExtraField extraField : entry.getExtraFields()) {
+ if (!(extraField instanceof Zip64ExtendedInformationExtraField)) {
+ continue;
+ }
+
+ assertNull(((Zip64ExtendedInformationExtraField) extraField).getRelativeHeaderOffset());
+ assertNull(((Zip64ExtendedInformationExtraField) extraField).getDiskStartNumber());
+ }
+
+ // with Zip64Mode.Always, the relative header offset and disk number start will be
+ // set in extra fields
+ final File zipUsingModeAlways = buildZipWithZip64Mode("testZip64ModeAlwaysWithCompatibility-output-2", Zip64Mode.Always, inputFile);
+ final ZipFile zipFileWithAlways = new ZipFile(zipUsingModeAlways);
+ entry = zipFileWithAlways.getEntries().nextElement();
+ for (final ZipExtraField extraField : entry.getExtraFields()) {
+ if (!(extraField instanceof Zip64ExtendedInformationExtraField)) {
+ continue;
+ }
+
+ assertNotNull(((Zip64ExtendedInformationExtraField) extraField).getRelativeHeaderOffset());
+ assertNotNull(((Zip64ExtendedInformationExtraField) extraField).getDiskStartNumber());
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntryTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntryTest.java
index 5c3167cb..ddc3d29e 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntryTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntryTest.java
@@ -52,43 +52,6 @@ public class ZipArchiveEntryTest {
assertEquals(extraFields.length, read.length);
}
- @Test
- public void testDraconicThrowsOnUnparseableExtraData() throws Exception {
- final ZipExtraField[] extraFields = parsingModeBehaviorTestData();
- final ZipArchiveEntry ze = new ZipArchiveEntry("foo");
- ze.setExtraFields(extraFields);
- assertThrows(ZipException.class, () -> ze.getExtraFields(ZipArchiveEntry.ExtraFieldParsingMode.DRACONIC));
- }
-
- /**
- * @see "https://issues.apache.org/jira/browse/COMPRESS-379"
- */
- @Test
- public void testIsUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception {
- try (ZipFile zf = new ZipFile(getFile("COMPRESS-379.jar"))) {
- final ZipArchiveEntry ze = zf.getEntry("META-INF/maven/");
- assertFalse(ze.isUnixSymlink());
- }
- }
-
- @Test
- public void testOnlyParseableLenientExcludesUnparseableExtraData() throws Exception {
- final ZipExtraField[] extraFields = parsingModeBehaviorTestData();
- final ZipArchiveEntry ze = new ZipArchiveEntry("foo");
- ze.setExtraFields(extraFields);
- final ZipExtraField[] read = ze.getExtraFields(ZipArchiveEntry.ExtraFieldParsingMode.ONLY_PARSEABLE_LENIENT);
- assertEquals(extraFields.length, read.length + 1);
- }
-
- @Test
- public void testOnlyParseableStrictExcludesUnparseableExtraData() throws Exception {
- final ZipExtraField[] extraFields = parsingModeBehaviorTestData();
- final ZipArchiveEntry ze = new ZipArchiveEntry("foo");
- ze.setExtraFields(extraFields);
- final ZipExtraField[] read = ze.getExtraFields(ZipArchiveEntry.ExtraFieldParsingMode.ONLY_PARSEABLE_STRICT);
- assertEquals(extraFields.length, read.length + 1);
- }
-
private ZipExtraField[] parsingModeBehaviorTestData() {
final AsiExtraField a = new AsiExtraField();
a.setDirectory(true);
@@ -104,24 +67,6 @@ public class ZipArchiveEntryTest {
return new ZipExtraField[] { a, u, x };
}
- @Test
- public void testReparsingUnicodeExtraWithUnsupportedversionThrowsInStrictMode()
- throws Exception {
- try (ZipFile zf = new ZipFile(getFile("COMPRESS-479.zip"))) {
- final ZipArchiveEntry ze = zf.getEntry("%U20AC_for_Dollar.txt");
- assertThrows(ZipException.class, () -> ze.getExtraFields(ZipArchiveEntry.ExtraFieldParsingMode.STRICT_FOR_KNOW_EXTRA_FIELDS));
- }
- }
-
- @Test
- public void testStrictForKnowExtraFieldsIncludesUnparseableExtraData() throws Exception {
- final ZipExtraField[] extraFields = parsingModeBehaviorTestData();
- final ZipArchiveEntry ze = new ZipArchiveEntry("foo");
- ze.setExtraFields(extraFields);
- final ZipExtraField[] read = ze.getExtraFields(ZipArchiveEntry.ExtraFieldParsingMode.STRICT_FOR_KNOW_EXTRA_FIELDS);
- assertEquals(extraFields.length, read.length);
- }
-
/**
* test handling of extra fields
*/
@@ -198,6 +143,14 @@ public class ZipArchiveEntryTest {
assertEquals(archiveEntry, copy);
}
+ @Test
+ public void testDraconicThrowsOnUnparseableExtraData() throws Exception {
+ final ZipExtraField[] extraFields = parsingModeBehaviorTestData();
+ final ZipArchiveEntry ze = new ZipArchiveEntry("foo");
+ ze.setExtraFields(extraFields);
+ assertThrows(ZipException.class, () -> ze.getExtraFields(ZipArchiveEntry.ExtraFieldParsingMode.DRACONIC));
+ }
+
/**
* test handling of extra fields via central directory
*/
@@ -305,6 +258,17 @@ public class ZipArchiveEntryTest {
assertFalse(ze.isUnixSymlink());
}
+ /**
+ * @see "https://issues.apache.org/jira/browse/COMPRESS-379"
+ */
+ @Test
+ public void testIsUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception {
+ try (ZipFile zf = new ZipFile(getFile("COMPRESS-379.jar"))) {
+ final ZipArchiveEntry ze = zf.getEntry("META-INF/maven/");
+ assertFalse(ze.isUnixSymlink());
+ }
+ }
+
/**
* Test case for
* <a href="https://issues.apache.org/jira/browse/COMPRESS-94"
@@ -334,6 +298,33 @@ public class ZipArchiveEntryTest {
assertNotEquals(entry2, entry3);
}
+ @Test
+ public void testOnlyParseableLenientExcludesUnparseableExtraData() throws Exception {
+ final ZipExtraField[] extraFields = parsingModeBehaviorTestData();
+ final ZipArchiveEntry ze = new ZipArchiveEntry("foo");
+ ze.setExtraFields(extraFields);
+ final ZipExtraField[] read = ze.getExtraFields(ZipArchiveEntry.ExtraFieldParsingMode.ONLY_PARSEABLE_LENIENT);
+ assertEquals(extraFields.length, read.length + 1);
+ }
+
+ @Test
+ public void testOnlyParseableStrictExcludesUnparseableExtraData() throws Exception {
+ final ZipExtraField[] extraFields = parsingModeBehaviorTestData();
+ final ZipArchiveEntry ze = new ZipArchiveEntry("foo");
+ ze.setExtraFields(extraFields);
+ final ZipExtraField[] read = ze.getExtraFields(ZipArchiveEntry.ExtraFieldParsingMode.ONLY_PARSEABLE_STRICT);
+ assertEquals(extraFields.length, read.length + 1);
+ }
+
+ @Test
+ public void testReparsingUnicodeExtraWithUnsupportedversionThrowsInStrictMode()
+ throws Exception {
+ try (ZipFile zf = new ZipFile(getFile("COMPRESS-479.zip"))) {
+ final ZipArchiveEntry ze = zf.getEntry("%U20AC_for_Dollar.txt");
+ assertThrows(ZipException.class, () -> ze.getExtraFields(ZipArchiveEntry.ExtraFieldParsingMode.STRICT_FOR_KNOW_EXTRA_FIELDS));
+ }
+ }
+
@Test
public void testShouldNotSetExtraDateFieldsIfDateFitsInDosDates() {
final ZipArchiveEntry ze = new ZipArchiveEntry();
@@ -490,6 +481,15 @@ public class ZipArchiveEntryTest {
assertEquals(0L, ntfs.getCreateTime().getLongValue());
}
+ @Test
+ public void testStrictForKnowExtraFieldsIncludesUnparseableExtraData() throws Exception {
+ final ZipExtraField[] extraFields = parsingModeBehaviorTestData();
+ final ZipArchiveEntry ze = new ZipArchiveEntry("foo");
+ ze.setExtraFields(extraFields);
+ final ZipExtraField[] read = ze.getExtraFields(ZipArchiveEntry.ExtraFieldParsingMode.STRICT_FOR_KNOW_EXTRA_FIELDS);
+ assertEquals(extraFields.length, read.length);
+ }
+
@Test
public void testUnixMode() {
ZipArchiveEntry ze = new ZipArchiveEntry("foo");
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
index 3754d4d0..6dac6c61 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStreamTest.java
@@ -154,6 +154,35 @@ public class ZipArchiveInputStreamTest extends AbstractTestCase {
}
}
+ private void singleByteReadConsistentlyReturnsMinusOneAtEof(final File file) throws Exception {
+ try (InputStream in = Files.newInputStream(file.toPath());
+ ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) {
+ final ArchiveEntry e = archive.getNextEntry();
+ IOUtils.toByteArray(archive);
+ assertEquals(-1, archive.read());
+ assertEquals(-1, archive.read());
+ }
+ }
+
+ /**
+ * Test case for
+ * <a href="https://issues.apache.org/jira/browse/COMPRESS-351"
+ * >COMPRESS-351</a>.
+ */
+ @Test
+ public void testMessageWithCorruptFileName() throws Exception {
+ try (ZipArchiveInputStream in = new ZipArchiveInputStream(newInputStream("COMPRESS-351.zip"))) {
+ final EOFException ex = assertThrows(EOFException.class, () -> {
+ ZipArchiveEntry ze = in.getNextZipEntry();
+ while (ze != null) {
+ ze = in.getNextZipEntry();
+ }
+ }, "expected EOFException");
+ final String m = ex.getMessage();
+ assertTrue(m.startsWith("Truncated ZIP entry: ?2016")); // the first character is not printable
+ }
+ }
+
@Test
public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingBzip2() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("bzip2-zip.zip"));
@@ -221,6 +250,27 @@ public class ZipArchiveInputStreamTest extends AbstractTestCase {
ZipArchiveEntry.NameSource.UNICODE_EXTRA_FIELD);
}
+ /**
+ * Test correct population of header and data offsets.
+ */
+ @Test
+ public void testOffsets() throws Exception {
+ // mixed.zip contains both inflated and stored files
+ try (InputStream archiveStream = ZipArchiveInputStream.class.getResourceAsStream("/mixed.zip");
+ ZipArchiveInputStream zipStream = new ZipArchiveInputStream(archiveStream)
+ ) {
+ final ZipArchiveEntry inflatedEntry = zipStream.getNextZipEntry();
+ assertEquals("inflated.txt", inflatedEntry.getName());
+ assertEquals(0x0000, inflatedEntry.getLocalHeaderOffset());
+ assertEquals(0x0046, inflatedEntry.getDataOffset());
+ final ZipArchiveEntry storedEntry = zipStream.getNextZipEntry();
+ assertEquals("stored.txt", storedEntry.getName());
+ assertEquals(0x5892, storedEntry.getLocalHeaderOffset());
+ assertEquals(0x58d6, storedEntry.getDataOffset());
+ assertNull(zipStream.getNextZipEntry());
+ }
+ }
+
@Test
public void testProperlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception {
// we never read any data
@@ -351,6 +401,22 @@ public class ZipArchiveInputStreamTest extends AbstractTestCase {
}
}
+ /**
+ * Test case for
+ * <a href="https://issues.apache.org/jira/browse/COMPRESS-264"
+ * >COMPRESS-264</a>.
+ */
+ @Test
+ public void testReadingOfFirstStoredEntry() throws Exception {
+
+ try (ZipArchiveInputStream in = new ZipArchiveInputStream(newInputStream("COMPRESS-264.zip"))) {
+ final ZipArchiveEntry ze = in.getNextZipEntry();
+ assertEquals(5, ze.getSize());
+ assertArrayEquals(new byte[] { 'd', 'a', 't', 'a', '\n' },
+ IOUtils.toByteArray(in));
+ }
+ }
+
@Test
public void testRejectsStoredEntriesWithDataDescriptorByDefault() throws IOException {
try (InputStream fs = newInputStream("bla-stored-dd.zip"); ZipArchiveInputStream archive = new ZipArchiveInputStream(fs)) {
@@ -385,16 +451,6 @@ public class ZipArchiveInputStreamTest extends AbstractTestCase {
}
}
- private void singleByteReadConsistentlyReturnsMinusOneAtEof(final File file) throws Exception {
- try (InputStream in = Files.newInputStream(file.toPath());
- ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) {
- final ArchiveEntry e = archive.getNextEntry();
- IOUtils.toByteArray(archive);
- assertEquals(-1, archive.read());
- assertEquals(-1, archive.read());
- }
- }
-
@Test
public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingBzip2() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("bzip2-zip.zip"));
@@ -444,62 +500,6 @@ public class ZipArchiveInputStreamTest extends AbstractTestCase {
}
}
- /**
- * Test case for
- * <a href="https://issues.apache.org/jira/browse/COMPRESS-351"
- * >COMPRESS-351</a>.
- */
- @Test
- public void testMessageWithCorruptFileName() throws Exception {
- try (ZipArchiveInputStream in = new ZipArchiveInputStream(newInputStream("COMPRESS-351.zip"))) {
- final EOFException ex = assertThrows(EOFException.class, () -> {
- ZipArchiveEntry ze = in.getNextZipEntry();
- while (ze != null) {
- ze = in.getNextZipEntry();
- }
- }, "expected EOFException");
- final String m = ex.getMessage();
- assertTrue(m.startsWith("Truncated ZIP entry: ?2016")); // the first character is not printable
- }
- }
-
- /**
- * Test correct population of header and data offsets.
- */
- @Test
- public void testOffsets() throws Exception {
- // mixed.zip contains both inflated and stored files
- try (InputStream archiveStream = ZipArchiveInputStream.class.getResourceAsStream("/mixed.zip");
- ZipArchiveInputStream zipStream = new ZipArchiveInputStream(archiveStream)
- ) {
- final ZipArchiveEntry inflatedEntry = zipStream.getNextZipEntry();
- assertEquals("inflated.txt", inflatedEntry.getName());
- assertEquals(0x0000, inflatedEntry.getLocalHeaderOffset());
- assertEquals(0x0046, inflatedEntry.getDataOffset());
- final ZipArchiveEntry storedEntry = zipStream.getNextZipEntry();
- assertEquals("stored.txt", storedEntry.getName());
- assertEquals(0x5892, storedEntry.getLocalHeaderOffset());
- assertEquals(0x58d6, storedEntry.getDataOffset());
- assertNull(zipStream.getNextZipEntry());
- }
- }
-
- /**
- * Test case for
- * <a href="https://issues.apache.org/jira/browse/COMPRESS-264"
- * >COMPRESS-264</a>.
- */
- @Test
- public void testReadingOfFirstStoredEntry() throws Exception {
-
- try (ZipArchiveInputStream in = new ZipArchiveInputStream(newInputStream("COMPRESS-264.zip"))) {
- final ZipArchiveEntry ze = in.getNextZipEntry();
- assertEquals(5, ze.getSize());
- assertArrayEquals(new byte[] { 'd', 'a', 't', 'a', '\n' },
- IOUtils.toByteArray(in));
- }
- }
-
@Test
public void testSplitZipCreatedByWinrar() throws IOException {
final File lastFile = getFile("COMPRESS-477/split_zip_created_by_winrar/split_zip_created_by_winrar.zip");
@@ -630,6 +630,19 @@ public class ZipArchiveInputStreamTest extends AbstractTestCase {
}
}
+ /**
+ * @see "https://issues.apache.org/jira/browse/COMPRESS-176"
+ */
+ @Test
+ public void testWinzipBackSlashWorkaround() throws Exception {
+ try (ZipArchiveInputStream in = new ZipArchiveInputStream(newInputStream("test-winzip.zip"))) {
+ ZipArchiveEntry zae = in.getNextZipEntry();
+ zae = in.getNextZipEntry();
+ zae = in.getNextZipEntry();
+ assertEquals("\u00e4/", zae.getName());
+ }
+ }
+
/**
* Test case for
* <a href="https://issues.apache.org/jira/browse/COMPRESS-364"
@@ -731,17 +744,4 @@ public class ZipArchiveInputStreamTest extends AbstractTestCase {
assertThrows(IOException.class, () -> getAllZipEntries(zipInputStream));
}
}
-
- /**
- * @see "https://issues.apache.org/jira/browse/COMPRESS-176"
- */
- @Test
- public void testWinzipBackSlashWorkaround() throws Exception {
- try (ZipArchiveInputStream in = new ZipArchiveInputStream(newInputStream("test-winzip.zip"))) {
- ZipArchiveEntry zae = in.getNextZipEntry();
- zae = in.getNextZipEntry();
- zae = in.getNextZipEntry();
- assertEquals("\u00e4/", zae.getName());
- }
- }
}
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileIgnoringLocalFileHeaderTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileIgnoringLocalFileHeaderTest.java
index a21cdcd7..ad603417 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileIgnoringLocalFileHeaderTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileIgnoringLocalFileHeaderTest.java
@@ -39,14 +39,6 @@ public class ZipFileIgnoringLocalFileHeaderTest {
@TempDir
private File dir;
- @Test
- public void testGetEntryWorks() throws IOException {
- try (final ZipFile zf = openZipWithoutLFH("bla.zip")) {
- final ZipArchiveEntry ze = zf.getEntry("test1.xml");
- assertEquals(610, ze.getSize());
- }
- }
-
@Test
public void testDuplicateEntry() throws Exception {
try (final ZipFile zf = openZipWithoutLFH("COMPRESS-227.zip")) {
@@ -61,6 +53,14 @@ public class ZipFileIgnoringLocalFileHeaderTest {
}
}
+ @Test
+ public void testGetEntryWorks() throws IOException {
+ try (final ZipFile zf = openZipWithoutLFH("bla.zip")) {
+ final ZipArchiveEntry ze = zf.getEntry("test1.xml");
+ assertEquals(610, ze.getSize());
+ }
+ }
+
@Test
public void testGetRawInputStreamReturnsNotNull() throws IOException {
try (final ZipFile zf = openZipWithoutLFH("bla.zip")) {
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java
index b61a86fb..beac0024 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java
@@ -161,57 +161,6 @@ public class ZipFileTest extends AbstractTestCase {
return crc.getValue();
}
- @Test
- public void testExtractFileLiesAcrossSplitZipSegmentsCreatedByWinrar() throws Exception {
- final File lastFile = getFile("COMPRESS-477/split_zip_created_by_winrar/split_zip_created_by_winrar.zip");
- try (final SeekableByteChannel channel = ZipSplitReadOnlySeekableByteChannel.buildFromLastSplitSegment(lastFile)) {
- zf = new ZipFile(channel);
-
- // the compressed content of ZipArchiveInputStream.java lies between .z01 and .z02
- final ZipArchiveEntry zipEntry = zf.getEntry("commons-compress/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java");
- final File fileToCompare = getFile("COMPRESS-477/split_zip_created_by_winrar/file_to_compare_1");
- assertFileEqualsToEntry(fileToCompare, zipEntry, zf);
- }
- }
-
- @Test
- public void testExtractFileLiesAcrossSplitZipSegmentsCreatedByZip() throws Exception {
- final File lastFile = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.zip");
- try (final SeekableByteChannel channel = ZipSplitReadOnlySeekableByteChannel.buildFromLastSplitSegment(lastFile)) {
- zf = new ZipFile(channel);
-
- // the compressed content of UnsupportedCompressionAlgorithmException.java lies between .z01 and .z02
- ZipArchiveEntry zipEntry = zf
- .getEntry("commons-compress/src/main/java/org/apache/commons/compress/archivers/dump/UnsupportedCompressionAlgorithmException.java");
- File fileToCompare = getFile("COMPRESS-477/split_zip_created_by_zip/file_to_compare_1");
- assertFileEqualsToEntry(fileToCompare, zipEntry, zf);
-
- // the compressed content of DeflateParameters.java lies between .z02 and .zip
- zipEntry = zf.getEntry("commons-compress/src/main/java/org/apache/commons/compress/compressors/deflate/DeflateParameters.java");
- fileToCompare = getFile("COMPRESS-477/split_zip_created_by_zip/file_to_compare_2");
- assertFileEqualsToEntry(fileToCompare, zipEntry, zf);
- }
- }
-
- @Test
- public void testExtractFileLiesAcrossSplitZipSegmentsCreatedByZipOfZip64() throws Exception {
- final File lastFile = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip_zip64.zip");
- try (final SeekableByteChannel channel = ZipSplitReadOnlySeekableByteChannel.buildFromLastSplitSegment(lastFile)) {
- zf = new ZipFile(channel);
-
- // the compressed content of UnsupportedCompressionAlgorithmException.java lies between .z01 and .z02
- ZipArchiveEntry zipEntry = zf
- .getEntry("commons-compress/src/main/java/org/apache/commons/compress/archivers/dump/UnsupportedCompressionAlgorithmException.java");
- File fileToCompare = getFile("COMPRESS-477/split_zip_created_by_zip/file_to_compare_1");
- assertFileEqualsToEntry(fileToCompare, zipEntry, zf);
-
- // the compressed content of DeflateParameters.java lies between .z02 and .zip
- zipEntry = zf.getEntry("commons-compress/src/main/java/org/apache/commons/compress/compressors/deflate/DeflateParameters.java");
- fileToCompare = getFile("COMPRESS-477/split_zip_created_by_zip/file_to_compare_2");
- assertFileEqualsToEntry(fileToCompare, zipEntry, zf);
- }
- }
-
private void multiByteReadConsistentlyReturnsMinusOneAtEof(final File file) throws Exception {
final byte[] buf = new byte[2];
try (ZipFile archive = new ZipFile(file)) {
@@ -224,71 +173,6 @@ public class ZipFileTest extends AbstractTestCase {
}
}
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingBzip2() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("bzip2-zip.zip"));
- }
-
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("bla.zip"));
- }
-
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate64() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("COMPRESS-380/COMPRESS-380.zip"));
- }
-
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingExplode() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("imploding-8Kdict-3trees.zip"));
- }
-
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingStore() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("COMPRESS-264.zip"));
- }
-
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingUnshrink() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("SHRUNK.ZIP"));
- }
-
- @Test
- public void testNameSourceDefaultsToName() throws Exception {
- nameSource("bla.zip", "test1.xml", ZipArchiveEntry.NameSource.NAME);
- }
-
- @Test
- public void testNameSourceIsSetToEFS() throws Exception {
- nameSource("utf8-7zip-test.zip", "\u20AC_for_Dollar.txt",
- ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG);
- }
-
- @Test
- public void testNameSourceIsSetToUnicodeExtraField() throws Exception {
- nameSource("utf8-winzip-test.zip", "\u20AC_for_Dollar.txt",
- ZipArchiveEntry.NameSource.UNICODE_EXTRA_FIELD);
- }
-
- /**
- * @see "https://issues.apache.org/jira/browse/COMPRESS-380"
- */
- @Test
- public void testReadDeflate64CompressedStream() throws Exception {
- final File input = getFile("COMPRESS-380/COMPRESS-380-input");
- final File archive = getFile("COMPRESS-380/COMPRESS-380.zip");
- try (InputStream in = Files.newInputStream(input.toPath());
- ZipFile zf = new ZipFile(archive)) {
- final byte[] orig = IOUtils.toByteArray(in);
- final ZipArchiveEntry e = zf.getEntry("input2");
- try (InputStream s = zf.getInputStream(e)) {
- final byte[] fromZip = IOUtils.toByteArray(s);
- assertArrayEquals(orig, fromZip);
- }
- }
- }
-
/*
* ordertest.zip has been handcrafted.
*
@@ -326,36 +210,6 @@ public class ZipFileTest extends AbstractTestCase {
}
}
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingBzip2() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("bzip2-zip.zip"));
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("bla.zip"));
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate64() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("COMPRESS-380/COMPRESS-380.zip"));
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingExplode() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("imploding-8Kdict-3trees.zip"));
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingStore() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("COMPRESS-264.zip"));
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingUnshrink() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("SHRUNK.ZIP"));
- }
-
@AfterEach
public void tearDownClose() {
ZipFile.closeQuietly(zf);
@@ -675,6 +529,57 @@ public class ZipFileTest extends AbstractTestCase {
assertEquals(26101, ze.getSize());
}
+ @Test
+ public void testExtractFileLiesAcrossSplitZipSegmentsCreatedByWinrar() throws Exception {
+ final File lastFile = getFile("COMPRESS-477/split_zip_created_by_winrar/split_zip_created_by_winrar.zip");
+ try (final SeekableByteChannel channel = ZipSplitReadOnlySeekableByteChannel.buildFromLastSplitSegment(lastFile)) {
+ zf = new ZipFile(channel);
+
+ // the compressed content of ZipArchiveInputStream.java lies between .z01 and .z02
+ final ZipArchiveEntry zipEntry = zf.getEntry("commons-compress/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java");
+ final File fileToCompare = getFile("COMPRESS-477/split_zip_created_by_winrar/file_to_compare_1");
+ assertFileEqualsToEntry(fileToCompare, zipEntry, zf);
+ }
+ }
+
+ @Test
+ public void testExtractFileLiesAcrossSplitZipSegmentsCreatedByZip() throws Exception {
+ final File lastFile = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.zip");
+ try (final SeekableByteChannel channel = ZipSplitReadOnlySeekableByteChannel.buildFromLastSplitSegment(lastFile)) {
+ zf = new ZipFile(channel);
+
+ // the compressed content of UnsupportedCompressionAlgorithmException.java lies between .z01 and .z02
+ ZipArchiveEntry zipEntry = zf
+ .getEntry("commons-compress/src/main/java/org/apache/commons/compress/archivers/dump/UnsupportedCompressionAlgorithmException.java");
+ File fileToCompare = getFile("COMPRESS-477/split_zip_created_by_zip/file_to_compare_1");
+ assertFileEqualsToEntry(fileToCompare, zipEntry, zf);
+
+ // the compressed content of DeflateParameters.java lies between .z02 and .zip
+ zipEntry = zf.getEntry("commons-compress/src/main/java/org/apache/commons/compress/compressors/deflate/DeflateParameters.java");
+ fileToCompare = getFile("COMPRESS-477/split_zip_created_by_zip/file_to_compare_2");
+ assertFileEqualsToEntry(fileToCompare, zipEntry, zf);
+ }
+ }
+
+ @Test
+ public void testExtractFileLiesAcrossSplitZipSegmentsCreatedByZipOfZip64() throws Exception {
+ final File lastFile = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip_zip64.zip");
+ try (final SeekableByteChannel channel = ZipSplitReadOnlySeekableByteChannel.buildFromLastSplitSegment(lastFile)) {
+ zf = new ZipFile(channel);
+
+ // the compressed content of UnsupportedCompressionAlgorithmException.java lies between .z01 and .z02
+ ZipArchiveEntry zipEntry = zf
+ .getEntry("commons-compress/src/main/java/org/apache/commons/compress/archivers/dump/UnsupportedCompressionAlgorithmException.java");
+ File fileToCompare = getFile("COMPRESS-477/split_zip_created_by_zip/file_to_compare_1");
+ assertFileEqualsToEntry(fileToCompare, zipEntry, zf);
+
+ // the compressed content of DeflateParameters.java lies between .z02 and .zip
+ zipEntry = zf.getEntry("commons-compress/src/main/java/org/apache/commons/compress/compressors/deflate/DeflateParameters.java");
+ fileToCompare = getFile("COMPRESS-477/split_zip_created_by_zip/file_to_compare_2");
+ assertFileEqualsToEntry(fileToCompare, zipEntry, zf);
+ }
+ }
+
/**
* Test non power of 2 alignment.
*/
@@ -683,6 +588,53 @@ public class ZipFileTest extends AbstractTestCase {
assertThrows(IllegalArgumentException.class, () -> new ZipArchiveEntry("dummy").setAlignment(3));
}
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingBzip2() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("bzip2-zip.zip"));
+ }
+
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("bla.zip"));
+ }
+
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate64() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("COMPRESS-380/COMPRESS-380.zip"));
+ }
+
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingExplode() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("imploding-8Kdict-3trees.zip"));
+ }
+
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingStore() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("COMPRESS-264.zip"));
+ }
+
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEofUsingUnshrink() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(getFile("SHRUNK.ZIP"));
+ }
+
+ @Test
+ public void testNameSourceDefaultsToName() throws Exception {
+ nameSource("bla.zip", "test1.xml", ZipArchiveEntry.NameSource.NAME);
+ }
+
+ @Test
+ public void testNameSourceIsSetToEFS() throws Exception {
+ nameSource("utf8-7zip-test.zip", "\u20AC_for_Dollar.txt",
+ ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG);
+ }
+
+ @Test
+ public void testNameSourceIsSetToUnicodeExtraField() throws Exception {
+ nameSource("utf8-winzip-test.zip", "\u20AC_for_Dollar.txt",
+ ZipArchiveEntry.NameSource.UNICODE_EXTRA_FIELD);
+ }
+
/**
* Test correct population of header and data offsets.
*/
@@ -743,6 +695,24 @@ public class ZipFileTest extends AbstractTestCase {
assertFalse(iter.hasNext());
}
+ /**
+ * @see "https://issues.apache.org/jira/browse/COMPRESS-380"
+ */
+ @Test
+ public void testReadDeflate64CompressedStream() throws Exception {
+ final File input = getFile("COMPRESS-380/COMPRESS-380-input");
+ final File archive = getFile("COMPRESS-380/COMPRESS-380.zip");
+ try (InputStream in = Files.newInputStream(input.toPath());
+ ZipFile zf = new ZipFile(archive)) {
+ final byte[] orig = IOUtils.toByteArray(in);
+ final ZipArchiveEntry e = zf.getEntry("input2");
+ try (InputStream s = zf.getInputStream(e)) {
+ final byte[] fromZip = IOUtils.toByteArray(s);
+ assertArrayEquals(orig, fromZip);
+ }
+ }
+ }
+
/**
* Test case for
* <a href="https://issues.apache.org/jira/browse/COMPRESS-621"
@@ -891,6 +861,36 @@ public class ZipFileTest extends AbstractTestCase {
assertThrows(IllegalArgumentException.class, () -> fixture.setLevel(Deflater.DEFAULT_COMPRESSION - 1));
}
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingBzip2() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("bzip2-zip.zip"));
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("bla.zip"));
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate64() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("COMPRESS-380/COMPRESS-380.zip"));
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingExplode() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("imploding-8Kdict-3trees.zip"));
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingStore() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("COMPRESS-264.zip"));
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEofUsingUnshrink() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(getFile("SHRUNK.ZIP"));
+ }
+
/**
* Test case for
* <a href="https://issues.apache.org/jira/browse/COMPRESS-208"
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/ZipMemoryFileSystemTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/ZipMemoryFileSystemTest.java
index 8c81d367..c69f7727 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/ZipMemoryFileSystemTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/ZipMemoryFileSystemTest.java
@@ -70,6 +70,23 @@ public class ZipMemoryFileSystemTest {
return () -> payload;
}
+ @BeforeEach
+ public void setup() throws IOException {
+ dir = Files.createTempDirectory(UUID.randomUUID().toString());
+ }
+
+ @AfterEach
+ public void tearDown() throws IOException {
+ try (Stream<Path> walk = Files.walk(dir)) {
+ walk.sorted(Comparator.reverseOrder()).peek(path -> println("Deleting: " + path.toAbsolutePath())).forEach(path -> {
+ try {
+ Files.deleteIfExists(path);
+ } catch (final IOException ignore) {
+ }
+ });
+ }
+ }
+
@Test
public void testForPathsReturnCorrectClassInMemory() throws IOException {
final Path firstFile = getPath("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.z01");
@@ -255,23 +272,6 @@ public class ZipMemoryFileSystemTest {
}
- @BeforeEach
- public void setup() throws IOException {
- dir = Files.createTempDirectory(UUID.randomUUID().toString());
- }
-
- @AfterEach
- public void tearDown() throws IOException {
- try (Stream<Path> walk = Files.walk(dir)) {
- walk.sorted(Comparator.reverseOrder()).peek(path -> println("Deleting: " + path.toAbsolutePath())).forEach(path -> {
- try {
- Files.deleteIfExists(path);
- } catch (final IOException ignore) {
- }
- });
- }
- }
-
@Test
public void testZipFileInMemory() throws IOException {
try (FileSystem fileSystem = MemoryFileSystemBuilder.newLinux().build()) {
diff --git a/src/test/java/org/apache/commons/compress/archivers/zip/ZipSplitOutputStreamTest.java b/src/test/java/org/apache/commons/compress/archivers/zip/ZipSplitOutputStreamTest.java
index 24a3a293..39e7b7c5 100644
--- a/src/test/java/org/apache/commons/compress/archivers/zip/ZipSplitOutputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/archivers/zip/ZipSplitOutputStreamTest.java
@@ -30,18 +30,6 @@ import org.junit.jupiter.api.Test;
public class ZipSplitOutputStreamTest extends AbstractTestCase {
- @Test
- public void testSplitZipBeginsWithZipSplitSignature() throws IOException {
- final File tempFile = File.createTempFile("temp", "zip");
- new ZipSplitOutputStream(tempFile, 100 * 1024L);
-
- final InputStream inputStream = Files.newInputStream(tempFile.toPath());
- final byte[] buffer = new byte[4];
- inputStream.read(buffer);
-
- assertEquals(ByteBuffer.wrap(ZipArchiveOutputStream.DD_SIG).getInt(), ByteBuffer.wrap(buffer).getInt());
- }
-
@Test
public void testCreateSplittedFiles() throws IOException {
final File testOutputFile = new File(dir, "testCreateSplittedFiles.zip");
@@ -79,6 +67,18 @@ public class ZipSplitOutputStreamTest extends AbstractTestCase {
assertEquals(zipFile.length(), fileToTest.length() + 4 - splitSize * 5);
}
+ @Test
+ public void testSplitZipBeginsWithZipSplitSignature() throws IOException {
+ final File tempFile = File.createTempFile("temp", "zip");
+ new ZipSplitOutputStream(tempFile, 100 * 1024L);
+
+ final InputStream inputStream = Files.newInputStream(tempFile.toPath());
+ final byte[] buffer = new byte[4];
+ inputStream.read(buffer);
+
+ assertEquals(ByteBuffer.wrap(ZipArchiveOutputStream.DD_SIG).getInt(), ByteBuffer.wrap(buffer).getInt());
+ }
+
@Test
public void throwsExceptionIfSplitSizeIsTooLarge() {
assertThrows(IllegalArgumentException.class, () -> new ZipSplitOutputStream(File.createTempFile("temp", "zip"), 4 * 1024 * 1024 * 1024L));
diff --git a/src/test/java/org/apache/commons/compress/compressors/GZipTestCase.java b/src/test/java/org/apache/commons/compress/compressors/GZipTestCase.java
index 92e00206..e16009ba 100644
--- a/src/test/java/org/apache/commons/compress/compressors/GZipTestCase.java
+++ b/src/test/java/org/apache/commons/compress/compressors/GZipTestCase.java
@@ -43,29 +43,6 @@ import org.junit.jupiter.params.provider.ValueSource;
public final class GZipTestCase extends AbstractTestCase {
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
- final File input = getFile("bla.tgz");
- final byte[] buf = new byte[2];
- try (InputStream is = Files.newInputStream(input.toPath());
- final GzipCompressorInputStream in = new GzipCompressorInputStream(is)) {
- IOUtils.toByteArray(in);
- assertEquals(-1, in.read(buf));
- assertEquals(-1, in.read(buf));
- }
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
- final File input = getFile("bla.tgz");
- try (InputStream is = Files.newInputStream(input.toPath());
- final GzipCompressorInputStream in = new GzipCompressorInputStream(is)) {
- IOUtils.toByteArray(in);
- assertEquals(-1, in.read());
- assertEquals(-1, in.read());
- }
- }
-
@Test
public void testConcatenatedStreamsReadFirstOnly() throws Exception {
final File input = getFile("multiple.gz");
@@ -259,10 +236,33 @@ public final class GZipTestCase extends AbstractTestCase {
assertEquals("Umlaute möglich?", readParams.getComment());
}
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
+ final File input = getFile("bla.tgz");
+ final byte[] buf = new byte[2];
+ try (InputStream is = Files.newInputStream(input.toPath());
+ final GzipCompressorInputStream in = new GzipCompressorInputStream(is)) {
+ IOUtils.toByteArray(in);
+ assertEquals(-1, in.read(buf));
+ assertEquals(-1, in.read(buf));
+ }
+ }
+
@Test
public void testOverWrite() throws Exception {
final GzipCompressorOutputStream out = new GzipCompressorOutputStream(new ByteArrayOutputStream());
out.close();
assertThrows(IOException.class, () -> out.write(0), "IOException expected");
}
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
+ final File input = getFile("bla.tgz");
+ try (InputStream is = Files.newInputStream(input.toPath());
+ final GzipCompressorInputStream in = new GzipCompressorInputStream(is)) {
+ IOUtils.toByteArray(in);
+ assertEquals(-1, in.read());
+ assertEquals(-1, in.read());
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/compress/compressors/LZMATestCase.java b/src/test/java/org/apache/commons/compress/compressors/LZMATestCase.java
index 9356bdf9..b9ecdef5 100644
--- a/src/test/java/org/apache/commons/compress/compressors/LZMATestCase.java
+++ b/src/test/java/org/apache/commons/compress/compressors/LZMATestCase.java
@@ -53,48 +53,48 @@ public final class LZMATestCase extends AbstractTestCase {
}
@Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
+ public void testLZMAUnarchive() throws Exception {
final File input = getFile("bla.tar.lzma");
- final byte[] buf = new byte[2];
+ final File output = new File(dir, "bla.tar");
try (InputStream is = Files.newInputStream(input.toPath())) {
- try (LZMACompressorInputStream in = new LZMACompressorInputStream(is)) {
- IOUtils.toByteArray(in);
- assertEquals(-1, in.read(buf));
- assertEquals(-1, in.read(buf));
+ try (final CompressorInputStream in = new LZMACompressorInputStream(is)) {
+ Files.copy(in, output.toPath());
}
}
}
@Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
+ public void testLZMAUnarchiveWithAutodetection() throws Exception {
final File input = getFile("bla.tar.lzma");
- try (InputStream is = Files.newInputStream(input.toPath())) {
- try (LZMACompressorInputStream in = new LZMACompressorInputStream(is)) {
- IOUtils.toByteArray(in);
- assertEquals(-1, in.read());
- assertEquals(-1, in.read());
+ final File output = new File(dir, "bla.tar");
+ try (InputStream is = new BufferedInputStream(Files.newInputStream(input.toPath()))) {
+ try (final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream(is)) {
+ Files.copy(in, output.toPath());
}
}
}
@Test
- public void testLZMAUnarchive() throws Exception {
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
final File input = getFile("bla.tar.lzma");
- final File output = new File(dir, "bla.tar");
+ final byte[] buf = new byte[2];
try (InputStream is = Files.newInputStream(input.toPath())) {
- try (final CompressorInputStream in = new LZMACompressorInputStream(is)) {
- Files.copy(in, output.toPath());
+ try (LZMACompressorInputStream in = new LZMACompressorInputStream(is)) {
+ IOUtils.toByteArray(in);
+ assertEquals(-1, in.read(buf));
+ assertEquals(-1, in.read(buf));
}
}
}
@Test
- public void testLZMAUnarchiveWithAutodetection() throws Exception {
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
final File input = getFile("bla.tar.lzma");
- final File output = new File(dir, "bla.tar");
- try (InputStream is = new BufferedInputStream(Files.newInputStream(input.toPath()))) {
- try (final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream(is)) {
- Files.copy(in, output.toPath());
+ try (InputStream is = Files.newInputStream(input.toPath())) {
+ try (LZMACompressorInputStream in = new LZMACompressorInputStream(is)) {
+ IOUtils.toByteArray(in);
+ assertEquals(-1, in.read());
+ assertEquals(-1, in.read());
}
}
}
diff --git a/src/test/java/org/apache/commons/compress/compressors/Pack200TestCase.java b/src/test/java/org/apache/commons/compress/compressors/Pack200TestCase.java
index a9e21169..42bc864f 100644
--- a/src/test/java/org/apache/commons/compress/compressors/Pack200TestCase.java
+++ b/src/test/java/org/apache/commons/compress/compressors/Pack200TestCase.java
@@ -105,16 +105,6 @@ public final class Pack200TestCase extends AbstractTestCase {
}
}
- @Test
- public void testMultiByteReadFromMemoryConsistentlyReturnsMinusOneAtEof() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(Pack200Strategy.IN_MEMORY);
- }
-
- @Test
- public void testMultiByteReadFromTempFileConsistentlyReturnsMinusOneAtEof() throws Exception {
- multiByteReadConsistentlyReturnsMinusOneAtEof(Pack200Strategy.TEMP_FILE);
- }
-
private void singleByteReadConsistentlyReturnsMinusOneAtEof(final Pack200Strategy s) throws Exception {
final File input = getFile("bla.pack");
try (final Pack200CompressorInputStream in = new Pack200CompressorInputStream(input, s)) {
@@ -124,16 +114,6 @@ public final class Pack200TestCase extends AbstractTestCase {
}
}
- @Test
- public void testSingleByteReadFromMemoryConsistentlyReturnsMinusOneAtEof() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(Pack200Strategy.IN_MEMORY);
- }
-
- @Test
- public void testSingleByteReadFromTempFileConsistentlyReturnsMinusOneAtEof() throws Exception {
- singleByteReadConsistentlyReturnsMinusOneAtEof(Pack200Strategy.TEMP_FILE);
- }
-
@Test
public void testBadSignature() throws Exception {
try (InputStream is = newInputStream("bla.jar")) {
@@ -205,6 +185,16 @@ public final class Pack200TestCase extends AbstractTestCase {
jarUnarchiveAll(false, Pack200Strategy.TEMP_FILE);
}
+ @Test
+ public void testMultiByteReadFromMemoryConsistentlyReturnsMinusOneAtEof() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(Pack200Strategy.IN_MEMORY);
+ }
+
+ @Test
+ public void testMultiByteReadFromTempFileConsistentlyReturnsMinusOneAtEof() throws Exception {
+ multiByteReadConsistentlyReturnsMinusOneAtEof(Pack200Strategy.TEMP_FILE);
+ }
+
@Test
public void testOutputStreamMethods() throws Exception {
final File output = new File(dir, "bla.pack");
@@ -226,4 +216,14 @@ public final class Pack200TestCase extends AbstractTestCase {
}
}
+ @Test
+ public void testSingleByteReadFromMemoryConsistentlyReturnsMinusOneAtEof() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(Pack200Strategy.IN_MEMORY);
+ }
+
+ @Test
+ public void testSingleByteReadFromTempFileConsistentlyReturnsMinusOneAtEof() throws Exception {
+ singleByteReadConsistentlyReturnsMinusOneAtEof(Pack200Strategy.TEMP_FILE);
+ }
+
}
diff --git a/src/test/java/org/apache/commons/compress/compressors/brotli/BrotliCompressorInputStreamTest.java b/src/test/java/org/apache/commons/compress/compressors/brotli/BrotliCompressorInputStreamTest.java
index d480be0f..7aba9e1a 100644
--- a/src/test/java/org/apache/commons/compress/compressors/brotli/BrotliCompressorInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/brotli/BrotliCompressorInputStreamTest.java
@@ -43,44 +43,6 @@ public class BrotliCompressorInputStreamTest extends AbstractTestCase {
}
}
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
- final byte[] buf = new byte[2];
- try (InputStream is = newInputStream("brotli.testdata.compressed");
- final BrotliCompressorInputStream in = new BrotliCompressorInputStream(is)) {
- IOUtils.toByteArray(in);
- assertEquals(-1, in.read(buf));
- assertEquals(-1, in.read(buf));
- }
- }
-
- @Test
- public void testShouldBeAbleToSkipAByte() throws IOException {
- try (InputStream is = newInputStream("brotli.testdata.compressed");
- final BrotliCompressorInputStream in = new BrotliCompressorInputStream(is)) {
- assertEquals(1, in.skip(1));
- }
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
- try (InputStream is = newInputStream("brotli.testdata.compressed");
- final BrotliCompressorInputStream in = new BrotliCompressorInputStream(is)) {
- IOUtils.toByteArray(in);
- assertEquals(-1, in.read());
- assertEquals(-1, in.read());
- }
- }
-
- @Test
- public void testSingleByteReadWorksAsExpected() throws IOException {
- try (InputStream is = newInputStream("brotli.testdata.compressed");
- final BrotliCompressorInputStream in = new BrotliCompressorInputStream(is)) {
- // starts with file name "XXX"
- assertEquals('X', in.read());
- }
- }
-
/**
* Test bridge works fine.
*
@@ -129,6 +91,44 @@ public class BrotliCompressorInputStreamTest extends AbstractTestCase {
}
}
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
+ final byte[] buf = new byte[2];
+ try (InputStream is = newInputStream("brotli.testdata.compressed");
+ final BrotliCompressorInputStream in = new BrotliCompressorInputStream(is)) {
+ IOUtils.toByteArray(in);
+ assertEquals(-1, in.read(buf));
+ assertEquals(-1, in.read(buf));
+ }
+ }
+
+ @Test
+ public void testShouldBeAbleToSkipAByte() throws IOException {
+ try (InputStream is = newInputStream("brotli.testdata.compressed");
+ final BrotliCompressorInputStream in = new BrotliCompressorInputStream(is)) {
+ assertEquals(1, in.skip(1));
+ }
+ }
+
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
+ try (InputStream is = newInputStream("brotli.testdata.compressed");
+ final BrotliCompressorInputStream in = new BrotliCompressorInputStream(is)) {
+ IOUtils.toByteArray(in);
+ assertEquals(-1, in.read());
+ assertEquals(-1, in.read());
+ }
+ }
+
+ @Test
+ public void testSingleByteReadWorksAsExpected() throws IOException {
+ try (InputStream is = newInputStream("brotli.testdata.compressed");
+ final BrotliCompressorInputStream in = new BrotliCompressorInputStream(is)) {
+ // starts with file name "XXX"
+ assertEquals('X', in.read());
+ }
+ }
+
@Test
public void testTurningOnCachingReEvaluatesAvailability() {
try {
diff --git a/src/test/java/org/apache/commons/compress/compressors/deflate64/Deflate64CompressorInputStreamTest.java b/src/test/java/org/apache/commons/compress/compressors/deflate64/Deflate64CompressorInputStreamTest.java
index 810b91d2..1a51f15e 100644
--- a/src/test/java/org/apache/commons/compress/compressors/deflate64/Deflate64CompressorInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/deflate64/Deflate64CompressorInputStreamTest.java
@@ -46,6 +46,18 @@ public class Deflate64CompressorInputStreamTest {
@Mock
private HuffmanDecoder decoder;
+ private void fuzzingTest(final int[] bytes) throws IOException, ArchiveException {
+ final int len = bytes.length;
+ final byte[] input = new byte[len];
+ for (int i = 0; i < len; i++) {
+ input[i] = (byte) bytes[i];
+ }
+ try (ArchiveInputStream<?> ais = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("zip", new ByteArrayInputStream(input))) {
+ ais.getNextEntry();
+ IOUtils.toByteArray(ais);
+ }
+ }
+
@Test
public void testCloseCallsDecoder() throws Exception {
@@ -75,18 +87,6 @@ public class Deflate64CompressorInputStreamTest {
}
}
- private void fuzzingTest(final int[] bytes) throws IOException, ArchiveException {
- final int len = bytes.length;
- final byte[] input = new byte[len];
- for (int i = 0; i < len; i++) {
- input[i] = (byte) bytes[i];
- }
- try (ArchiveInputStream<?> ais = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("zip", new ByteArrayInputStream(input))) {
- ais.getNextEntry();
- IOUtils.toByteArray(ais);
- }
- }
-
@Test
public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws Exception {
final byte[] buf = new byte[2];
diff --git a/src/test/java/org/apache/commons/compress/compressors/lz4/BlockLZ4CompressorOutputStreamTest.java b/src/test/java/org/apache/commons/compress/compressors/lz4/BlockLZ4CompressorOutputStreamTest.java
index a49534c3..36b14081 100644
--- a/src/test/java/org/apache/commons/compress/compressors/lz4/BlockLZ4CompressorOutputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/lz4/BlockLZ4CompressorOutputStreamTest.java
@@ -33,6 +33,52 @@ import org.junit.jupiter.api.Test;
public class BlockLZ4CompressorOutputStreamTest {
+ @Test
+ @Disabled("would pass if the algorithm used for rewriting the final pairs was smarter")
+ public void canWriteBackReferenceFollowedByShortLiteralIfLengthIsBigEnough() {
+ final BlockLZ4CompressorOutputStream.Pair p = new BlockLZ4CompressorOutputStream.Pair();
+ p.setBackReference(new LZ77Compressor.BackReference(1, 10));
+ assertTrue(p.canBeWritten(5));
+ }
+
+ @Test
+ @Disabled("would pass if the algorithm used for rewriting the final pairs was smarter")
+ public void canWriteBackReferenceFollowedByShortLiteralIfOffsetIsBigEnough() {
+ final BlockLZ4CompressorOutputStream.Pair p = new BlockLZ4CompressorOutputStream.Pair();
+ p.setBackReference(new LZ77Compressor.BackReference(10, 4));
+ assertTrue(p.canBeWritten(5));
+ }
+
+ private byte[] compress(final byte[] input, final int... lengthOfTrailers) throws IOException {
+ try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ BlockLZ4CompressorOutputStream lo = new BlockLZ4CompressorOutputStream(baos)) {
+ lo.write(input);
+ for (int i = 0; i < lengthOfTrailers.length; i++) {
+ final int lengthOfTrailer = lengthOfTrailers[i];
+ for (int j = 0; j < lengthOfTrailer; j++) {
+ lo.write(i + 1);
+ }
+ }
+ lo.close();
+ return baos.toByteArray();
+ }
+ }
+
+ private byte[] compress(final int length) throws IOException {
+ return compress(length, 0);
+ }
+
+ private byte[] compress(final int lengthBeforeTrailer, final int... lengthOfTrailers) throws IOException {
+ final byte[] b = prepareExpected(lengthBeforeTrailer);
+ return compress(b, lengthOfTrailers);
+ }
+
+ private byte[] prepareExpected(final int length) {
+ final byte[] b = new byte[length];
+ Arrays.fill(b, (byte) -1);
+ return b;
+ }
+
@Test
public void testCantWriteBackReferenceFollowedByLiteralThatIsTooShort() {
final BlockLZ4CompressorOutputStream.Pair p = new BlockLZ4CompressorOutputStream.Pair();
@@ -57,22 +103,6 @@ public class BlockLZ4CompressorOutputStreamTest {
assertTrue(p.canBeWritten(16));
}
- @Test
- @Disabled("would pass if the algorithm used for rewriting the final pairs was smarter")
- public void canWriteBackReferenceFollowedByShortLiteralIfLengthIsBigEnough() {
- final BlockLZ4CompressorOutputStream.Pair p = new BlockLZ4CompressorOutputStream.Pair();
- p.setBackReference(new LZ77Compressor.BackReference(1, 10));
- assertTrue(p.canBeWritten(5));
- }
-
- @Test
- @Disabled("would pass if the algorithm used for rewriting the final pairs was smarter")
- public void canWriteBackReferenceFollowedByShortLiteralIfOffsetIsBigEnough() {
- final BlockLZ4CompressorOutputStream.Pair p = new BlockLZ4CompressorOutputStream.Pair();
- p.setBackReference(new LZ77Compressor.BackReference(10, 4));
- assertTrue(p.canBeWritten(5));
- }
-
@Test
public void testCanWritePairWithoutBackReference() throws IOException {
final BlockLZ4CompressorOutputStream.Pair p = new BlockLZ4CompressorOutputStream.Pair();
@@ -92,30 +122,6 @@ public class BlockLZ4CompressorOutputStreamTest {
assertArrayEquals(new byte[] { 0, 1, 0 }, bos.toByteArray());
}
- private byte[] compress(final byte[] input, final int... lengthOfTrailers) throws IOException {
- try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
- BlockLZ4CompressorOutputStream lo = new BlockLZ4CompressorOutputStream(baos)) {
- lo.write(input);
- for (int i = 0; i < lengthOfTrailers.length; i++) {
- final int lengthOfTrailer = lengthOfTrailers[i];
- for (int j = 0; j < lengthOfTrailer; j++) {
- lo.write(i + 1);
- }
- }
- lo.close();
- return baos.toByteArray();
- }
- }
-
- private byte[] compress(final int length) throws IOException {
- return compress(length, 0);
- }
-
- private byte[] compress(final int lengthBeforeTrailer, final int... lengthOfTrailers) throws IOException {
- final byte[] b = prepareExpected(lengthBeforeTrailer);
- return compress(b, lengthOfTrailers);
- }
-
@Test
public void testPairAccumulatesLengths() {
final BlockLZ4CompressorOutputStream.Pair p = new BlockLZ4CompressorOutputStream.Pair();
@@ -134,12 +140,6 @@ public class BlockLZ4CompressorOutputStreamTest {
assertTrue(p.hasBackReference());
}
- private byte[] prepareExpected(final int length) {
- final byte[] b = new byte[length];
- Arrays.fill(b, (byte) -1);
- return b;
- }
-
@Test
public void testRewritingOfFinalBlockWithoutTrailingLZ77Literals() throws IOException {
for (int i = 1; i < 13; i++) {
diff --git a/src/test/java/org/apache/commons/compress/compressors/lz4/FactoryTest.java b/src/test/java/org/apache/commons/compress/compressors/lz4/FactoryTest.java
index 3a3939e7..a91e793b 100644
--- a/src/test/java/org/apache/commons/compress/compressors/lz4/FactoryTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/lz4/FactoryTest.java
@@ -32,16 +32,6 @@ import org.junit.jupiter.api.Test;
public class FactoryTest extends AbstractTestCase {
- @Test
- public void testBlockRoundtripViaFactory() throws Exception {
- roundtripViaFactory(CompressorStreamFactory.getLZ4Block());
- }
-
- @Test
- public void testFrameRoundtripViaFactory() throws Exception {
- roundtripViaFactory(CompressorStreamFactory.getLZ4Framed());
- }
-
private void roundtripViaFactory(final String format) throws Exception {
final Path input = getPath("bla.tar");
long start = System.currentTimeMillis();
@@ -61,4 +51,14 @@ public class FactoryTest extends AbstractTestCase {
}
// System.err.println(outputSz.getName() + " read after " + (System.currentTimeMillis() - start) + "ms");
}
+
+ @Test
+ public void testBlockRoundtripViaFactory() throws Exception {
+ roundtripViaFactory(CompressorStreamFactory.getLZ4Block());
+ }
+
+ @Test
+ public void testFrameRoundtripViaFactory() throws Exception {
+ roundtripViaFactory(CompressorStreamFactory.getLZ4Framed());
+ }
}
diff --git a/src/test/java/org/apache/commons/compress/compressors/lz4/FramedLZ4CompressorInputStreamTest.java b/src/test/java/org/apache/commons/compress/compressors/lz4/FramedLZ4CompressorInputStreamTest.java
index eb1356c2..931f5be8 100644
--- a/src/test/java/org/apache/commons/compress/compressors/lz4/FramedLZ4CompressorInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/lz4/FramedLZ4CompressorInputStreamTest.java
@@ -52,6 +52,29 @@ public final class FramedLZ4CompressorInputStreamTest extends AbstractTestCase {
return to;
}
+ private void expectIOException(final String fileName) {
+ assertThrows(IOException.class, () -> {
+ try (InputStream is = Files.newInputStream(getFile(fileName).toPath());
+ final FramedLZ4CompressorInputStream in = new FramedLZ4CompressorInputStream(is)) {
+ IOUtils.toByteArray(in);
+ }
+ });
+ }
+
+ private void readDoubledBlaLz4(final StreamWrapper wrapper, final boolean expectDuplicateOutput) throws Exception {
+ byte[] singleInput;
+ try (InputStream i = newInputStream("bla.tar.lz4")) {
+ singleInput = IOUtils.toByteArray(i);
+ }
+ final byte[] input = duplicate(singleInput);
+ try (InputStream a = wrapper.wrap(new ByteArrayInputStream(input));
+ InputStream e = newInputStream("bla.tar")) {
+ final byte[] expected = IOUtils.toByteArray(e);
+ final byte[] actual = IOUtils.toByteArray(a);
+ assertArrayEquals(expectDuplicateOutput ? duplicate(expected) : expected, actual);
+ }
+ }
+
@Test
public void testBackreferenceAtStartCausesIOException() {
expectIOException("COMPRESS-490/ArrayIndexOutOfBoundsException1.lz4");
@@ -67,13 +90,14 @@ public final class FramedLZ4CompressorInputStreamTest extends AbstractTestCase {
expectIOException("COMPRESS-490/ArrayIndexOutOfBoundsException2.lz4");
}
- private void expectIOException(final String fileName) {
- assertThrows(IOException.class, () -> {
- try (InputStream is = Files.newInputStream(getFile(fileName).toPath());
- final FramedLZ4CompressorInputStream in = new FramedLZ4CompressorInputStream(is)) {
- IOUtils.toByteArray(in);
- }
- });
+ @Test
+ public void testMatches() throws IOException {
+ assertFalse(FramedLZ4CompressorInputStream.matches(new byte[10], 4));
+ final byte[] b = new byte[12];
+ IOUtils.read(getFile("bla.tar.lz4"), b);
+ assertFalse(FramedLZ4CompressorInputStream.matches(b, 3));
+ assertTrue(FramedLZ4CompressorInputStream.matches(b, 4));
+ assertTrue(FramedLZ4CompressorInputStream.matches(b, 5));
}
@Test
@@ -154,20 +178,6 @@ public final class FramedLZ4CompressorInputStreamTest extends AbstractTestCase {
}
}
- private void readDoubledBlaLz4(final StreamWrapper wrapper, final boolean expectDuplicateOutput) throws Exception {
- byte[] singleInput;
- try (InputStream i = newInputStream("bla.tar.lz4")) {
- singleInput = IOUtils.toByteArray(i);
- }
- final byte[] input = duplicate(singleInput);
- try (InputStream a = wrapper.wrap(new ByteArrayInputStream(input));
- InputStream e = newInputStream("bla.tar")) {
- final byte[] expected = IOUtils.toByteArray(e);
- final byte[] actual = IOUtils.toByteArray(a);
- assertArrayEquals(expectDuplicateOutput ? duplicate(expected) : expected, actual);
- }
- }
-
@Test
public void testReadDoubledBlaLz4ViaFactoryWithDecompressConcatenatedFalse() throws Exception {
readDoubledBlaLz4(in -> new CompressorStreamFactory()
@@ -592,14 +602,4 @@ public final class FramedLZ4CompressorInputStreamTest extends AbstractTestCase {
}
}
- @Test
- public void testMatches() throws IOException {
- assertFalse(FramedLZ4CompressorInputStream.matches(new byte[10], 4));
- final byte[] b = new byte[12];
- IOUtils.read(getFile("bla.tar.lz4"), b);
- assertFalse(FramedLZ4CompressorInputStream.matches(b, 3));
- assertTrue(FramedLZ4CompressorInputStream.matches(b, 4));
- assertTrue(FramedLZ4CompressorInputStream.matches(b, 5));
- }
-
}
diff --git a/src/test/java/org/apache/commons/compress/compressors/lz77support/LZ77CompressorTest.java b/src/test/java/org/apache/commons/compress/compressors/lz77support/LZ77CompressorTest.java
index ef218343..a97d4877 100644
--- a/src/test/java/org/apache/commons/compress/compressors/lz77support/LZ77CompressorTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/lz77support/LZ77CompressorTest.java
@@ -106,6 +106,29 @@ public class LZ77CompressorTest {
return r;
}
+ private List<LZ77Compressor.Block> compress(final Parameters params, final byte[]... chunks) throws IOException {
+ final List<LZ77Compressor.Block> blocks = new ArrayList<>();
+ final LZ77Compressor c = new LZ77Compressor(params, block -> {
+ //System.err.println(block);
+ if (block instanceof LZ77Compressor.LiteralBlock) {
+ // replace with a real copy of data so tests
+ // can see the results as they've been when
+ // the callback has been called
+ final LZ77Compressor.LiteralBlock b = (LZ77Compressor.LiteralBlock) block;
+ final int len = b.getLength();
+ block = new LZ77Compressor.LiteralBlock(
+ Arrays.copyOfRange(b.getData(), b.getOffset(), b.getOffset() + len),
+ 0, len);
+ }
+ blocks.add(block);
+ });
+ for (final byte[] chunk : chunks) {
+ c.compress(chunk);
+ }
+ c.finish();
+ return blocks;
+ }
+
@Test
public void testBlaExampleSmallerWindowSize() throws IOException {
final List<LZ77Compressor.Block> blocks = compress(newParameters(8), BLA);
@@ -246,29 +269,6 @@ public class LZ77CompressorTest {
assertThrows(IllegalStateException.class, () -> c.prefill(Arrays.copyOfRange(BLA, 2, 4)));
}
- private List<LZ77Compressor.Block> compress(final Parameters params, final byte[]... chunks) throws IOException {
- final List<LZ77Compressor.Block> blocks = new ArrayList<>();
- final LZ77Compressor c = new LZ77Compressor(params, block -> {
- //System.err.println(block);
- if (block instanceof LZ77Compressor.LiteralBlock) {
- // replace with a real copy of data so tests
- // can see the results as they've been when
- // the callback has been called
- final LZ77Compressor.LiteralBlock b = (LZ77Compressor.LiteralBlock) block;
- final int len = b.getLength();
- block = new LZ77Compressor.LiteralBlock(
- Arrays.copyOfRange(b.getData(), b.getOffset(), b.getOffset() + len),
- 0, len);
- }
- blocks.add(block);
- });
- for (final byte[] chunk : chunks) {
- c.compress(chunk);
- }
- c.finish();
- return blocks;
- }
-
@Test
public void testNonCompressableSentAsSingleBytes() throws IOException {
final List<LZ77Compressor.Block> blocks = compress(newParameters(8), stagger(ONE_TO_TEN));
diff --git a/src/test/java/org/apache/commons/compress/compressors/snappy/FramedSnappyCompressorInputStreamTest.java b/src/test/java/org/apache/commons/compress/compressors/snappy/FramedSnappyCompressorInputStreamTest.java
index 6c52322d..fa04bdcb 100644
--- a/src/test/java/org/apache/commons/compress/compressors/snappy/FramedSnappyCompressorInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/snappy/FramedSnappyCompressorInputStreamTest.java
@@ -43,58 +43,6 @@ public final class FramedSnappyCompressorInputStreamTest extends AbstractTestCas
return (x >>> 15 | x << 17) + FramedSnappyCompressorInputStream.MASK_OFFSET & 0xffffFFFFL;
}
- @Test
- public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
- final File input = getFile("bla.tar.sz");
- final byte[] buf = new byte[2];
- try (InputStream is = Files.newInputStream(input.toPath());
- FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(is);) {
- IOUtils.toByteArray(in);
- assertEquals(-1, in.read(buf));
- assertEquals(-1, in.read(buf));
- }
- }
-
- @Test
- public void testReadIWAFile() throws Exception {
- try (ZipFile zip = new ZipFile(getFile("testNumbersNew.numbers"))) {
- try (InputStream is = zip.getInputStream(zip.getEntry("Index/Document.iwa"))) {
- try (FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(is, FramedSnappyDialect.IWORK_ARCHIVE)) {
- Files.copy(in, new File(dir, "snappyIWATest.raw").toPath());
- }
- }
- }
- }
-
- /**
- * @see "https://issues.apache.org/jira/browse/COMPRESS-358"
- */
- @Test
- public void testReadIWAFileWithBiggerOffset() throws Exception {
- final File o = new File(dir, "COMPRESS-358.raw");
- try (InputStream is = newInputStream("COMPRESS-358.iwa");
- FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(is, 1 << 16, FramedSnappyDialect.IWORK_ARCHIVE);) {
- Files.copy(in, o.toPath());
- }
- try (InputStream a = Files.newInputStream(o.toPath());
- InputStream e = newInputStream("COMPRESS-358.uncompressed")) {
- final byte[] expected = IOUtils.toByteArray(e);
- final byte[] actual = IOUtils.toByteArray(a);
- assertArrayEquals(expected, actual);
- }
- }
-
- @Test
- public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
- final File input = getFile("bla.tar.sz");
- try (InputStream is = Files.newInputStream(input.toPath());
- FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(is);) {
- IOUtils.toByteArray(in);
- assertEquals(-1, in.read());
- assertEquals(-1, in.read());
- }
- }
-
@Test
public void testAvailable() throws Exception {
try (InputStream isSz = newInputStream("mixed.txt.sz");
@@ -150,6 +98,47 @@ public final class FramedSnappyCompressorInputStreamTest extends AbstractTestCas
assertTrue(FramedSnappyCompressorInputStream.matches(b, 12));
}
+ @Test
+ public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
+ final File input = getFile("bla.tar.sz");
+ final byte[] buf = new byte[2];
+ try (InputStream is = Files.newInputStream(input.toPath());
+ FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(is);) {
+ IOUtils.toByteArray(in);
+ assertEquals(-1, in.read(buf));
+ assertEquals(-1, in.read(buf));
+ }
+ }
+
+ @Test
+ public void testReadIWAFile() throws Exception {
+ try (ZipFile zip = new ZipFile(getFile("testNumbersNew.numbers"))) {
+ try (InputStream is = zip.getInputStream(zip.getEntry("Index/Document.iwa"))) {
+ try (FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(is, FramedSnappyDialect.IWORK_ARCHIVE)) {
+ Files.copy(in, new File(dir, "snappyIWATest.raw").toPath());
+ }
+ }
+ }
+ }
+
+ /**
+ * @see "https://issues.apache.org/jira/browse/COMPRESS-358"
+ */
+ @Test
+ public void testReadIWAFileWithBiggerOffset() throws Exception {
+ final File o = new File(dir, "COMPRESS-358.raw");
+ try (InputStream is = newInputStream("COMPRESS-358.iwa");
+ FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(is, 1 << 16, FramedSnappyDialect.IWORK_ARCHIVE);) {
+ Files.copy(in, o.toPath());
+ }
+ try (InputStream a = Files.newInputStream(o.toPath());
+ InputStream e = newInputStream("COMPRESS-358.uncompressed")) {
+ final byte[] expected = IOUtils.toByteArray(e);
+ final byte[] actual = IOUtils.toByteArray(a);
+ assertArrayEquals(expected, actual);
+ }
+ }
+
@Test
public void testRemainingChunkTypes() throws Exception {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
@@ -163,6 +152,17 @@ public final class FramedSnappyCompressorInputStreamTest extends AbstractTestCas
'5', '6', '7', '8', '9', 10, '1', '2', '3', '4', '1', '2', '3', '4', }, out.toByteArray());
}
+ @Test
+ public void testSingleByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
+ final File input = getFile("bla.tar.sz");
+ try (InputStream is = Files.newInputStream(input.toPath());
+ FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(is);) {
+ IOUtils.toByteArray(in);
+ assertEquals(-1, in.read());
+ assertEquals(-1, in.read());
+ }
+ }
+
@Test
public void testUnskippableChunk() {
final byte[] input = { (byte) 0xff, 6, 0, 0, 's', 'N', 'a', 'P', 'p', 'Y', 2, 2, 0, 0, 1, 1 };
diff --git a/src/test/java/org/apache/commons/compress/compressors/snappy/SnappyRoundtripTest.java b/src/test/java/org/apache/commons/compress/compressors/snappy/SnappyRoundtripTest.java
index 4d29f449..8f2f84fe 100644
--- a/src/test/java/org/apache/commons/compress/compressors/snappy/SnappyRoundtripTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/snappy/SnappyRoundtripTest.java
@@ -46,43 +46,6 @@ public final class SnappyRoundtripTest extends AbstractTestCase {
.build();
}
- // yields no compression at all
- @Test
- public void testBiggerFileRoundtrip() throws IOException {
- roundTripTest("COMPRESS-256.7z");
- }
-
- // should yield decent compression
- @Test
- public void testBlaTarRoundtrip() throws IOException {
- // System.err.println("Configuration: default");
- roundTripTest("bla.tar");
- }
-
- @Test
- public void testBlaTarRoundtripTunedForCompressionRatio() throws IOException {
- // System.err.println("Configuration: tuned for compression ratio");
- roundTripTest(getFile("bla.tar"),
- SnappyCompressorOutputStream.createParameterBuilder(SnappyCompressorInputStream.DEFAULT_BLOCK_SIZE)
- .tunedForCompressionRatio()
- .build());
- }
-
- @Test
- public void testBlaTarRoundtripTunedForSpeed() throws IOException {
- // System.err.println("Configuration: tuned for speed");
- roundTripTest(getFile("bla.tar"),
- SnappyCompressorOutputStream.createParameterBuilder(SnappyCompressorInputStream.DEFAULT_BLOCK_SIZE)
- .tunedForSpeed()
- .build());
- }
-
- // yields no compression at all
- @Test
- public void testGzippedLoremIpsumRoundtrip() throws IOException {
- roundTripTest("lorem-ipsum.txt.gz");
- }
-
private void roundTripTest(final byte[] input, final Parameters params) throws IOException {
long start = System.currentTimeMillis();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
@@ -127,6 +90,43 @@ public final class SnappyRoundtripTest extends AbstractTestCase {
.build());
}
+ // yields no compression at all
+ @Test
+ public void testBiggerFileRoundtrip() throws IOException {
+ roundTripTest("COMPRESS-256.7z");
+ }
+
+ // should yield decent compression
+ @Test
+ public void testBlaTarRoundtrip() throws IOException {
+ // System.err.println("Configuration: default");
+ roundTripTest("bla.tar");
+ }
+
+ @Test
+ public void testBlaTarRoundtripTunedForCompressionRatio() throws IOException {
+ // System.err.println("Configuration: tuned for compression ratio");
+ roundTripTest(getFile("bla.tar"),
+ SnappyCompressorOutputStream.createParameterBuilder(SnappyCompressorInputStream.DEFAULT_BLOCK_SIZE)
+ .tunedForCompressionRatio()
+ .build());
+ }
+
+ @Test
+ public void testBlaTarRoundtripTunedForSpeed() throws IOException {
+ // System.err.println("Configuration: tuned for speed");
+ roundTripTest(getFile("bla.tar"),
+ SnappyCompressorOutputStream.createParameterBuilder(SnappyCompressorInputStream.DEFAULT_BLOCK_SIZE)
+ .tunedForSpeed()
+ .build());
+ }
+
+ // yields no compression at all
+ @Test
+ public void testGzippedLoremIpsumRoundtrip() throws IOException {
+ roundTripTest("lorem-ipsum.txt.gz");
+ }
+
@Test
public void tryReallyBigOffset() throws IOException {
// "normal" Snappy files will never reach offsets beyond
diff --git a/src/test/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStreamTest.java b/src/test/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStreamTest.java
index b9e7431b..597e8a3e 100644
--- a/src/test/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/xz/XZCompressorInputStreamTest.java
@@ -43,6 +43,16 @@ public class XZCompressorInputStreamTest {
}
}
+ private void singleByteReadConsistentlyReturnsMinusOneAtEof(final boolean decompressConcatenated) throws IOException {
+ final File input = getFile("bla.tar.xz");
+ try (InputStream is = Files.newInputStream(input.toPath());
+ XZCompressorInputStream in = new XZCompressorInputStream(is, decompressConcatenated)) {
+ IOUtils.toByteArray(in);
+ assertEquals(-1, in.read());
+ assertEquals(-1, in.read());
+ }
+ }
+
@Test
public void testMultiByteReadConsistentlyReturnsMinusOneAtEofDecompressConcatenated() throws IOException {
multiByteReadConsistentlyReturnsMinusOneAtEof(true);
@@ -63,16 +73,6 @@ public class XZCompressorInputStreamTest {
assertFalse(XZCompressorInputStream.matches(data, 6));
}
- private void singleByteReadConsistentlyReturnsMinusOneAtEof(final boolean decompressConcatenated) throws IOException {
- final File input = getFile("bla.tar.xz");
- try (InputStream is = Files.newInputStream(input.toPath());
- XZCompressorInputStream in = new XZCompressorInputStream(is, decompressConcatenated)) {
- IOUtils.toByteArray(in);
- assertEquals(-1, in.read());
- assertEquals(-1, in.read());
- }
- }
-
@Test
public void testSingleByteReadConsistentlyReturnsMinusOneAtEofDecompressConcatenated() throws IOException {
singleByteReadConsistentlyReturnsMinusOneAtEof(true);
diff --git a/src/test/java/org/apache/commons/compress/compressors/z/ZCompressorInputStreamTest.java b/src/test/java/org/apache/commons/compress/compressors/z/ZCompressorInputStreamTest.java
index 0889d1b3..d73250a4 100644
--- a/src/test/java/org/apache/commons/compress/compressors/z/ZCompressorInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/z/ZCompressorInputStreamTest.java
@@ -39,6 +39,12 @@ import org.junit.jupiter.api.Test;
*/
public class ZCompressorInputStreamTest {
+ @Test
+ public void testFailsToCreateZCompressorInputStreamAndThrowsIOException() {
+ final SequenceInputStream sequenceInputStream = new SequenceInputStream(Collections.emptyEnumeration());
+ assertThrows(IOException.class, () -> new ZCompressorInputStream(sequenceInputStream));
+ }
+
@Test
public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
final File input = getFile("bla.tar.Z");
@@ -62,10 +68,4 @@ public class ZCompressorInputStreamTest {
}
}
- @Test
- public void testFailsToCreateZCompressorInputStreamAndThrowsIOException() {
- final SequenceInputStream sequenceInputStream = new SequenceInputStream(Collections.emptyEnumeration());
- assertThrows(IOException.class, () -> new ZCompressorInputStream(sequenceInputStream));
- }
-
}
diff --git a/src/test/java/org/apache/commons/compress/compressors/zstandard/ZstdCompressorInputStreamTest.java b/src/test/java/org/apache/commons/compress/compressors/zstandard/ZstdCompressorInputStreamTest.java
index f9dae59f..5a7a18a2 100644
--- a/src/test/java/org/apache/commons/compress/compressors/zstandard/ZstdCompressorInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/zstandard/ZstdCompressorInputStreamTest.java
@@ -38,6 +38,23 @@ import com.github.luben.zstd.RecyclingBufferPool;
public class ZstdCompressorInputStreamTest extends AbstractTestCase {
+ @Test
+ public void testCachingIsEnabledByDefaultAndZstdUtilsPresent() {
+ assertEquals(ZstdUtils.CachedAvailability.CACHED_AVAILABLE, ZstdUtils.getCachedZstdAvailability());
+ assertTrue(ZstdUtils.isZstdCompressionAvailable());
+ }
+
+ @Test
+ public void testCanTurnOffCaching() {
+ try {
+ ZstdUtils.setCacheZstdAvailablity(false);
+ assertEquals(ZstdUtils.CachedAvailability.DONT_CACHE, ZstdUtils.getCachedZstdAvailability());
+ assertTrue(ZstdUtils.isZstdCompressionAvailable());
+ } finally {
+ ZstdUtils.setCacheZstdAvailablity(true);
+ }
+ }
+
@Test
public void testMultiByteReadConsistentlyReturnsMinusOneAtEof() throws IOException {
final File input = getFile("zstandard.testdata.zst");
@@ -90,23 +107,6 @@ public class ZstdCompressorInputStreamTest extends AbstractTestCase {
}
}
- @Test
- public void testCachingIsEnabledByDefaultAndZstdUtilsPresent() {
- assertEquals(ZstdUtils.CachedAvailability.CACHED_AVAILABLE, ZstdUtils.getCachedZstdAvailability());
- assertTrue(ZstdUtils.isZstdCompressionAvailable());
- }
-
- @Test
- public void testCanTurnOffCaching() {
- try {
- ZstdUtils.setCacheZstdAvailablity(false);
- assertEquals(ZstdUtils.CachedAvailability.DONT_CACHE, ZstdUtils.getCachedZstdAvailability());
- assertTrue(ZstdUtils.isZstdCompressionAvailable());
- } finally {
- ZstdUtils.setCacheZstdAvailablity(true);
- }
- }
-
@Test
public void testTurningOnCachingReEvaluatesAvailability() {
try {
diff --git a/src/test/java/org/apache/commons/compress/compressors/zstandard/ZstdRoundtripTest.java b/src/test/java/org/apache/commons/compress/compressors/zstandard/ZstdRoundtripTest.java
index ca5b4edf..d3f55319 100644
--- a/src/test/java/org/apache/commons/compress/compressors/zstandard/ZstdRoundtripTest.java
+++ b/src/test/java/org/apache/commons/compress/compressors/zstandard/ZstdRoundtripTest.java
@@ -39,6 +39,26 @@ public class ZstdRoundtripTest extends AbstractTestCase {
ZstdCompressorOutputStream wrap(FileOutputStream os) throws IOException;
}
+ private void roundtrip(final OutputStreamCreator oc) throws IOException {
+ final File input = getFile("bla.tar");
+ long start = System.currentTimeMillis();
+ final File output = new File(dir, input.getName() + ".zstd");
+ try (FileOutputStream os = new FileOutputStream(output);
+ ZstdCompressorOutputStream zos = oc.wrap(os)) {
+ Files.copy(input.toPath(), zos);
+ }
+ //System.err.println(input.getName() + " written, uncompressed bytes: " + input.length()
+ // + ", compressed bytes: " + output.length() + " after " + (System.currentTimeMillis() - start) + "ms");
+ start = System.currentTimeMillis();
+ try (InputStream is = Files.newInputStream(input.toPath());
+ ZstdCompressorInputStream zis = new ZstdCompressorInputStream(Files.newInputStream(output.toPath()))) {
+ final byte[] expected = IOUtils.toByteArray(is);
+ final byte[] actual = IOUtils.toByteArray(zis);
+ assertArrayEquals(expected, actual);
+ }
+ // System.err.println(output.getName() + " read after " + (System.currentTimeMillis() - start) + "ms");
+ }
+
@Test
public void testDirectRoundtrip() throws Exception {
roundtrip(ZstdCompressorOutputStream::new);
@@ -62,26 +82,6 @@ public class ZstdRoundtripTest extends AbstractTestCase {
}
}
- private void roundtrip(final OutputStreamCreator oc) throws IOException {
- final File input = getFile("bla.tar");
- long start = System.currentTimeMillis();
- final File output = new File(dir, input.getName() + ".zstd");
- try (FileOutputStream os = new FileOutputStream(output);
- ZstdCompressorOutputStream zos = oc.wrap(os)) {
- Files.copy(input.toPath(), zos);
- }
- //System.err.println(input.getName() + " written, uncompressed bytes: " + input.length()
- // + ", compressed bytes: " + output.length() + " after " + (System.currentTimeMillis() - start) + "ms");
- start = System.currentTimeMillis();
- try (InputStream is = Files.newInputStream(input.toPath());
- ZstdCompressorInputStream zis = new ZstdCompressorInputStream(Files.newInputStream(output.toPath()))) {
- final byte[] expected = IOUtils.toByteArray(is);
- final byte[] actual = IOUtils.toByteArray(zis);
- assertArrayEquals(expected, actual);
- }
- // System.err.println(output.getName() + " read after " + (System.currentTimeMillis() - start) + "ms");
- }
-
@Test
public void testRoundtripWithChecksum() throws Exception {
roundtrip(os -> new ZstdCompressorOutputStream(os, 3, false, true));
diff --git a/src/test/java/org/apache/commons/compress/utils/BitInputStreamTest.java b/src/test/java/org/apache/commons/compress/utils/BitInputStreamTest.java
index e573c25c..04e6a98d 100644
--- a/src/test/java/org/apache/commons/compress/utils/BitInputStreamTest.java
+++ b/src/test/java/org/apache/commons/compress/utils/BitInputStreamTest.java
@@ -29,6 +29,14 @@ import org.junit.jupiter.api.Test;
public class BitInputStreamTest {
+ private ByteArrayInputStream getStream() {
+ return new ByteArrayInputStream(new byte[] {
+ (byte) 0xF8, // 11111000
+ 0x40, // 01000000
+ 0x01, // 00000001
+ 0x2F }); // 00101111
+ }
+
@Test
public void testAlignWithByteBoundaryWhenAtBoundary() throws Exception {
try (final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN)) {
@@ -89,12 +97,21 @@ public class BitInputStreamTest {
}
}
- private ByteArrayInputStream getStream() {
- return new ByteArrayInputStream(new byte[] {
- (byte) 0xF8, // 11111000
- 0x40, // 01000000
- 0x01, // 00000001
- 0x2F }); // 00101111
+ @Test
+ public void testClearBitCache() throws IOException {
+ try (final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN)) {
+ assertEquals(0x08, bis.readBits(4));
+ bis.clearBitCache();
+ assertEquals(0, bis.readBits(1));
+ }
+ }
+
+ @Test
+ public void testEOF() throws IOException {
+ try (final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN)) {
+ assertEquals(0x2f0140f8, bis.readBits(30));
+ assertEquals(-1, bis.readBits(3));
+ }
}
/**
@@ -125,37 +142,6 @@ public class BitInputStreamTest {
}
}
- @Test
- public void testShouldNotAllowReadingOfANegativeAmountOfBits() throws IOException {
- try (final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN)) {
- assertThrows(IOException.class, () -> bis.readBits(-1));
- }
- }
-
- @Test
- public void testShouldNotAllowReadingOfMoreThan63BitsAtATime() throws IOException {
- try (final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN)) {
- assertThrows(IOException.class, () -> bis.readBits(64));
- }
- }
-
- @Test
- public void testClearBitCache() throws IOException {
- try (final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN)) {
- assertEquals(0x08, bis.readBits(4));
- bis.clearBitCache();
- assertEquals(0, bis.readBits(1));
- }
- }
-
- @Test
- public void testEOF() throws IOException {
- try (final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN)) {
- assertEquals(0x2f0140f8, bis.readBits(30));
- assertEquals(-1, bis.readBits(3));
- }
- }
-
@Test
public void testReading17BitsInBigEndian() throws IOException {
try (final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.BIG_ENDIAN)) {
@@ -215,4 +201,18 @@ public class BitInputStreamTest {
}
}
+ @Test
+ public void testShouldNotAllowReadingOfANegativeAmountOfBits() throws IOException {
+ try (final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN)) {
+ assertThrows(IOException.class, () -> bis.readBits(-1));
+ }
+ }
+
+ @Test
+ public void testShouldNotAllowReadingOfMoreThan63BitsAtATime() throws IOException {
+ try (final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN)) {
+ assertThrows(IOException.class, () -> bis.readBits(64));
+ }
+ }
+
}
diff --git a/src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java b/src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java
index 1bb988c8..c7a0efbe 100644
--- a/src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java
+++ b/src/test/java/org/apache/commons/compress/utils/IOUtilsTest.java
@@ -43,6 +43,15 @@ public class IOUtilsTest {
IOUtils.readFully(new SeekableInMemoryByteChannel(source), b);
}
+ private void skip(final StreamWrapper wrapper) throws Exception {
+ final ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
+ });
+ final InputStream sut = wrapper.wrap(in);
+ assertEquals(10, IOUtils.skip(sut, 10));
+ assertEquals(11, sut.read());
+ }
+
@Test
public void testCopyRangeDoesntCopyMoreThanAskedFor() throws IOException {
try (ByteArrayInputStream in = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 });
@@ -171,15 +180,6 @@ public class IOUtilsTest {
}
}
- private void skip(final StreamWrapper wrapper) throws Exception {
- final ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
- });
- final InputStream sut = wrapper.wrap(in);
- assertEquals(10, IOUtils.skip(sut, 10));
- assertEquals(11, sut.read());
- }
-
@Test
public void testSkipUsingRead() throws Exception {
skip(toWrap -> new FilterInputStream(toWrap) {
diff --git a/src/test/java/org/apache/commons/compress/utils/MultiReadOnlySeekableByteChannelTest.java b/src/test/java/org/apache/commons/compress/utils/MultiReadOnlySeekableByteChannelTest.java
index d42f4625..b051858d 100644
--- a/src/test/java/org/apache/commons/compress/utils/MultiReadOnlySeekableByteChannelTest.java
+++ b/src/test/java/org/apache/commons/compress/utils/MultiReadOnlySeekableByteChannelTest.java
@@ -81,26 +81,6 @@ public class MultiReadOnlySeekableByteChannelTest {
}
}
- @Test
- public void testCantPositionToANegativePosition() throws IOException {
- try (SeekableByteChannel s = MultiReadOnlySeekableByteChannel.forSeekableByteChannels(makeEmpty(), makeEmpty())) {
- assertThrows(IllegalArgumentException.class, () -> s.position(-1));
- }
- }
-
- @Test
- public void testCantTruncate() throws IOException {
- try (SeekableByteChannel s = MultiReadOnlySeekableByteChannel.forSeekableByteChannels(makeEmpty(), makeEmpty())) {
- assertThrows(NonWritableChannelException.class, () -> s.truncate(1));
- }
- }
-
- @Test
- public void testCantWrite() {
- final SeekableByteChannel s = MultiReadOnlySeekableByteChannel.forSeekableByteChannels(makeEmpty(), makeEmpty());
- assertThrows(NonWritableChannelException.class, () -> s.write(ByteBuffer.allocate(10)));
- }
-
private void check(final byte[] expected) throws IOException {
for (int channelSize = 1; channelSize <= expected.length; channelSize++) {
// Sanity check that all operations work for SeekableInMemoryByteChannel
@@ -183,6 +163,59 @@ public class MultiReadOnlySeekableByteChannelTest {
"expected a ClosedChannelException");
}
+ private byte[][] grouped(final byte[] input, final int chunkSize) {
+ final List<byte[]> groups = new ArrayList<>();
+ int idx = 0;
+ for (; idx + chunkSize <= input.length; idx += chunkSize) {
+ groups.add(Arrays.copyOfRange(input, idx, idx + chunkSize));
+ }
+ if (idx < input.length) {
+ groups.add(Arrays.copyOfRange(input, idx, input.length));
+ }
+ return groups.toArray(new byte[0][]);
+ }
+
+ private SeekableByteChannel makeEmpty() {
+ return makeSingle(ByteUtils.EMPTY_BYTE_ARRAY);
+ }
+
+ private SeekableByteChannel makeMulti(final byte[][] arr) {
+ final SeekableByteChannel[] s = new SeekableByteChannel[arr.length];
+ for (int i = 0; i < s.length; i++) {
+ s[i] = makeSingle(arr[i]);
+ }
+ return MultiReadOnlySeekableByteChannel.forSeekableByteChannels(s);
+ }
+
+ private SeekableByteChannel makeSingle(final byte[] arr) {
+ return new SeekableInMemoryByteChannel(arr);
+ }
+
+ @Test
+ public void testCantPositionToANegativePosition() throws IOException {
+ try (SeekableByteChannel s = MultiReadOnlySeekableByteChannel.forSeekableByteChannels(makeEmpty(), makeEmpty())) {
+ assertThrows(IllegalArgumentException.class, () -> s.position(-1));
+ }
+ }
+
+ @Test
+ public void testCantTruncate() throws IOException {
+ try (SeekableByteChannel s = MultiReadOnlySeekableByteChannel.forSeekableByteChannels(makeEmpty(), makeEmpty())) {
+ assertThrows(NonWritableChannelException.class, () -> s.truncate(1));
+ }
+ }
+
+ @Test
+ public void testCantWrite() {
+ final SeekableByteChannel s = MultiReadOnlySeekableByteChannel.forSeekableByteChannels(makeEmpty(), makeEmpty());
+ assertThrows(NonWritableChannelException.class, () -> s.write(ByteBuffer.allocate(10)));
+ }
+
+ private SeekableByteChannel testChannel() {
+ return MultiReadOnlySeekableByteChannel
+ .forSeekableByteChannels(makeEmpty(), makeEmpty());
+ }
+
@Test
public void testCheckForSingleByte() throws IOException {
check(new byte[] { 0 });
@@ -242,34 +275,6 @@ public class MultiReadOnlySeekableByteChannelTest {
assertThrows(NullPointerException.class, () -> MultiReadOnlySeekableByteChannel.forSeekableByteChannels(null));
}
- private byte[][] grouped(final byte[] input, final int chunkSize) {
- final List<byte[]> groups = new ArrayList<>();
- int idx = 0;
- for (; idx + chunkSize <= input.length; idx += chunkSize) {
- groups.add(Arrays.copyOfRange(input, idx, idx + chunkSize));
- }
- if (idx < input.length) {
- groups.add(Arrays.copyOfRange(input, idx, input.length));
- }
- return groups.toArray(new byte[0][]);
- }
-
- private SeekableByteChannel makeEmpty() {
- return makeSingle(ByteUtils.EMPTY_BYTE_ARRAY);
- }
-
- private SeekableByteChannel makeMulti(final byte[][] arr) {
- final SeekableByteChannel[] s = new SeekableByteChannel[arr.length];
- for (int i = 0; i < s.length; i++) {
- s[i] = makeSingle(arr[i]);
- }
- return MultiReadOnlySeekableByteChannel.forSeekableByteChannels(s);
- }
-
- private SeekableByteChannel makeSingle(final byte[] arr) {
- return new SeekableInMemoryByteChannel(arr);
- }
-
/*
* <q>Setting the position to a value that is greater than the current size is legal but does not change the size of
* the entity. A later attempt to read bytes at such a position will immediately return an end-of-file
@@ -285,19 +290,33 @@ public class MultiReadOnlySeekableByteChannelTest {
}
}
+ // Contract Tests added in response to https://issues.apache.org/jira/browse/COMPRESS-499
+
@Test
public void testReferenceBehaviorForEmptyChannel() throws IOException {
checkEmpty(makeEmpty());
}
- // Contract Tests added in response to https://issues.apache.org/jira/browse/COMPRESS-499
+ // https://docs.oracle.com/javase/7/docs/api/java/io/Closeable.html#close()
- private SeekableByteChannel testChannel() {
- return MultiReadOnlySeekableByteChannel
- .forSeekableByteChannels(makeEmpty(), makeEmpty());
+ @Test
+ public void testVerifyGrouped() {
+ assertArrayEquals(new byte[][] {
+ new byte[] { 1, 2, 3, },
+ new byte[] { 4, 5, 6, },
+ new byte[] { 7, },
+ }, grouped(new byte[] { 1, 2, 3, 4, 5, 6, 7 }, 3));
+ assertArrayEquals(new byte[][] {
+ new byte[] { 1, 2, 3, },
+ new byte[] { 4, 5, 6, },
+ }, grouped(new byte[] { 1, 2, 3, 4, 5, 6 }, 3));
+ assertArrayEquals(new byte[][] {
+ new byte[] { 1, 2, 3, },
+ new byte[] { 4, 5, },
+ }, grouped(new byte[] { 1, 2, 3, 4, 5, }, 3));
}
- // https://docs.oracle.com/javase/7/docs/api/java/io/Closeable.html#close()
+ // https://docs.oracle.com/javase/7/docs/api/java/nio/channels/SeekableByteChannel.html#position()
/*
* <q>ClosedChannelException - If this channel is closed</q>
@@ -311,7 +330,7 @@ public class MultiReadOnlySeekableByteChannelTest {
}
}
- // https://docs.oracle.com/javase/7/docs/api/java/nio/channels/SeekableByteChannel.html#position()
+ // https://docs.oracle.com/javase/7/docs/api/java/nio/channels/SeekableByteChannel.html#size()
/*
* <q>ClosedChannelException - If this channel is closed</q>
@@ -324,7 +343,7 @@ public class MultiReadOnlySeekableByteChannelTest {
}
}
- // https://docs.oracle.com/javase/7/docs/api/java/nio/channels/SeekableByteChannel.html#size()
+ // https://docs.oracle.com/javase/7/docs/api/java/nio/channels/SeekableByteChannel.html#position(long)
/*
* <q>ClosedChannelException - If this channel is closed</q>
@@ -337,8 +356,6 @@ public class MultiReadOnlySeekableByteChannelTest {
}
}
- // https://docs.oracle.com/javase/7/docs/api/java/nio/channels/SeekableByteChannel.html#position(long)
-
/*
* <q>IOException - If the new position is negative</q>
*/
@@ -356,21 +373,4 @@ public class MultiReadOnlySeekableByteChannelTest {
}
}
- @Test
- public void testVerifyGrouped() {
- assertArrayEquals(new byte[][] {
- new byte[] { 1, 2, 3, },
- new byte[] { 4, 5, 6, },
- new byte[] { 7, },
- }, grouped(new byte[] { 1, 2, 3, 4, 5, 6, 7 }, 3));
- assertArrayEquals(new byte[][] {
- new byte[] { 1, 2, 3, },
- new byte[] { 4, 5, 6, },
- }, grouped(new byte[] { 1, 2, 3, 4, 5, 6 }, 3));
- assertArrayEquals(new byte[][] {
- new byte[] { 1, 2, 3, },
- new byte[] { 4, 5, },
- }, grouped(new byte[] { 1, 2, 3, 4, 5, }, 3));
- }
-
}
diff --git a/src/test/java/org/apache/commons/compress/utils/TimeUtilsTest.java b/src/test/java/org/apache/commons/compress/utils/TimeUtilsTest.java
index 21e4c23a..6e0141e0 100644
--- a/src/test/java/org/apache/commons/compress/utils/TimeUtilsTest.java
+++ b/src/test/java/org/apache/commons/compress/utils/TimeUtilsTest.java
@@ -124,17 +124,6 @@ public class TimeUtilsTest {
);
}
- @Test
- public void testShouldCheckWhetherTimeCanBeRepresentedAsUnixTime() {
- assertTrue(TimeUtils.isUnixTime(null));
- assertTrue(TimeUtils.isUnixTime(FileTime.from(Instant.parse("2022-12-27T12:45:22Z"))));
- assertTrue(TimeUtils.isUnixTime(FileTime.from(Instant.parse("2038-01-19T03:14:07Z"))));
- assertTrue(TimeUtils.isUnixTime(FileTime.from(Instant.parse("1901-12-13T23:14:08Z"))));
- assertFalse(TimeUtils.isUnixTime(FileTime.from(Instant.parse("1901-12-13T03:14:08Z"))));
- assertFalse(TimeUtils.isUnixTime(FileTime.from(Instant.parse("2038-01-19T03:14:08Z"))));
- assertFalse(TimeUtils.isUnixTime(FileTime.from(Instant.parse("2099-06-30T12:31:42Z"))));
- }
-
@ParameterizedTest
@MethodSource("dateToNtfsProvider")
public void shouldConvertDateToFileTime(final String instant, final long ignored) {
@@ -193,16 +182,6 @@ public class TimeUtilsTest {
assertEquals(parsed, ntfsTimeToFileTime(ntfsTime));
}
- @Test
- public void testShouldConvertNullDateToNullFileTime() {
- assertNull(toFileTime(null));
- }
-
- @Test
- public void testShouldConvertNullFileTimeToNullDate() {
- assertNull(toDate(null));
- }
-
@ParameterizedTest
@MethodSource("fileTimeToUnixTimeArguments")
public void shouldConvertUnixTimeToFileTime(final long unixTime, final String expectedInstant) {
@@ -216,4 +195,25 @@ public class TimeUtilsTest {
final FileTime truncatedTime = FileTime.from(Instant.parse(truncated));
assertEquals(truncatedTime, TimeUtils.truncateToHundredNanos(originalTime));
}
+
+ @Test
+ public void testShouldCheckWhetherTimeCanBeRepresentedAsUnixTime() {
+ assertTrue(TimeUtils.isUnixTime(null));
+ assertTrue(TimeUtils.isUnixTime(FileTime.from(Instant.parse("2022-12-27T12:45:22Z"))));
+ assertTrue(TimeUtils.isUnixTime(FileTime.from(Instant.parse("2038-01-19T03:14:07Z"))));
+ assertTrue(TimeUtils.isUnixTime(FileTime.from(Instant.parse("1901-12-13T23:14:08Z"))));
+ assertFalse(TimeUtils.isUnixTime(FileTime.from(Instant.parse("1901-12-13T03:14:08Z"))));
+ assertFalse(TimeUtils.isUnixTime(FileTime.from(Instant.parse("2038-01-19T03:14:08Z"))));
+ assertFalse(TimeUtils.isUnixTime(FileTime.from(Instant.parse("2099-06-30T12:31:42Z"))));
+ }
+
+ @Test
+ public void testShouldConvertNullDateToNullFileTime() {
+ assertNull(toFileTime(null));
+ }
+
+ @Test
+ public void testShouldConvertNullFileTimeToNullDate() {
+ assertNull(toDate(null));
+ }
}
diff --git a/src/test/java/org/apache/commons/compress/utils/ZipSplitReadOnlySeekableByteChannelTest.java b/src/test/java/org/apache/commons/compress/utils/ZipSplitReadOnlySeekableByteChannelTest.java
index 75ca89e6..6e1260e8 100644
--- a/src/test/java/org/apache/commons/compress/utils/ZipSplitReadOnlySeekableByteChannelTest.java
+++ b/src/test/java/org/apache/commons/compress/utils/ZipSplitReadOnlySeekableByteChannelTest.java
@@ -39,6 +39,20 @@ import org.junit.jupiter.api.Test;
public class ZipSplitReadOnlySeekableByteChannelTest {
+ private List<SeekableByteChannel> getSplitZipChannels() throws IOException {
+ final List<SeekableByteChannel> channels = new ArrayList<>();
+ final File file1 = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.z01");
+ channels.add(Files.newByteChannel(file1.toPath(), StandardOpenOption.READ));
+
+ final File file2 = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.z02");
+ channels.add(Files.newByteChannel(file2.toPath(), StandardOpenOption.READ));
+
+ final File lastFile = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.zip");
+ channels.add(Files.newByteChannel(lastFile.toPath(), StandardOpenOption.READ));
+
+ return channels;
+ }
+
@Test
public void testBuildFromLastSplitSegmentThrowsOnNotZipFile() throws IOException {
final File lastFile = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.z01");
@@ -165,20 +179,6 @@ public class ZipSplitReadOnlySeekableByteChannelTest {
assertThrows(NullPointerException.class, () -> ZipSplitReadOnlySeekableByteChannel.forPaths(null));
}
- private List<SeekableByteChannel> getSplitZipChannels() throws IOException {
- final List<SeekableByteChannel> channels = new ArrayList<>();
- final File file1 = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.z01");
- channels.add(Files.newByteChannel(file1.toPath(), StandardOpenOption.READ));
-
- final File file2 = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.z02");
- channels.add(Files.newByteChannel(file2.toPath(), StandardOpenOption.READ));
-
- final File lastFile = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.zip");
- channels.add(Files.newByteChannel(lastFile.toPath(), StandardOpenOption.READ));
-
- return channels;
- }
-
@Test
public void testPositionToSomeZipSplitSegment() throws IOException {
final File firstFile = getFile("COMPRESS-477/split_zip_created_by_zip/split_zip_created_by_zip.z01");