pax_global_header00006660000000000000000000000064123214556370014522gustar00rootroot0000000000000052 comment=4b22297414ff5faf8b792c7c086c3a9e26ca4f35 zip-zip-0.3/000077500000000000000000000000001232145563700127665ustar00rootroot00000000000000zip-zip-0.3/.gitignore000066400000000000000000000002711232145563700147560ustar00rootroot00000000000000bin *.gem *.rbc .bundle .config .ruby-version coverage InstalledFiles lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp # YARD artifacts .yardoc _yardoc doc/ *.swp zip-zip-0.3/Gemfile000066400000000000000000000001341232145563700142570ustar00rootroot00000000000000source 'https://rubygems.org' # Specify your gem's dependencies in zip-zip.gemspec gemspec zip-zip-0.3/Gemfile.lock000066400000000000000000000006501232145563700152110ustar00rootroot00000000000000PATH remote: . specs: zip-zip (0.3) rubyzip (>= 1.0.0) GEM remote: https://rubygems.org/ specs: coderay (1.1.0) method_source (0.8.2) minitest (4.7.5) pry (0.9.12.6) coderay (~> 1.0) method_source (~> 0.8) slop (~> 3.4) rake (10.2.2) rubyzip (1.0.0) slop (3.5.0) PLATFORMS ruby DEPENDENCIES bundler (~> 1.6) minitest (= 4.7.5) pry rake zip-zip! zip-zip-0.3/LICENSE.txt000066400000000000000000000020571232145563700146150ustar00rootroot00000000000000Copyright (c) 2014 Orien Madgwick MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. zip-zip-0.3/README.md000066400000000000000000000015401232145563700142450ustar00rootroot00000000000000# zip-zip [![Gem Version](https://badge.fury.io/rb/zip-zip.png)](http://badge.fury.io/rb/zip-zip) So you've upgraded a gem dependency that requires RubyZip v1.0.0 or higher. While all your other dependencies use the interface provided by v0.x. **zip-zip** provides a simple adapter to let all your dependencies use RubyZip v1.0.0. It is very simple and light weight, aliasing the old class names to the new. ## Installation Add this line to your application's Gemfile: gem 'zip-zip' And then execute: $ bundle Or install it yourself as: $ gem install zip-zip ## Contributing 1. Fork it ( https://github.com/orien/zip-zip/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request zip-zip-0.3/Rakefile000066400000000000000000000002601232145563700144310ustar00rootroot00000000000000require 'bundler/gem_tasks' require 'rake/testtask' task :default => :test Rake::TestTask.new(:test) do |test| test.libs << 'test' test.pattern = 'test/**/*test.rb' end zip-zip-0.3/lib/000077500000000000000000000000001232145563700135345ustar00rootroot00000000000000zip-zip-0.3/lib/zip/000077500000000000000000000000001232145563700143365ustar00rootroot00000000000000zip-zip-0.3/lib/zip/zip.rb000066400000000000000000000016671232145563700154770ustar00rootroot00000000000000require 'zip' Zip::Zip = Zip Zip::ZipCentralDirectory = Zip::CentralDirectory Zip::ZipEntry = Zip::Entry Zip::ZipEntrySet = Zip::EntrySet Zip::ZipExtraField = Zip::ExtraField Zip::ZipFile = Zip::File Zip::ZipInputStream = Zip::InputStream Zip::ZipOutputStream = Zip::OutputStream Zip::ZipStreamableDirectory = Zip::StreamableDirectory Zip::ZipStreamableStream = Zip::StreamableStream IOExtras = Zip::IOExtras module Zip class Entry alias :is_directory :directory? alias :localHeaderOffset :local_header_offset end class ExtraField alias :local_length :local_size alias :c_dir_length :c_dir_size end module OptionsAdapter def self.[]=(key, value) Zip.send("#{key}=", value) end def self.[](key) Zip.send(key) end end def options OptionsAdapter end end zip-zip-0.3/lib/zip/zipfilesystem.rb000066400000000000000000000001211232145563700175640ustar00rootroot00000000000000require 'zip/zip' require 'zip/filesystem' Zip::ZipFileSystem = Zip::FileSystem zip-zip-0.3/test/000077500000000000000000000000001232145563700137455ustar00rootroot00000000000000zip-zip-0.3/test/0.9.9/000077500000000000000000000000001232145563700144225ustar00rootroot00000000000000zip-zip-0.3/test/0.9.9/data/000077500000000000000000000000001232145563700153335ustar00rootroot00000000000000zip-zip-0.3/test/0.9.9/data/.cvsignore000066400000000000000000000000121232145563700173240ustar00rootroot00000000000000generated zip-zip-0.3/test/0.9.9/data/file1.txt000066400000000000000000000024571232145563700171040ustar00rootroot00000000000000 AUTOMAKE_OPTIONS = gnu EXTRA_DIST = test.zip CXXFLAGS= -g noinst_LIBRARIES = libzipios.a bin_PROGRAMS = test_zip test_izipfilt test_izipstream # test_flist libzipios_a_SOURCES = backbuffer.h fcol.cpp fcol.h \ fcol_common.h fcolexceptions.cpp fcolexceptions.h \ fileentry.cpp fileentry.h flist.cpp \ flist.h flistentry.cpp flistentry.h \ flistscanner.h ifiltstreambuf.cpp ifiltstreambuf.h \ inflatefilt.cpp inflatefilt.h izipfilt.cpp \ izipfilt.h izipstream.cpp izipstream.h \ zipfile.cpp zipfile.h ziphead.cpp \ ziphead.h flistscanner.ll # test_flist_SOURCES = test_flist.cpp test_izipfilt_SOURCES = test_izipfilt.cpp test_izipstream_SOURCES = test_izipstream.cpp test_zip_SOURCES = test_zip.cpp # Notice that libzipios.a is not specified as -L. -lzipios # If it was, automake would not include it as a dependency. # test_flist_LDADD = libzipios.a test_izipfilt_LDADD = libzipios.a -lz test_zip_LDADD = libzipios.a -lz test_izipstream_LDADD = libzipios.a -lz flistscanner.cc : flistscanner.ll $(LEX) -+ -PFListScanner -o$@ $^ zip-zip-0.3/test/0.9.9/data/file1.txt.deflatedData000066400000000000000000000007421232145563700214400ustar00rootroot00000000000000Tn0}+56IƚBMi1Xulu =6@]?F?VzOlVm8Z0m?!@*.ɓ{ DtH\tF&ۧ 3T9CJA1'y~N }7eɎavT5* xqĜAɎ7eJuU^\0&Ptzuj\#DJow; 4?# t'S:=롗zQ*F!+^'nw/}Oy~J {<$s[lʳ#2241\Tuͨ=tV $!Q4.|# ƨyeQtJ.h R`j& &{8I&YF0ě:Ël0:@J?Ga1Y>a}b73Z|/TRAILINGSTUFF zip-zip-0.3/test/0.9.9/data/file2.txt000066400000000000000000001204221232145563700170760ustar00rootroot00000000000000#!/usr/bin/env ruby $VERBOSE = true require 'rubyunit' require 'zip' include Zip Dir.chdir "test" class AbstractInputStreamTest < RUNIT::TestCase # AbstractInputStream subclass that provides a read method TEST_LINES = [ "Hello world#{$/}", "this is the second line#{$/}", "this is the last line"] TEST_STRING = TEST_LINES.join class TestAbstractInputStream include AbstractInputStream def initialize(aString) @contents = aString @readPointer = 0 end def read(charsToRead) retVal=@contents[@readPointer, charsToRead] @readPointer+=charsToRead return retVal end def produceInput read(100) end def inputFinished? @contents[@readPointer] == nil end end def setup @io = TestAbstractInputStream.new(TEST_STRING) end def test_gets assert_equals(TEST_LINES[0], @io.gets) assert_equals(TEST_LINES[1], @io.gets) assert_equals(TEST_LINES[2], @io.gets) assert_equals(nil, @io.gets) end def test_getsMultiCharSeperator assert_equals("Hell", @io.gets("ll")) assert_equals("o world#{$/}this is the second l", @io.gets("d l")) end def test_each_line lineNumber=0 @io.each_line { |line| assert_equals(TEST_LINES[lineNumber], line) lineNumber+=1 } end def test_readlines assert_equals(TEST_LINES, @io.readlines) end def test_readline test_gets begin @io.readline fail "EOFError expected" rescue EOFError end end end class ZipEntryTest < RUNIT::TestCase TEST_ZIPFILE = "someZipFile.zip" TEST_COMMENT = "a comment" TEST_COMPRESSED_SIZE = 1234 TEST_CRC = 325324 TEST_EXTRA = "Some data here" TEST_COMPRESSIONMETHOD = ZipEntry::DEFLATED TEST_NAME = "entry name" TEST_SIZE = 8432 TEST_ISDIRECTORY = false def test_constructorAndGetters entry = ZipEntry.new(TEST_ZIPFILE, TEST_NAME, TEST_COMMENT, TEST_EXTRA, TEST_COMPRESSED_SIZE, TEST_CRC, TEST_COMPRESSIONMETHOD, TEST_SIZE) assert_equals(TEST_COMMENT, entry.comment) assert_equals(TEST_COMPRESSED_SIZE, entry.compressedSize) assert_equals(TEST_CRC, entry.crc) assert_equals(TEST_EXTRA, entry.extra) assert_equals(TEST_COMPRESSIONMETHOD, entry.compressionMethod) assert_equals(TEST_NAME, entry.name) assert_equals(TEST_SIZE, entry.size) assert_equals(TEST_ISDIRECTORY, entry.isDirectory) end def test_equality entry1 = ZipEntry.new("file.zip", "name", "isNotCompared", "something extra", 123, 1234, ZipEntry::DEFLATED, 10000) entry2 = ZipEntry.new("file.zip", "name", "isNotComparedXXX", "something extra", 123, 1234, ZipEntry::DEFLATED, 10000) entry3 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extra", 123, 1234, ZipEntry::DEFLATED, 10000) entry4 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extraXX", 123, 1234, ZipEntry::DEFLATED, 10000) entry5 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extraXX", 12, 1234, ZipEntry::DEFLATED, 10000) entry6 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extraXX", 12, 123, ZipEntry::DEFLATED, 10000) entry7 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extraXX", 12, 123, ZipEntry::STORED, 10000) entry8 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extraXX", 12, 123, ZipEntry::STORED, 100000) assert_equals(entry1, entry1) assert_equals(entry1, entry2) assert(entry2 != entry3) assert(entry3 != entry4) assert(entry4 != entry5) assert(entry5 != entry6) assert(entry6 != entry7) assert(entry7 != entry8) assert(entry7 != "hello") assert(entry7 != 12) end end module IOizeString attr_reader :tell def read(count = nil) @tell ||= 0 count = size unless count retVal = slice(@tell, count) @tell += count return retVal end def seek(index, offset) @tell ||= 0 case offset when IO::SEEK_END newPos = size + index when IO::SEEK_SET newPos = index when IO::SEEK_CUR newPos = @tell + index else raise "Error in test method IOizeString::seek" end if (newPos < 0 || newPos >= size) raise Errno::EINVAL else @tell=newPos end end def reset @tell = 0 end end class ZipLocalEntryTest < RUNIT::TestCase def test_readLocalEntryHeaderOfFirstTestZipEntry File.open(TestZipFile::TEST_ZIP3.zipName) { |file| entry = ZipEntry.readLocalEntry(file) assert_equal("", entry.comment) # Differs from windows and unix because of CR LF # assert_equal(480, entry.compressedSize) # assert_equal(0x2a27930f, entry.crc) # extra field is 21 bytes long # probably contains some unix attrutes or something # disabled: assert_equal(nil, entry.extra) assert_equal(ZipEntry::DEFLATED, entry.compressionMethod) assert_equal(TestZipFile::TEST_ZIP3.entryNames[0], entry.name) assert_equal(File.size(TestZipFile::TEST_ZIP3.entryNames[0]), entry.size) assert(! entry.isDirectory) } end def test_readLocalEntryFromNonZipFile File.open("ziptest.rb") { |file| assert_equals(nil, ZipEntry.readLocalEntry(file)) } end def test_readLocalEntryFromTruncatedZipFile zipFragment="" File.open(TestZipFile::TEST_ZIP2.zipName) { |f| zipFragment = f.read(12) } # local header is at least 30 bytes zipFragment.extend(IOizeString).reset entry = ZipEntry.new entry.readLocalEntry(zipFragment) fail "ZipError expected" rescue ZipError end def test_writeEntry entry = ZipEntry.new("file.zip", "entryName", "my little comment", "thisIsSomeExtraInformation", 100, 987654, ZipEntry::DEFLATED, 400) writeToFile("localEntryHeader.bin", "centralEntryHeader.bin", entry) entryReadLocal, entryReadCentral = readFromFile("localEntryHeader.bin", "centralEntryHeader.bin") compareLocalEntryHeaders(entry, entryReadLocal) compareCDirEntryHeaders(entry, entryReadCentral) end private def compareLocalEntryHeaders(entry1, entry2) assert_equals(entry1.compressedSize , entry2.compressedSize) assert_equals(entry1.crc , entry2.crc) assert_equals(entry1.extra , entry2.extra) assert_equals(entry1.compressionMethod, entry2.compressionMethod) assert_equals(entry1.name , entry2.name) assert_equals(entry1.size , entry2.size) assert_equals(entry1.localHeaderOffset, entry2.localHeaderOffset) end def compareCDirEntryHeaders(entry1, entry2) compareLocalEntryHeaders(entry1, entry2) assert_equals(entry1.comment, entry2.comment) end def writeToFile(localFileName, centralFileName, entry) File.open(localFileName, "wb") { |f| entry.writeLocalEntry(f) } File.open(centralFileName, "wb") { |f| entry.writeCDirEntry(f) } end def readFromFile(localFileName, centralFileName) localEntry = nil cdirEntry = nil File.open(localFileName, "rb") { |f| localEntry = ZipEntry.readLocalEntry(f) } File.open(centralFileName, "rb") { |f| cdirEntry = ZipEntry.readCDirEntry(f) } return [localEntry, cdirEntry] end end module DecompressorTests # expects @refText and @decompressor def test_readEverything assert_equals(@refText, @decompressor.read) end def test_readInChunks chunkSize = 5 while (decompressedChunk = @decompressor.read(chunkSize)) assert_equals(@refText.slice!(0, chunkSize), decompressedChunk) end assert_equals(0, @refText.size) end end class InflaterTest < RUNIT::TestCase include DecompressorTests def setup @file = File.new("file1.txt.deflatedData", "rb") @refText="" File.open("file1.txt") { |f| @refText = f.read } @decompressor = Inflater.new(@file) end def teardown @file.close end end class PassThruDecompressorTest < RUNIT::TestCase include DecompressorTests TEST_FILE="file1.txt" def setup @file = File.new(TEST_FILE) @refText="" File.open(TEST_FILE) { |f| @refText = f.read } @decompressor = PassThruDecompressor.new(@file, File.size(TEST_FILE)) end def teardown @file.close end end module AssertEntry def assertNextEntry(filename, zis) assertEntry(filename, zis, zis.getNextEntry.name) end def assertEntry(filename, zis, entryName) assert_equals(filename, entryName) assertEntryContentsForStream(filename, zis, entryName) end def assertEntryContentsForStream(filename, zis, entryName) File.open(filename, "rb") { |file| expected = file.read actual = zis.read if (expected != actual) if (expected.length > 400 || actual.length > 400) zipEntryFilename=entryName+".zipEntry" File.open(zipEntryFilename, "wb") { |file| file << actual } fail("File '#{filename}' is different from '#{zipEntryFilename}'") else assert_equals(expected, actual) end end } end def AssertEntry.assertContents(filename, aString) fileContents = "" File.open(filename, "rb") { |f| fileContents = f.read } if (fileContents != aString) if (expected.length > 400 || actual.length > 400) stringFile = filename + ".other" File.open(stringFile, "wb") { |f| f << aString } fail("File '#{filename}' is different from contents of string stored in '#{stringFile}'") else assert_equals(expected, actual) end end end def assertStreamContents(zis, testZipFile) assert(zis != nil) testZipFile.entryNames.each { |entryName| assertNextEntry(entryName, zis) } assert_equals(nil, zis.getNextEntry) end def assertTestZipContents(testZipFile) ZipInputStream.open(testZipFile.zipName) { |zis| assertStreamContents(zis, testZipFile) } end def assertEntryContents(zipFile, entryName, filename = entryName.to_s) zis = zipFile.getInputStream(entryName) assertEntryContentsForStream(filename, zis, entryName) ensure zis.close if zis end end class ZipInputStreamTest < RUNIT::TestCase include AssertEntry def test_new zis = ZipInputStream.new(TestZipFile::TEST_ZIP2.zipName) assertStreamContents(zis, TestZipFile::TEST_ZIP2) zis.close end def test_openWithBlock ZipInputStream.open(TestZipFile::TEST_ZIP2.zipName) { |zis| assertStreamContents(zis, TestZipFile::TEST_ZIP2) } end def test_openWithoutBlock zis = ZipInputStream.open(TestZipFile::TEST_ZIP2.zipName) assertStreamContents(zis, TestZipFile::TEST_ZIP2) end def test_incompleteReads ZipInputStream.open(TestZipFile::TEST_ZIP2.zipName) { |zis| entry = zis.getNextEntry assert_equals(TestZipFile::TEST_ZIP2.entryNames[0], entry.name) assert zis.gets.length > 0 entry = zis.getNextEntry assert_equals(TestZipFile::TEST_ZIP2.entryNames[1], entry.name) assert_equals(0, entry.size) assert_equals(nil, zis.gets) entry = zis.getNextEntry assert_equals(TestZipFile::TEST_ZIP2.entryNames[2], entry.name) assert zis.gets.length > 0 entry = zis.getNextEntry assert_equals(TestZipFile::TEST_ZIP2.entryNames[3], entry.name) assert zis.gets.length > 0 } end end class TestFiles RANDOM_ASCII_FILE1 = "randomAscii1.txt" RANDOM_ASCII_FILE2 = "randomAscii2.txt" RANDOM_ASCII_FILE3 = "randomAscii3.txt" RANDOM_BINARY_FILE1 = "randomBinary1.bin" RANDOM_BINARY_FILE2 = "randomBinary2.bin" EMPTY_TEST_DIR = "emptytestdir" ASCII_TEST_FILES = [ RANDOM_ASCII_FILE1, RANDOM_ASCII_FILE2, RANDOM_ASCII_FILE3 ] BINARY_TEST_FILES = [ RANDOM_BINARY_FILE1, RANDOM_BINARY_FILE2 ] TEST_DIRECTORIES = [ EMPTY_TEST_DIR ] TEST_FILES = [ ASCII_TEST_FILES, BINARY_TEST_FILES, EMPTY_TEST_DIR ].flatten! def TestFiles.createTestFiles(recreate) if (recreate || ! (TEST_FILES.inject(true) { |accum, element| accum && File.exists?(element) })) ASCII_TEST_FILES.each_with_index { |filename, index| createRandomAscii(filename, 1E4 * (index+1)) } BINARY_TEST_FILES.each_with_index { |filename, index| createRandomBinary(filename, 1E4 * (index+1)) } ensureDir(EMPTY_TEST_DIR) end end private def TestFiles.createRandomAscii(filename, size) File.open(filename, "wb") { |file| while (file.tell < size) file << rand end } end def TestFiles.createRandomBinary(filename, size) File.open(filename, "wb") { |file| while (file.tell < size) file << rand.to_a.pack("V") end } end def TestFiles.ensureDir(name) if File.exists?(name) return if File.stat(name).directory? File.delete(name) end Dir.mkdir(name) end end # For representation and creation of # test data class TestZipFile attr_accessor :zipName, :entryNames, :comment def initialize(zipName, entryNames, comment = "") @zipName=zipName @entryNames=entryNames @comment = comment end def TestZipFile.createTestZips(recreate) files = Dir.entries(".") if (recreate || ! (files.index(TEST_ZIP1.zipName) && files.index(TEST_ZIP2.zipName) && files.index(TEST_ZIP3.zipName) && files.index(TEST_ZIP4.zipName) && files.index("empty.txt") && files.index("short.txt") && files.index("longAscii.txt") && files.index("longBinary.bin") )) raise "failed to create test zip '#{TEST_ZIP1.zipName}'" unless system("zip #{TEST_ZIP1.zipName} ziptest.rb") raise "failed to remove entry from '#{TEST_ZIP1.zipName}'" unless system("zip #{TEST_ZIP1.zipName} -d ziptest.rb") File.open("empty.txt", "w") {} File.open("short.txt", "w") { |file| file << "ABCDEF" } ziptestTxt="" File.open("ziptest.rb") { |file| ziptestTxt=file.read } File.open("longAscii.txt", "w") { |file| while (file.tell < 1E5) file << ziptestTxt end } testBinaryPattern="" File.open("empty.zip") { |file| testBinaryPattern=file.read } testBinaryPattern *= 4 File.open("longBinary.bin", "wb") { |file| while (file.tell < 3E5) file << testBinaryPattern << rand end } raise "failed to create test zip '#{TEST_ZIP2.zipName}'" unless system("zip #{TEST_ZIP2.zipName} #{TEST_ZIP2.entryNames.join(' ')}") # without bash system interprets everything after echo as parameters to # echo including | zip -z ... raise "failed to add comment to test zip '#{TEST_ZIP2.zipName}'" unless system("bash -c \"echo #{TEST_ZIP2.comment} | zip -z #{TEST_ZIP2.zipName}\"") raise "failed to create test zip '#{TEST_ZIP3.zipName}'" unless system("zip #{TEST_ZIP3.zipName} #{TEST_ZIP3.entryNames.join(' ')}") raise "failed to create test zip '#{TEST_ZIP4.zipName}'" unless system("zip #{TEST_ZIP4.zipName} #{TEST_ZIP4.entryNames.join(' ')}") end rescue raise $!.to_s + "\n\nziptest.rb requires the Info-ZIP program 'zip' in the path\n" + "to create test data. If you don't have it you can download\n" + "the necessary test files at http://sf.net/projects/rubyzip." end TEST_ZIP1 = TestZipFile.new("empty.zip", []) TEST_ZIP2 = TestZipFile.new("4entry.zip", %w{ longAscii.txt empty.txt short.txt longBinary.bin}, "my zip comment") TEST_ZIP3 = TestZipFile.new("test1.zip", %w{ file1.txt }) TEST_ZIP4 = TestZipFile.new("zipWithDir.zip", [ "file1.txt", TestFiles::EMPTY_TEST_DIR]) end class AbstractOutputStreamTest < RUNIT::TestCase class TestOutputStream include AbstractOutputStream attr_accessor :buffer def initialize @buffer = "" end def << (data) @buffer << data self end end def setup @outputStream = TestOutputStream.new @origCommaSep = $, @origOutputSep = $\ end def teardown $, = @origCommaSep $\ = @origOutputSep end def test_write count = @outputStream.write("a little string") assert_equals("a little string", @outputStream.buffer) assert_equals("a little string".length, count) count = @outputStream.write(". a little more") assert_equals("a little string. a little more", @outputStream.buffer) assert_equals(". a little more".length, count) end def test_print $\ = nil # record separator set to nil @outputStream.print("hello") assert_equals("hello", @outputStream.buffer) @outputStream.print(" world.") assert_equals("hello world.", @outputStream.buffer) @outputStream.print(" You ok ", "out ", "there?") assert_equals("hello world. You ok out there?", @outputStream.buffer) $\ = "\n" @outputStream.print assert_equals("hello world. You ok out there?\n", @outputStream.buffer) @outputStream.print("I sure hope so!") assert_equals("hello world. You ok out there?\nI sure hope so!\n", @outputStream.buffer) $, = "X" @outputStream.buffer = "" @outputStream.print("monkey", "duck", "zebra") assert_equals("monkeyXduckXzebra\n", @outputStream.buffer) $\ = nil @outputStream.buffer = "" @outputStream.print(20) assert_equals("20", @outputStream.buffer) end def test_printf @outputStream.printf("%d %04x", 123, 123) assert_equals("123 007b", @outputStream.buffer) end def test_putc @outputStream.putc("A") assert_equals("A", @outputStream.buffer) @outputStream.putc(65) assert_equals("AA", @outputStream.buffer) end def test_puts @outputStream.puts assert_equals("\n", @outputStream.buffer) @outputStream.puts("hello", "world") assert_equals("\nhello\nworld\n", @outputStream.buffer) @outputStream.buffer = "" @outputStream.puts("hello\n", "world\n") assert_equals("hello\nworld\n", @outputStream.buffer) @outputStream.buffer = "" @outputStream.puts(["hello\n", "world\n"]) assert_equals("hello\nworld\n", @outputStream.buffer) @outputStream.buffer = "" @outputStream.puts(["hello\n", "world\n"], "bingo") assert_equals("hello\nworld\nbingo\n", @outputStream.buffer) @outputStream.buffer = "" @outputStream.puts(16, 20, 50, "hello") assert_equals("16\n20\n50\nhello\n", @outputStream.buffer) end end module CrcTest def runCrcTest(compressorClass) str = "Here's a nice little text to compute the crc for! Ho hum, it is nice nice nice nice indeed." fakeOut = AbstractOutputStreamTest::TestOutputStream.new deflater = compressorClass.new(fakeOut) deflater << str assert_equals(0x919920fc, deflater.crc) end end class PassThruCompressorTest < RUNIT::TestCase include CrcTest def test_size File.open("dummy.txt", "wb") { |file| compressor = PassThruCompressor.new(file) assert_equals(0, compressor.size) t1 = "hello world" t2 = "" t3 = "bingo" compressor << t1 assert_equals(compressor.size, t1.size) compressor << t2 assert_equals(compressor.size, t1.size + t2.size) compressor << t3 assert_equals(compressor.size, t1.size + t2.size + t3.size) } end def test_crc runCrcTest(PassThruCompressor) end end class DeflaterTest < RUNIT::TestCase include CrcTest def test_outputOperator txt = loadFile("ziptest.rb") deflate(txt, "deflatertest.bin") inflatedTxt = inflate("deflatertest.bin") assert_equals(txt, inflatedTxt) end private def loadFile(fileName) txt = nil File.open(fileName, "rb") { |f| txt = f.read } end def deflate(data, fileName) File.open(fileName, "wb") { |file| deflater = Deflater.new(file) deflater << data deflater.finish assert_equals(deflater.size, data.size) file << "trailing data for zlib with -MAX_WBITS" } end def inflate(fileName) txt = nil File.open(fileName, "rb") { |file| inflater = Inflater.new(file) txt = inflater.read } end def test_crc runCrcTest(Deflater) end end class ZipOutputStreamTest < RUNIT::TestCase include AssertEntry TEST_ZIP = TestZipFile::TEST_ZIP2.clone TEST_ZIP.zipName = "output.zip" def test_new zos = ZipOutputStream.new(TEST_ZIP.zipName) zos.comment = TEST_ZIP.comment writeTestZip(zos) zos.close assertTestZipContents(TEST_ZIP) end def test_open ZipOutputStream.open(TEST_ZIP.zipName) { |zos| zos.comment = TEST_ZIP.comment writeTestZip(zos) } assertTestZipContents(TEST_ZIP) end def test_writingToClosedStream assertIOErrorInClosedStream { |zos| zos << "hello world" } assertIOErrorInClosedStream { |zos| zos.puts "hello world" } assertIOErrorInClosedStream { |zos| zos.write "hello world" } end def test_cannotOpenFile name = TestFiles::EMPTY_TEST_DIR begin zos = ZipOutputStream.open(name) rescue Exception assert($!.kind_of?(Errno::EISDIR) || # Linux $!.kind_of?(Errno::EEXIST) || # Windows/cygwin $!.kind_of?(Errno::EACCES), # Windows "Expected Errno::EISDIR (or on win/cygwin: Errno::EEXIST), but was: #{$!.type}") end end def assertIOErrorInClosedStream assert_exception(IOError) { zos = ZipOutputStream.new("test_putOnClosedStream.zip") zos.close yield zos } end def writeTestZip(zos) TEST_ZIP.entryNames.each { |entryName| zos.putNextEntry(entryName) File.open(entryName, "rb") { |f| zos.write(f.read) } } end end module Enumerable def compareEnumerables(otherEnumerable) otherAsArray = otherEnumerable.to_a index=0 each_with_index { |element, index| return false unless yield(element, otherAsArray[index]) } return index+1 == otherAsArray.size end end class ZipCentralDirectoryEntryTest < RUNIT::TestCase def test_readFromStream File.open("testDirectory.bin", "rb") { |file| entry = ZipEntry.readCDirEntry(file) assert_equals("longAscii.txt", entry.name) assert_equals(ZipEntry::DEFLATED, entry.compressionMethod) assert_equals(106490, entry.size) assert_equals(3784, entry.compressedSize) assert_equals(0xfcd1799c, entry.crc) assert_equals("", entry.comment) entry = ZipEntry.readCDirEntry(file) assert_equals("empty.txt", entry.name) assert_equals(ZipEntry::STORED, entry.compressionMethod) assert_equals(0, entry.size) assert_equals(0, entry.compressedSize) assert_equals(0x0, entry.crc) assert_equals("", entry.comment) entry = ZipEntry.readCDirEntry(file) assert_equals("short.txt", entry.name) assert_equals(ZipEntry::STORED, entry.compressionMethod) assert_equals(6, entry.size) assert_equals(6, entry.compressedSize) assert_equals(0xbb76fe69, entry.crc) assert_equals("", entry.comment) entry = ZipEntry.readCDirEntry(file) assert_equals("longBinary.bin", entry.name) assert_equals(ZipEntry::DEFLATED, entry.compressionMethod) assert_equals(1000024, entry.size) assert_equals(70847, entry.compressedSize) assert_equals(0x10da7d59, entry.crc) assert_equals("", entry.comment) entry = ZipEntry.readCDirEntry(file) assert_equals(nil, entry) # Fields that are not check by this test: # version made by 2 bytes # version needed to extract 2 bytes # general purpose bit flag 2 bytes # last mod file time 2 bytes # last mod file date 2 bytes # compressed size 4 bytes # uncompressed size 4 bytes # disk number start 2 bytes # internal file attributes 2 bytes # external file attributes 4 bytes # relative offset of local header 4 bytes # file name (variable size) # extra field (variable size) # file comment (variable size) } end def test_ReadEntryFromTruncatedZipFile fragment="" File.open("testDirectory.bin") { |f| fragment = f.read(12) } # cdir entry header is at least 46 bytes fragment.extend(IOizeString) entry = ZipEntry.new entry.readCDirEntry(fragment) fail "ZipError expected" rescue ZipError end end class ZipCentralDirectoryTest < RUNIT::TestCase def test_readFromStream File.open(TestZipFile::TEST_ZIP2.zipName, "rb") { |zipFile| cdir = ZipCentralDirectory.readFromStream(zipFile) assert_equals(TestZipFile::TEST_ZIP2.entryNames.size, cdir.size) assert(cdir.compareEnumerables(TestZipFile::TEST_ZIP2.entryNames) { |cdirEntry, testEntryName| cdirEntry.name == testEntryName }) assert_equals(TestZipFile::TEST_ZIP2.comment, cdir.comment) } end def test_readFromInvalidStream File.open("ziptest.rb", "rb") { |zipFile| cdir = ZipCentralDirectory.new cdir.readFromStream(zipFile) } fail "ZipError expected!" rescue ZipError end def test_ReadFromTruncatedZipFile fragment="" File.open("testDirectory.bin") { |f| fragment = f.read } fragment.slice!(12) # removed part of first cdir entry. eocd structure still complete fragment.extend(IOizeString) entry = ZipCentralDirectory.new entry.readFromStream(fragment) fail "ZipError expected" rescue ZipError end def test_writeToStream entries = [ ZipEntry.new("file.zip", "flimse", "myComment", "somethingExtra"), ZipEntry.new("file.zip", "secondEntryName"), ZipEntry.new("file.zip", "lastEntry.txt", "Has a comment too") ] cdir = ZipCentralDirectory.new(entries, "my zip comment") File.open("cdirtest.bin", "wb") { |f| cdir.writeToStream(f) } cdirReadback = ZipCentralDirectory.new File.open("cdirtest.bin", "rb") { |f| cdirReadback.readFromStream(f) } assert_equals(cdir.entries, cdirReadback.entries) end def test_equality cdir1 = ZipCentralDirectory.new([ ZipEntry.new("file.zip", "flimse", nil, "somethingExtra"), ZipEntry.new("file.zip", "secondEntryName"), ZipEntry.new("file.zip", "lastEntry.txt") ], "my zip comment") cdir2 = ZipCentralDirectory.new([ ZipEntry.new("file.zip", "flimse", nil, "somethingExtra"), ZipEntry.new("file.zip", "secondEntryName"), ZipEntry.new("file.zip", "lastEntry.txt") ], "my zip comment") cdir3 = ZipCentralDirectory.new([ ZipEntry.new("file.zip", "flimse", nil, "somethingExtra"), ZipEntry.new("file.zip", "secondEntryName"), ZipEntry.new("file.zip", "lastEntry.txt") ], "comment?") cdir4 = ZipCentralDirectory.new([ ZipEntry.new("file.zip", "flimse", nil, "somethingExtra"), ZipEntry.new("file.zip", "lastEntry.txt") ], "comment?") assert_equals(cdir1, cdir1) assert_equals(cdir1, cdir2) assert(cdir1 != cdir3) assert(cdir2 != cdir3) assert(cdir2 != cdir3) assert(cdir3 != cdir4) assert(cdir3 != "hello") end end class BasicZipFileTest < RUNIT::TestCase include AssertEntry def setup @zipFile = ZipFile.new(TestZipFile::TEST_ZIP2.zipName) @testEntryNameIndex=0 end def nextTestEntryName retVal=TestZipFile::TEST_ZIP2.entryNames[@testEntryNameIndex] @testEntryNameIndex+=1 return retVal end def test_entries assert_equals(TestZipFile::TEST_ZIP2.entryNames, @zipFile.entries.map {|e| e.name} ) end def test_each @zipFile.each { |entry| assert_equals(nextTestEntryName, entry.name) } assert_equals(4, @testEntryNameIndex) end def test_foreach ZipFile.foreach(TestZipFile::TEST_ZIP2.zipName) { |entry| assert_equals(nextTestEntryName, entry.name) } assert_equals(4, @testEntryNameIndex) end def test_getInputStream @zipFile.each { |entry| assertEntry(nextTestEntryName, @zipFile.getInputStream(entry), entry.name) } assert_equals(4, @testEntryNameIndex) end def test_getInputStreamBlock fileAndEntryName = @zipFile.entries.first.name @zipFile.getInputStream(fileAndEntryName) { |zis| assertEntryContentsForStream(fileAndEntryName, zis, fileAndEntryName) } end end class CommonZipFileFixture < RUNIT::TestCase include AssertEntry EMPTY_FILENAME = "emptyZipFile.zip" TEST_ZIP = TestZipFile::TEST_ZIP2.clone TEST_ZIP.zipName = "4entry_copy.zip" def setup File.delete(EMPTY_FILENAME) if File.exists?(EMPTY_FILENAME) File.copy(TestZipFile::TEST_ZIP2.zipName, TEST_ZIP.zipName) end end class ZipFileTest < CommonZipFileFixture def test_createFromScratch comment = "a short comment" zf = ZipFile.new(EMPTY_FILENAME, ZipFile::CREATE) zf.comment = comment zf.close zfRead = ZipFile.new(EMPTY_FILENAME) assert_equals(comment, zfRead.comment) assert_equals(0, zfRead.entries.length) end def test_add srcFile = "ziptest.rb" entryName = "newEntryName.rb" assert(File.exists? srcFile) zf = ZipFile.new(EMPTY_FILENAME, ZipFile::CREATE) zf.add(entryName, srcFile) zf.close zfRead = ZipFile.new(EMPTY_FILENAME) assert_equals("", zfRead.comment) assert_equals(1, zfRead.entries.length) assert_equals(entryName, zfRead.entries.first.name) AssertEntry.assertContents(srcFile, zfRead.getInputStream(entryName) { |zis| zis.read }) end def test_addExistingEntryName assert_exception(ZipEntryExistsError) { ZipFile.open(TEST_ZIP.zipName) { |zf| zf.add(zf.entries.first.name, "ziptest.rb") } } end def test_addExistingEntryNameReplace gotCalled = false replacedEntry = nil ZipFile.open(TEST_ZIP.zipName) { |zf| replacedEntry = zf.entries.first.name zf.add(replacedEntry, "ziptest.rb") { gotCalled = true; true } } assert(gotCalled) ZipFile.open(TEST_ZIP.zipName) { |zf| assertContains(zf, replacedEntry, "ziptest.rb") } end def test_addDirectory ZipFile.open(TEST_ZIP.zipName) { |zf| zf.add(TestFiles::EMPTY_TEST_DIR, TestFiles::EMPTY_TEST_DIR) } ZipFile.open(TEST_ZIP.zipName) { |zf| dirEntry = zf.entries.detect { |e| e.name == TestFiles::EMPTY_TEST_DIR+"/" } assert(dirEntry.isDirectory) } end def test_remove entryToRemove, *remainingEntries = TEST_ZIP.entryNames File.copy(TestZipFile::TEST_ZIP2.zipName, TEST_ZIP.zipName) zf = ZipFile.new(TEST_ZIP.zipName) assert(zf.entries.map { |e| e.name }.include?(entryToRemove)) zf.remove(entryToRemove) assert(! zf.entries.map { |e| e.name }.include?(entryToRemove)) assert_equals(zf.entries.map {|x| x.name }.sort, remainingEntries.sort) zf.close zfRead = ZipFile.new(TEST_ZIP.zipName) assert(! zfRead.entries.map { |e| e.name }.include?(entryToRemove)) assert_equals(zfRead.entries.map {|x| x.name }.sort, remainingEntries.sort) zfRead.close end def test_rename entryToRename, *remainingEntries = TEST_ZIP.entryNames zf = ZipFile.new(TEST_ZIP.zipName) assert(zf.entries.map { |e| e.name }.include? entryToRename) newName = "changed name" assert(! zf.entries.map { |e| e.name }.include?(newName)) zf.rename(entryToRename, newName) assert(zf.entries.map { |e| e.name }.include? newName) zf.close zfRead = ZipFile.new(TEST_ZIP.zipName) assert(zfRead.entries.map { |e| e.name }.include? newName) zfRead.close end def test_renameToExistingEntry oldEntries = nil ZipFile.open(TEST_ZIP.zipName) { |zf| oldEntries = zf.entries } assert_exception(ZipEntryExistsError) { ZipFile.open(TEST_ZIP.zipName) { |zf| zf.rename(zf.entries[0], zf.entries[1].name) } } ZipFile.open(TEST_ZIP.zipName) { |zf| assert_equals(oldEntries.map{ |e| e.name }, zf.entries.map{ |e| e.name }) } end def test_renameToExistingEntryOverwrite oldEntries = nil ZipFile.open(TEST_ZIP.zipName) { |zf| oldEntries = zf.entries } gotCalled = false ZipFile.open(TEST_ZIP.zipName) { |zf| zf.rename(zf.entries[0], zf.entries[1].name) { gotCalled = true; true } } assert(gotCalled) oldEntries.delete_at(0) ZipFile.open(TEST_ZIP.zipName) { |zf| assert_equals(oldEntries.map{ |e| e.name }, zf.entries.map{ |e| e.name }) } end def test_renameNonEntry nonEntry = "bogusEntry" targetEntry = "targetEntryName" zf = ZipFile.new(TEST_ZIP.zipName) assert(! zf.entries.include?(nonEntry)) assert_exception(ZipNoSuchEntryError) { zf.rename(nonEntry, targetEntry) } zf.commit assert(! zf.entries.include?(targetEntry)) ensure zf.close end def test_renameEntryToExistingEntry entry1, entry2, *remaining = TEST_ZIP.entryNames zf = ZipFile.new(TEST_ZIP.zipName) assert_exception(ZipEntryExistsError) { zf.rename(entry1, entry2) } ensure zf.close end def test_replace unchangedEntries = TEST_ZIP.entryNames.dup entryToReplace = unchangedEntries.delete_at(2) newEntrySrcFilename = "ziptest.rb" zf = ZipFile.new(TEST_ZIP.zipName) zf.replace(entryToReplace, newEntrySrcFilename) zf.close zfRead = ZipFile.new(TEST_ZIP.zipName) AssertEntry::assertContents(newEntrySrcFilename, zfRead.getInputStream(entryToReplace) { |is| is.read }) zfRead.close end def test_replaceNonEntry entryToReplace = "nonExistingEntryname" ZipFile.open(TEST_ZIP.zipName) { |zf| assert_exception(ZipNoSuchEntryError) { zf.replace(entryToReplace, "ziptest.rb") } } end def test_commit newName = "renamedFirst" zf = ZipFile.new(TEST_ZIP.zipName) oldName = zf.entries.first zf.rename(oldName, newName) zf.commit zfRead = ZipFile.new(TEST_ZIP.zipName) assert(zfRead.entries.detect { |e| e.name == newName } != nil) assert(zfRead.entries.detect { |e| e.name == oldName } == nil) zfRead.close zf.close end # This test tests that after commit, you # can delete the file you used to add the entry to the zip file # with def test_commitUseZipEntry File.copy(TestFiles::RANDOM_ASCII_FILE1, "okToDelete.txt") zf = ZipFile.open(TEST_ZIP.zipName) zf.add("okToDelete.txt", "okToDelete.txt") assertContains(zf, "okToDelete.txt") zf.commit File.move("okToDelete.txt", "okToDeleteMoved.txt") assertContains(zf, "okToDelete.txt", "okToDeleteMoved.txt") end # def test_close # zf = ZipFile.new(TEST_ZIP.zipName) # zf.close # assert_exception(IOError) { # zf.extract(TEST_ZIP.entryNames.first, "hullubullu") # } # end def test_compound1 renamedName = "renamedName" originalEntries = [] begin zf = ZipFile.new(TEST_ZIP.zipName) originalEntries = zf.entries.dup assertNotContains(zf, TestFiles::RANDOM_ASCII_FILE1) zf.add(TestFiles::RANDOM_ASCII_FILE1, TestFiles::RANDOM_ASCII_FILE1) assertContains(zf, TestFiles::RANDOM_ASCII_FILE1) zf.rename(zf.entries[0], renamedName) assertContains(zf, renamedName) TestFiles::BINARY_TEST_FILES.each { |filename| zf.add(filename, filename) assertContains(zf, filename) } assertContains(zf, originalEntries.last.to_s) zf.remove(originalEntries.last.to_s) assertNotContains(zf, originalEntries.last.to_s) ensure zf.close end begin zfRead = ZipFile.new(TEST_ZIP.zipName) assertContains(zfRead, TestFiles::RANDOM_ASCII_FILE1) assertContains(zfRead, renamedName) TestFiles::BINARY_TEST_FILES.each { |filename| assertContains(zfRead, filename) } assertNotContains(zfRead, originalEntries.last.to_s) ensure zfRead.close end end def test_compound2 begin zf = ZipFile.new(TEST_ZIP.zipName) originalEntries = zf.entries.dup originalEntries.each { |entry| zf.remove(entry) assertNotContains(zf, entry) } assert(zf.entries.empty?) TestFiles::ASCII_TEST_FILES.each { |filename| zf.add(filename, filename) assertContains(zf, filename) } assert_equals(zf.entries.map { |e| e.name }, TestFiles::ASCII_TEST_FILES) zf.rename(TestFiles::ASCII_TEST_FILES[0], "newName") assertNotContains(zf, TestFiles::ASCII_TEST_FILES[0]) assertContains(zf, "newName") ensure zf.close end begin zfRead = ZipFile.new(TEST_ZIP.zipName) asciiTestFiles = TestFiles::ASCII_TEST_FILES.dup asciiTestFiles.shift asciiTestFiles.each { |filename| assertContains(zf, filename) } assertContains(zf, "newName") ensure zfRead.close end end private def assertContains(zf, entryName, filename = entryName) assert(zf.entries.detect { |e| e.name == entryName} != nil, "entry #{entryName} not in #{zf.entries.join(', ')} in zip file #{zf}") assertEntryContents(zf, entryName, filename) if File.exists?(filename) end def assertNotContains(zf, entryName) assert(zf.entries.detect { |e| e.name == entryName} == nil, "entry #{entryName} in #{zf.entries.join(', ')} in zip file #{zf}") end end class ZipFileExtractTest < CommonZipFileFixture EXTRACTED_FILENAME = "extEntry" ENTRY_TO_EXTRACT, *REMAINING_ENTRIES = TEST_ZIP.entryNames.reverse def setup super File.delete(EXTRACTED_FILENAME) if File.exists?(EXTRACTED_FILENAME) end def test_extract ZipFile.open(TEST_ZIP.zipName) { |zf| zf.extract(ENTRY_TO_EXTRACT, EXTRACTED_FILENAME) assert(File.exists? EXTRACTED_FILENAME) AssertEntry::assertContents(EXTRACTED_FILENAME, zf.getInputStream(ENTRY_TO_EXTRACT) { |is| is.read }) } end def test_extractExists writtenText = "written text" File.open(EXTRACTED_FILENAME, "w") { |f| f.write(writtenText) } assert_exception(ZipDestinationFileExistsError) { ZipFile.open(TEST_ZIP.zipName) { |zf| zf.extract(zf.entries.first, EXTRACTED_FILENAME) } } File.open(EXTRACTED_FILENAME, "r") { |f| assert_equals(writtenText, f.read) } end def test_extractExistsOverwrite writtenText = "written text" File.open(EXTRACTED_FILENAME, "w") { |f| f.write(writtenText) } gotCalled = false ZipFile.open(TEST_ZIP.zipName) { |zf| zf.extract(zf.entries.first, EXTRACTED_FILENAME) { gotCalled = true; true } } assert(gotCalled) File.open(EXTRACTED_FILENAME, "r") { |f| assert(writtenText != f.read) } end def test_extractNonEntry zf = ZipFile.new(TEST_ZIP.zipName) assert_exception(ZipNoSuchEntryError) { zf.extract("nonExistingEntry", "nonExistingEntry") } ensure zf.close if zf end def test_extractNonEntry2 outFile = "outfile" assert_exception(ZipNoSuchEntryError) { zf = ZipFile.new(TEST_ZIP.zipName) nonEntry = "hotdog-diddelidoo" assert(! zf.entries.include?(nonEntry)) zf.extract(nonEntry, outFile) zf.close } assert(! File.exists?(outFile)) end end class ZipFileExtractDirectoryTest < CommonZipFileFixture TEST_OUT_NAME = "emptyOutDir" def openZip(&aProc) assert(aProc != nil) ZipFile.open(TestZipFile::TEST_ZIP4.zipName, &aProc) end def extractTestDir(&aProc) openZip { |zf| zf.extract(TestFiles::EMPTY_TEST_DIR, TEST_OUT_NAME, &aProc) } end def setup super Dir.rmdir(TEST_OUT_NAME) if File.directory? TEST_OUT_NAME File.delete(TEST_OUT_NAME) if File.exists? TEST_OUT_NAME end def test_extractDirectory extractTestDir assert(File.directory? TEST_OUT_NAME) end def test_extractDirectoryExistsAsDir Dir.mkdir TEST_OUT_NAME extractTestDir assert(File.directory? TEST_OUT_NAME) end def test_extractDirectoryExistsAsFile File.open(TEST_OUT_NAME, "w") { |f| f.puts "something" } assert_exception(ZipDestinationFileExistsError) { extractTestDir } end def test_extractDirectoryExistsAsFileOverwrite File.open(TEST_OUT_NAME, "w") { |f| f.puts "something" } gotCalled = false extractTestDir { |entry, destPath| gotCalled = true assert_equals(TEST_OUT_NAME, destPath) assert(entry.isDirectory) true } assert(gotCalled) assert(File.directory? TEST_OUT_NAME) end end TestFiles::createTestFiles(ARGV.index("recreate") != nil || ARGV.index("recreateonly") != nil) TestZipFile::createTestZips(ARGV.index("recreate") != nil || ARGV.index("recreateonly") != nil) exit if ARGV.index("recreateonly") != nil #require 'runit/cui/testrunner' #RUNIT::CUI::TestRunner.run(ZipFileTest.suite) # Copyright (C) 2002 Thomas Sondergaard # rubyzip is free software; you can redistribute it and/or # modify it under the terms of the ruby license. zip-zip-0.3/test/0.9.9/data/globTest.zip000066400000000000000000000021721232145563700176440ustar00rootroot00000000000000PK ;@ globTest/UX OOPK L@ globTest/foo/UX OOPK L@globTest/foo/bar/UX OOPK Ʀ@globTest/foo/bar/baz/UX OOPK O@globTest/foo/bar/baz/foo/UX OOPK Ʀ@globTest/foo/bar/baz/foo.txtUX OOPK 4@globTest/foo.txtUX 䵶O䵶OPK ;@globTest/food.txtUX OOPK ;@ @AglobTest/UXOOPK L@ @A7globTest/foo/UXOOPK L@ @ArglobTest/foo/bar/UXOOPK Ʀ@ @AglobTest/foo/bar/baz/UXOOPK O@ @AglobTest/foo/bar/baz/foo/UXOOPK Ʀ@ @;globTest/foo/bar/baz/foo.txtUXOOPK 4@ @globTest/foo.txtUX䵶O䵶OPK ;@ @globTest/food.txtUXOOPKbzip-zip-0.3/test/0.9.9/data/globTest/000077500000000000000000000000001232145563700171165ustar00rootroot00000000000000zip-zip-0.3/test/0.9.9/data/globTest/foo.txt000066400000000000000000000000001232145563700204300ustar00rootroot00000000000000zip-zip-0.3/test/0.9.9/data/globTest/foo/000077500000000000000000000000001232145563700177015ustar00rootroot00000000000000zip-zip-0.3/test/0.9.9/data/globTest/foo/bar/000077500000000000000000000000001232145563700204455ustar00rootroot00000000000000zip-zip-0.3/test/0.9.9/data/globTest/foo/bar/baz/000077500000000000000000000000001232145563700212215ustar00rootroot00000000000000zip-zip-0.3/test/0.9.9/data/globTest/foo/bar/baz/foo.txt000066400000000000000000000000001232145563700225330ustar00rootroot00000000000000zip-zip-0.3/test/0.9.9/data/globTest/food.txt000066400000000000000000000000001232145563700205740ustar00rootroot00000000000000zip-zip-0.3/test/0.9.9/data/notzippedruby.rb000077500000000000000000000001151232145563700205760ustar00rootroot00000000000000#!/usr/bin/env ruby class NotZippedRuby def returnTrue true end end zip-zip-0.3/test/0.9.9/data/rubycode.zip000066400000000000000000000011511232145563700176710ustar00rootroot00000000000000PK, MWzippedruby1.rbUT Ʋ<ͷj&(A>ORq2p =P!pJiHq *_45>PK ̈́,dir2/UT ^A=^A=UxPK "}, dir2/dir21/UT oQA=^A=UxPK ̈́,dir2/dir21/dir221/UT ^A=^A=UxPK̈́,,O]dir2/dir21/dir221/file2221UT ^A=^A=UxA 0 }zMESVag1 :!--#E*18;̑rlvdzPEPK̈́,QhHN dir2/file21UT ^A=^A=Ux A 0 {_zS/|Fѕj&(A>e9j}}8:nk'_45>PK̈́,)gDHfile1UT ^A=^A=Ux A 0 {_z|%B^I?\: s Hȼn h|{PK ̈́, Adir1/UT^A=UxPK ̈́, A8dir1/dir11/UT^A=UxPK̈́,x 2KU vdir1/dir11/file111UT^A=UxPK̈́,HN dir1/file11UT^A=UxPK̈́,USHN dir1/file12UT^A=UxPK ̈́, Adir2/UT^A=UxPK "}, AJdir2/dir21/UToQA=UxPK ̈́, Adir2/dir21/dir221/UT^A=UxPK̈́,,O] dir2/dir21/dir221/file2221UT^A=UxPK̈́,QhHN idir2/file21UT^A=UxPK̈́,)gDH file1UT^A=UxPK kzip-zip-0.3/test/0.9.9/gentestfiles.rb000066400000000000000000000131471232145563700174510ustar00rootroot00000000000000class TestFiles RANDOM_ASCII_FILE1 = "#{GEN_DIR}/randomAscii1.txt" RANDOM_ASCII_FILE2 = "#{GEN_DIR}/randomAscii2.txt" RANDOM_ASCII_FILE3 = "#{GEN_DIR}/randomAscii3.txt" RANDOM_BINARY_FILE1 = "#{GEN_DIR}/randomBinary1.bin" RANDOM_BINARY_FILE2 = "#{GEN_DIR}/randomBinary2.bin" EMPTY_TEST_DIR = "#{GEN_DIR}/emptytestdir" ASCII_TEST_FILES = [ RANDOM_ASCII_FILE1, RANDOM_ASCII_FILE2, RANDOM_ASCII_FILE3 ] BINARY_TEST_FILES = [ RANDOM_BINARY_FILE1, RANDOM_BINARY_FILE2 ] TEST_DIRECTORIES = [ EMPTY_TEST_DIR ] TEST_FILES = [ ASCII_TEST_FILES, BINARY_TEST_FILES, EMPTY_TEST_DIR ].flatten! def TestFiles.create_test_files(recreate) if (recreate || ! (TEST_FILES.inject(true) { |accum, element| accum && File.exists?(element) })) FileUtils.mkdir_p GEN_DIR ASCII_TEST_FILES.each_with_index do |filename, index| create_random_ascii(filename, 1E4 * (index+1)) end BINARY_TEST_FILES.each_with_index do |filename, index| create_random_binary(filename, 1E4 * (index+1)) end ensure_dir(EMPTY_TEST_DIR) end end private def TestFiles.create_random_ascii(filename, size) File.open(filename, "wb") do |file| while (file.tell < size) file << rand end end end def TestFiles.create_random_binary(filename, size) File.open(filename, "wb") do |file| while (file.tell < size) file << [rand].pack("V") end end end def TestFiles.ensure_dir(name) if File.exists?(name) return if File.stat(name).directory? File.delete(name) end Dir.mkdir(name) end end # For representation and creation of # test data class TestZipFile attr_accessor :zip_name, :entry_names, :comment def initialize(zip_name, entry_names, comment = "") @zip_name=zip_name @entry_names=entry_names @comment = comment end def TestZipFile.create_test_zips(recreate) files = Dir.entries(GEN_DIR) if (recreate || ! (files.index(File.basename(TEST_ZIP1.zip_name)) && files.index(File.basename(TEST_ZIP2.zip_name)) && files.index(File.basename(TEST_ZIP3.zip_name)) && files.index(File.basename(TEST_ZIP4.zip_name)) && files.index("empty.txt") && files.index("empty_chmod640.txt") && files.index("short.txt") && files.index("longAscii.txt") && files.index("longBinary.bin") )) raise "failed to create test zip '#{TEST_ZIP1.zip_name}'" unless system("zip #{TEST_ZIP1.zip_name} #{SRC_DIR}/file2.txt") raise "failed to remove entry from '#{TEST_ZIP1.zip_name}'" unless system("zip #{TEST_ZIP1.zip_name} -d #{SRC_DIR}/file2.txt") File.open("#{GEN_DIR}/empty.txt", "w") {} File.open("#{GEN_DIR}/empty_chmod640.txt", "w") { |f| f.chmod(0640) } File.open("#{GEN_DIR}/short.txt", "w") { |file| file << "ABCDEF" } ziptestTxt="" File.open("#{SRC_DIR}/file2.txt") { |file| ziptestTxt=file.read } File.open("#{GEN_DIR}/longAscii.txt", "w") do |file| while (file.tell < 1E5) file << ziptestTxt end end testBinaryPattern="" File.open("#{GEN_DIR}/empty.zip") { |file| testBinaryPattern=file.read } testBinaryPattern *= 4 File.open("#{GEN_DIR}/longBinary.bin", "wb") do |file| while (file.tell < 3E5) file << testBinaryPattern << rand << "\0" end end raise "failed to create test zip '#{TEST_ZIP2.zip_name}'" unless system("zip #{TEST_ZIP2.zip_name} #{TEST_ZIP2.entry_names.join(' ')}") if RUBY_PLATFORM =~ /mswin|mingw|cygwin/ raise "failed to add comment to test zip '#{TEST_ZIP2.zip_name}'" unless system("echo #{TEST_ZIP2.comment}| zip -z #{TEST_ZIP2.zip_name}\"") else # without bash system interprets everything after echo as parameters to # echo including | zip -z ... raise "failed to add comment to test zip '#{TEST_ZIP2.zip_name}'" unless system("bash -c \"echo #{TEST_ZIP2.comment} | zip -z #{TEST_ZIP2.zip_name}\"") end raise "failed to create test zip '#{TEST_ZIP3.zip_name}'" unless system("zip #{TEST_ZIP3.zip_name} #{TEST_ZIP3.entry_names.join(' ')}") raise "failed to create test zip '#{TEST_ZIP4.zip_name}'" unless system("zip #{TEST_ZIP4.zip_name} #{TEST_ZIP4.entry_names.join(' ')}") end rescue # If there are any Windows developers wanting to use a command line zip.exe # to help create the following files, there's a free one available from # http://stahlworks.com/dev/index.php?tool=zipunzip # that works with the above code raise $!.to_s + "\n\nziptest.rb requires the Info-ZIP program 'zip' in the path\n" + "to create test data. If you don't have it you can download\n" + "the necessary test files at http://sf.net/projects/rubyzip." end TEST_ZIP1 = TestZipFile.new("#{GEN_DIR}/empty.zip", []) TEST_ZIP2 = TestZipFile.new( "#{GEN_DIR}/5entry.zip", [ "#{GEN_DIR}/longAscii.txt", "#{GEN_DIR}/empty.txt", "#{GEN_DIR}/empty_chmod640.txt", "#{GEN_DIR}/short.txt", "#{GEN_DIR}/longBinary.bin" ], "my zip comment" ) TEST_ZIP3 = TestZipFile.new("#{GEN_DIR}/test1.zip", [ "#{SRC_DIR}/file1.txt" ]) TEST_ZIP4 = TestZipFile.new("#{GEN_DIR}/zipWithDir.zip", [ "#{SRC_DIR}/file1.txt", TestFiles::EMPTY_TEST_DIR]) end END { TestFiles::create_test_files(ARGV.index("recreate") != nil || ARGV.index("recreateonly") != nil) TestZipFile::create_test_zips(ARGV.index("recreate") != nil || ARGV.index("recreateonly") != nil) exit if ARGV.index("recreateonly") != nil } zip-zip-0.3/test/0.9.9/ioextrastest.rb000066400000000000000000000113471232145563700175130ustar00rootroot00000000000000require '0.9.9/test_helper' include IOExtras class FakeIOTest < Test::Unit::TestCase class FakeIOUsingClass include FakeIO end def test_kind_of? obj = FakeIOUsingClass.new assert(obj.kind_of?(Object)) assert(obj.kind_of?(FakeIOUsingClass)) assert(obj.kind_of?(IO)) assert(!obj.kind_of?(Fixnum)) assert(!obj.kind_of?(String)) end end class AbstractInputStreamTest < Test::Unit::TestCase # AbstractInputStream subclass that provides a read method TEST_LINES = [ "Hello world#{$/}", "this is the second line#{$/}", "this is the last line"] TEST_STRING = TEST_LINES.join class TestAbstractInputStream include AbstractInputStream def initialize(aString) super() @contents = aString @readPointer = 0 end def read(charsToRead) retVal=@contents[@readPointer, charsToRead] @readPointer+=charsToRead return retVal end def produce_input read(100) end def input_finished? @contents[@readPointer] == nil end end def setup @io = TestAbstractInputStream.new(TEST_STRING) end def test_gets assert_equal(TEST_LINES[0], @io.gets) assert_equal(1, @io.lineno) assert_equal(TEST_LINES[1], @io.gets) assert_equal(2, @io.lineno) assert_equal(TEST_LINES[2], @io.gets) assert_equal(3, @io.lineno) assert_equal(nil, @io.gets) assert_equal(4, @io.lineno) end def test_getsMultiCharSeperator assert_equal("Hell", @io.gets("ll")) assert_equal("o world#{$/}this is the second l", @io.gets("d l")) end def test_each_line lineNumber=0 @io.each_line { |line| assert_equal(TEST_LINES[lineNumber], line) lineNumber+=1 } end def test_readlines assert_equal(TEST_LINES, @io.readlines) end def test_readline test_gets begin @io.readline fail "EOFError expected" rescue EOFError end end end class AbstractOutputStreamTest < Test::Unit::TestCase class TestOutputStream include AbstractOutputStream attr_accessor :buffer def initialize @buffer = "" end def << (data) @buffer << data self end end def setup @outputStream = TestOutputStream.new @origCommaSep = $, @origOutputSep = $\ end def teardown $, = @origCommaSep $\ = @origOutputSep end def test_write count = @outputStream.write("a little string") assert_equal("a little string", @outputStream.buffer) assert_equal("a little string".length, count) count = @outputStream.write(". a little more") assert_equal("a little string. a little more", @outputStream.buffer) assert_equal(". a little more".length, count) end def test_print $\ = nil # record separator set to nil @outputStream.print("hello") assert_equal("hello", @outputStream.buffer) @outputStream.print(" world.") assert_equal("hello world.", @outputStream.buffer) @outputStream.print(" You ok ", "out ", "there?") assert_equal("hello world. You ok out there?", @outputStream.buffer) $\ = "\n" @outputStream.print assert_equal("hello world. You ok out there?\n", @outputStream.buffer) @outputStream.print("I sure hope so!") assert_equal("hello world. You ok out there?\nI sure hope so!\n", @outputStream.buffer) $, = "X" @outputStream.buffer = "" @outputStream.print("monkey", "duck", "zebra") assert_equal("monkeyXduckXzebra\n", @outputStream.buffer) $\ = nil @outputStream.buffer = "" @outputStream.print(20) assert_equal("20", @outputStream.buffer) end def test_printf @outputStream.printf("%d %04x", 123, 123) assert_equal("123 007b", @outputStream.buffer) end def test_putc @outputStream.putc("A") assert_equal("A", @outputStream.buffer) @outputStream.putc(65) assert_equal("AA", @outputStream.buffer) end def test_puts @outputStream.puts assert_equal("\n", @outputStream.buffer) @outputStream.puts("hello", "world") assert_equal("\nhello\nworld\n", @outputStream.buffer) @outputStream.buffer = "" @outputStream.puts("hello\n", "world\n") assert_equal("hello\nworld\n", @outputStream.buffer) @outputStream.buffer = "" @outputStream.puts(["hello\n", "world\n"]) assert_equal("hello\nworld\n", @outputStream.buffer) @outputStream.buffer = "" @outputStream.puts(["hello\n", "world\n"], "bingo") assert_equal("hello\nworld\nbingo\n", @outputStream.buffer) @outputStream.buffer = "" @outputStream.puts(16, 20, 50, "hello") assert_equal("16\n20\n50\nhello\n", @outputStream.buffer) end end # Copyright (C) 2002-2004 Thomas Sondergaard # rubyzip is free software; you can redistribute it and/or # modify it under the terms of the ruby license. zip-zip-0.3/test/0.9.9/test_helper.rb000066400000000000000000000003231232145563700172630ustar00rootroot00000000000000require 'zip/zip' gem "minitest" require 'minitest/autorun' require 'test/unit' TRG_DIR = "tmp" GEN_DIR = "tmp/generated" SRC_DIR = "test/0.9.9/data" FileUtils.mkdir_p TRG_DIR require_relative 'gentestfiles' zip-zip-0.3/test/0.9.9/zipfilesystemtest.rb000066400000000000000000000565601232145563700205720ustar00rootroot00000000000000require '0.9.9/test_helper' require 'zip/zipfilesystem' require 'digest/sha1' module ExtraAssertions def assert_forwarded(anObject, method, retVal, *expectedArgs) callArgs = nil setCallArgsProc = proc { |args| callArgs = args } anObject.instance_eval <<-"end_eval" alias #{method}_org #{method} def #{method}(*args) ObjectSpace._id2ref(#{setCallArgsProc.object_id}).call(args) ObjectSpace._id2ref(#{retVal.object_id}) end end_eval assert_equal(retVal, yield) # Invoke test assert_equal(expectedArgs, callArgs) ensure anObject.instance_eval "undef #{method}; alias #{method} #{method}_org" end end include Zip class ZipFsFileNonmutatingTest < Test::Unit::TestCase def setup @zipsha = Digest::SHA1.file("#{SRC_DIR}/zipWithDirs.zip") @zipFile = ZipFile.new("#{SRC_DIR}/zipWithDirs.zip") end def teardown @zipFile.close if @zipFile assert_equal(@zipsha, Digest::SHA1.file("#{SRC_DIR}/zipWithDirs.zip")) end def test_umask assert_equal(File.umask, @zipFile.file.umask) @zipFile.file.umask(0006) end def test_exists? assert(! @zipFile.file.exists?("notAFile")) assert(@zipFile.file.exists?("file1")) assert(@zipFile.file.exists?("dir1")) assert(@zipFile.file.exists?("dir1/")) assert(@zipFile.file.exists?("dir1/file12")) assert(@zipFile.file.exist?("dir1/file12")) # notice, tests exist? alias of exists? ! @zipFile.dir.chdir "dir1/" assert(!@zipFile.file.exists?("file1")) assert(@zipFile.file.exists?("file12")) end def test_open_read blockCalled = false @zipFile.file.open("file1", "r") { |f| blockCalled = true assert_equal("this is the entry 'file1' in my test archive!", f.readline.chomp) } assert(blockCalled) blockCalled = false @zipFile.file.open("file1", "rb") { # test binary flag is ignored |f| blockCalled = true assert_equal("this is the entry 'file1' in my test archive!", f.readline.chomp) } assert(blockCalled) blockCalled = false @zipFile.dir.chdir "dir2" @zipFile.file.open("file21", "r") { |f| blockCalled = true assert_equal("this is the entry 'dir2/file21' in my test archive!", f.readline.chomp) } assert(blockCalled) @zipFile.dir.chdir "/" assert_raise(Errno::ENOENT) { @zipFile.file.open("noSuchEntry") } begin is = @zipFile.file.open("file1") assert_equal("this is the entry 'file1' in my test archive!", is.readline.chomp) ensure is.close if is end end def test_new begin is = @zipFile.file.new("file1") assert_equal("this is the entry 'file1' in my test archive!", is.readline.chomp) ensure is.close if is end begin is = @zipFile.file.new("file1") { fail "should not call block" } ensure is.close if is end end def test_symlink assert_raise(NotImplementedError) { @zipFile.file.symlink("file1", "aSymlink") } end def test_size assert_raise(Errno::ENOENT) { @zipFile.file.size("notAFile") } assert_equal(72, @zipFile.file.size("file1")) assert_equal(0, @zipFile.file.size("dir2/dir21")) assert_equal(72, @zipFile.file.stat("file1").size) assert_equal(0, @zipFile.file.stat("dir2/dir21").size) end def test_size? assert_equal(nil, @zipFile.file.size?("notAFile")) assert_equal(72, @zipFile.file.size?("file1")) assert_equal(nil, @zipFile.file.size?("dir2/dir21")) assert_equal(72, @zipFile.file.stat("file1").size?) assert_equal(nil, @zipFile.file.stat("dir2/dir21").size?) end def test_file? assert(@zipFile.file.file?("file1")) assert(@zipFile.file.file?("dir2/file21")) assert(! @zipFile.file.file?("dir1")) assert(! @zipFile.file.file?("dir1/dir11")) assert(@zipFile.file.stat("file1").file?) assert(@zipFile.file.stat("dir2/file21").file?) assert(! @zipFile.file.stat("dir1").file?) assert(! @zipFile.file.stat("dir1/dir11").file?) end include ExtraAssertions def test_dirname assert_forwarded(File, :dirname, "retVal", "a/b/c/d") { @zipFile.file.dirname("a/b/c/d") } end def test_basename assert_forwarded(File, :basename, "retVal", "a/b/c/d") { @zipFile.file.basename("a/b/c/d") } end def test_split assert_forwarded(File, :split, "retVal", "a/b/c/d") { @zipFile.file.split("a/b/c/d") } end def test_join assert_equal("a/b/c", @zipFile.file.join("a/b", "c")) assert_equal("a/b/c/d", @zipFile.file.join("a/b", "c/d")) assert_equal("/c/d", @zipFile.file.join("", "c/d")) assert_equal("a/b/c/d", @zipFile.file.join("a", "b", "c", "d")) end def test_utime t_now = DOSTime.now t_bak = @zipFile.file.mtime("file1") @zipFile.file.utime(t_now, "file1") assert_equal(t_now, @zipFile.file.mtime("file1")) @zipFile.file.utime(t_bak, "file1") assert_equal(t_bak, @zipFile.file.mtime("file1")) end def assert_always_false(operation) assert(! @zipFile.file.send(operation, "noSuchFile")) assert(! @zipFile.file.send(operation, "file1")) assert(! @zipFile.file.send(operation, "dir1")) assert(! @zipFile.file.stat("file1").send(operation)) assert(! @zipFile.file.stat("dir1").send(operation)) end def assert_true_if_entry_exists(operation) assert(! @zipFile.file.send(operation, "noSuchFile")) assert(@zipFile.file.send(operation, "file1")) assert(@zipFile.file.send(operation, "dir1")) assert(@zipFile.file.stat("file1").send(operation)) assert(@zipFile.file.stat("dir1").send(operation)) end def test_pipe? assert_always_false(:pipe?) end def test_blockdev? assert_always_false(:blockdev?) end def test_symlink? assert_always_false(:symlink?) end def test_socket? assert_always_false(:socket?) end def test_chardev? assert_always_false(:chardev?) end def test_truncate assert_raise(StandardError, "truncate not supported") { @zipFile.file.truncate("file1", 100) } end def assert_e_n_o_e_n_t(operation, args = ["NoSuchFile"]) assert_raise(Errno::ENOENT) { @zipFile.file.send(operation, *args) } end def test_ftype assert_e_n_o_e_n_t(:ftype) assert_equal("file", @zipFile.file.ftype("file1")) assert_equal("directory", @zipFile.file.ftype("dir1/dir11")) assert_equal("directory", @zipFile.file.ftype("dir1/dir11/")) end def test_link assert_raise(NotImplementedError) { @zipFile.file.link("file1", "someOtherString") } end def test_directory? assert(! @zipFile.file.directory?("notAFile")) assert(! @zipFile.file.directory?("file1")) assert(! @zipFile.file.directory?("dir1/file11")) assert(@zipFile.file.directory?("dir1")) assert(@zipFile.file.directory?("dir1/")) assert(@zipFile.file.directory?("dir2/dir21")) assert(! @zipFile.file.stat("file1").directory?) assert(! @zipFile.file.stat("dir1/file11").directory?) assert(@zipFile.file.stat("dir1").directory?) assert(@zipFile.file.stat("dir1/").directory?) assert(@zipFile.file.stat("dir2/dir21").directory?) end def test_chown assert_equal(2, @zipFile.file.chown(1,2, "dir1", "file1")) assert_equal(1, @zipFile.file.stat("dir1").uid) assert_equal(2, @zipFile.file.stat("dir1").gid) assert_equal(2, @zipFile.file.chown(nil, nil, "dir1", "file1")) end def test_zero? assert(! @zipFile.file.zero?("notAFile")) assert(! @zipFile.file.zero?("file1")) assert(@zipFile.file.zero?("dir1")) blockCalled = false ZipFile.open("#{GEN_DIR}/5entry.zip") { |zf| blockCalled = true assert(zf.file.zero?("#{GEN_DIR}/empty.txt")) } assert(blockCalled) assert(! @zipFile.file.stat("file1").zero?) assert(@zipFile.file.stat("dir1").zero?) blockCalled = false ZipFile.open("#{GEN_DIR}/5entry.zip") { |zf| blockCalled = true assert(zf.file.stat("#{GEN_DIR}/empty.txt").zero?) } assert(blockCalled) end def test_expand_path ZipFile.open("#{SRC_DIR}/zipWithDirs.zip") { |zf| assert_equal("/", zf.file.expand_path(".")) zf.dir.chdir "dir1" assert_equal("/dir1", zf.file.expand_path(".")) assert_equal("/dir1/file12", zf.file.expand_path("file12")) assert_equal("/", zf.file.expand_path("..")) assert_equal("/dir2/dir21", zf.file.expand_path("../dir2/dir21")) } end def test_mtime assert_equal(DOSTime.at(1027694306), @zipFile.file.mtime("dir2/file21")) assert_equal(DOSTime.at(1027690863), @zipFile.file.mtime("dir2/dir21")) assert_raise(Errno::ENOENT) { @zipFile.file.mtime("noSuchEntry") } assert_equal(DOSTime.at(1027694306), @zipFile.file.stat("dir2/file21").mtime) assert_equal(DOSTime.at(1027690863), @zipFile.file.stat("dir2/dir21").mtime) end def test_ctime assert_nil(@zipFile.file.ctime("file1")) assert_nil(@zipFile.file.stat("file1").ctime) end def test_atime assert_nil(@zipFile.file.atime("file1")) assert_nil(@zipFile.file.stat("file1").atime) end def test_readable? assert(! @zipFile.file.readable?("noSuchFile")) assert(@zipFile.file.readable?("file1")) assert(@zipFile.file.readable?("dir1")) assert(@zipFile.file.stat("file1").readable?) assert(@zipFile.file.stat("dir1").readable?) end def test_readable_real? assert(! @zipFile.file.readable_real?("noSuchFile")) assert(@zipFile.file.readable_real?("file1")) assert(@zipFile.file.readable_real?("dir1")) assert(@zipFile.file.stat("file1").readable_real?) assert(@zipFile.file.stat("dir1").readable_real?) end def test_writable? assert(! @zipFile.file.writable?("noSuchFile")) assert(@zipFile.file.writable?("file1")) assert(@zipFile.file.writable?("dir1")) assert(@zipFile.file.stat("file1").writable?) assert(@zipFile.file.stat("dir1").writable?) end def test_writable_real? assert(! @zipFile.file.writable_real?("noSuchFile")) assert(@zipFile.file.writable_real?("file1")) assert(@zipFile.file.writable_real?("dir1")) assert(@zipFile.file.stat("file1").writable_real?) assert(@zipFile.file.stat("dir1").writable_real?) end def test_executable? assert(! @zipFile.file.executable?("noSuchFile")) assert(! @zipFile.file.executable?("file1")) assert(@zipFile.file.executable?("dir1")) assert(! @zipFile.file.stat("file1").executable?) assert(@zipFile.file.stat("dir1").executable?) end def test_executable_real? assert(! @zipFile.file.executable_real?("noSuchFile")) assert(! @zipFile.file.executable_real?("file1")) assert(@zipFile.file.executable_real?("dir1")) assert(! @zipFile.file.stat("file1").executable_real?) assert(@zipFile.file.stat("dir1").executable_real?) end def test_owned? assert_true_if_entry_exists(:owned?) end def test_grpowned? assert_true_if_entry_exists(:grpowned?) end def test_setgid? assert_always_false(:setgid?) end def test_setuid? assert_always_false(:setgid?) end def test_sticky? assert_always_false(:sticky?) end def test_readlink assert_raise(NotImplementedError) { @zipFile.file.readlink("someString") } end def test_stat s = @zipFile.file.stat("file1") assert(s.kind_of?(File::Stat)) # It pretends assert_raise(Errno::ENOENT, "No such file or directory - noSuchFile") { @zipFile.file.stat("noSuchFile") } end def test_lstat assert(@zipFile.file.lstat("file1").file?) end def test_pipe assert_raise(NotImplementedError) { @zipFile.file.pipe } end def test_foreach ZipFile.open("#{GEN_DIR}/zipWithDir.zip") do |zf| ref = [] File.foreach("#{SRC_DIR}/file1.txt") { |e| ref << e } index = 0 zf.file.foreach("#{SRC_DIR}/file1.txt") do |l| #Ruby replaces \n with \r\n automatically on windows newline = Zip::RUNNING_ON_WINDOWS ? l.gsub(/\r\n/, "\n") : l assert_equal(ref[index], newline) index = index.next end assert_equal(ref.size, index) end ZipFile.open("#{GEN_DIR}/zipWithDir.zip") do |zf| ref = [] File.foreach("#{SRC_DIR}/file1.txt", " ") { |e| ref << e } index = 0 zf.file.foreach("#{SRC_DIR}/file1.txt", " ") do |l| #Ruby replaces \n with \r\n automatically on windows newline = Zip::RUNNING_ON_WINDOWS ? l.gsub(/\r\n/, "\n") : l assert_equal(ref[index], newline) index = index.next end assert_equal(ref.size, index) end end def test_glob ZipFile.open("#{SRC_DIR}/globTest.zip") do |zf| { 'globTest/foo.txt' => ['globTest/foo.txt'], '*/foo.txt' => ['globTest/foo.txt'], '**/foo.txt' => ['globTest/foo.txt','globTest/foo/bar/baz/foo.txt'], '*/foo/**/*.txt' => ['globTest/foo/bar/baz/foo.txt'] }.each do |spec,expected_results| results = zf.glob(spec) assert results.all?{|entry| entry.is_a? ZipEntry } result_strings = results.map(&:to_s) missing_matches = expected_results - result_strings extra_matches = result_strings - expected_results assert extra_matches.empty?, %Q{spec #{spec.inspect} has extra results #{extra_matches.inspect}} assert missing_matches.empty?, %Q{spec #{spec.inspect} missing results #{missing_matches.inspect}} end end ZipFile.open("#{SRC_DIR}/globTest.zip") do |zf| results = [] zf.glob('**/foo.txt') do |match| results << "<#{match.class.name}: #{match.to_s}>" end assert (not results.empty?), 'block not run, or run out of context' assert_equal 2, results.size assert_operator results, :include?, '' assert_operator results, :include?, '' end end def test_popen if Zip::RUNNING_ON_WINDOWS #This is pretty much projectile vomit but it allows the test to be #run on windows also system_dir = File.popen('dir') { |f| f.read }.gsub(/Dir\(s\).*$/, '') zipfile_dir = @zipFile.file.popen('dir') { |f| f.read }.gsub(/Dir\(s\).*$/, '') assert_equal(system_dir, zipfile_dir) else assert_equal(File.popen('ls') { |f| f.read }, @zipFile.file.popen('ls') { |f| f.read }) end end # Can be added later # def test_select # fail "implement test" # end def test_readlines ZipFile.open("#{GEN_DIR}/zipWithDir.zip") do |zf| orig_file = File.readlines("#{SRC_DIR}/file1.txt") zip_file = zf.file.readlines("#{SRC_DIR}/file1.txt") #Ruby replaces \n with \r\n automatically on windows zip_file.each { |l| l.gsub!(/\r\n/, "\n") } if Zip::RUNNING_ON_WINDOWS assert_equal(orig_file, zip_file) end end def test_read ZipFile.open("#{GEN_DIR}/zipWithDir.zip") do |zf| orig_file = File.read("#{SRC_DIR}/file1.txt") #Ruby replaces \n with \r\n automatically on windows zip_file = Zip::RUNNING_ON_WINDOWS ? \ zf.file.read("#{SRC_DIR}/file1.txt").gsub(/\r\n/, "\n") : zf.file.read("#{SRC_DIR}/file1.txt") assert_equal(orig_file, zip_file) end end end class ZipFsFileStatTest < Test::Unit::TestCase def setup @zipFile = ZipFile.new("#{SRC_DIR}/zipWithDirs.zip") end def teardown @zipFile.close if @zipFile end def test_blocks assert_equal(nil, @zipFile.file.stat("file1").blocks) end def test_ino assert_equal(0, @zipFile.file.stat("file1").ino) end def test_uid assert_equal(0, @zipFile.file.stat("file1").uid) end def test_gid assert_equal(0, @zipFile.file.stat("file1").gid) end def test_ftype assert_equal("file", @zipFile.file.stat("file1").ftype) assert_equal("directory", @zipFile.file.stat("dir1").ftype) end def test_mode assert_equal(0600, @zipFile.file.stat("file1").mode & 0777) assert_equal(0600, @zipFile.file.stat("file1").mode & 0777) assert_equal(0755, @zipFile.file.stat("dir1").mode & 0777) assert_equal(0755, @zipFile.file.stat("dir1").mode & 0777) end def test_dev assert_equal(0, @zipFile.file.stat("file1").dev) end def test_rdev assert_equal(0, @zipFile.file.stat("file1").rdev) end def test_rdev_major assert_equal(0, @zipFile.file.stat("file1").rdev_major) end def test_rdev_minor assert_equal(0, @zipFile.file.stat("file1").rdev_minor) end def test_nlink assert_equal(1, @zipFile.file.stat("file1").nlink) end def test_blksize assert_nil(@zipFile.file.stat("file1").blksize) end end class ZipFsFileMutatingTest < Test::Unit::TestCase TEST_ZIP = "#{TRG_DIR}/zipWithDirs_copy.zip" def setup FileUtils.cp("#{SRC_DIR}/zipWithDirs.zip", TEST_ZIP) end def teardown end def test_delete do_test_delete_or_unlink(:delete) end def test_unlink do_test_delete_or_unlink(:unlink) end def test_open_write ZipFile.open(TEST_ZIP) { |zf| zf.file.open("test_open_write_entry", "w") { |f| f.write "This is what I'm writing" } assert_equal("This is what I'm writing", zf.file.read("test_open_write_entry")) # Test with existing entry zf.file.open("file1", "wb") { #also check that 'b' option is ignored |f| f.write "This is what I'm writing too" } assert_equal("This is what I'm writing too", zf.file.read("file1")) } end def test_rename ZipFile.open(TEST_ZIP) { |zf| assert_raise(Errno::ENOENT, "") { zf.file.rename("NoSuchFile", "bimse") } zf.file.rename("file1", "newNameForFile1") } ZipFile.open(TEST_ZIP) { |zf| assert(! zf.file.exists?("file1")) assert(zf.file.exists?("newNameForFile1")) } end def test_chmod ZipFile.open(TEST_ZIP) { |zf| zf.file.chmod(0765, "file1") } ZipFile.open(TEST_ZIP) { |zf| assert_equal(0100765, zf.file.stat("file1").mode) } end def do_test_delete_or_unlink(symbol) ZipFile.open(TEST_ZIP) { |zf| assert(zf.file.exists?("dir2/dir21/dir221/file2221")) zf.file.send(symbol, "dir2/dir21/dir221/file2221") assert(! zf.file.exists?("dir2/dir21/dir221/file2221")) assert(zf.file.exists?("dir1/file11")) assert(zf.file.exists?("dir1/file12")) zf.file.send(symbol, "dir1/file11", "dir1/file12") assert(! zf.file.exists?("dir1/file11")) assert(! zf.file.exists?("dir1/file12")) assert_raise(Errno::ENOENT) { zf.file.send(symbol, "noSuchFile") } assert_raise(Errno::EISDIR) { zf.file.send(symbol, "dir1/dir11") } assert_raise(Errno::EISDIR) { zf.file.send(symbol, "dir1/dir11/") } } ZipFile.open(TEST_ZIP) { |zf| assert(! zf.file.exists?("dir2/dir21/dir221/file2221")) assert(! zf.file.exists?("dir1/file11")) assert(! zf.file.exists?("dir1/file12")) assert(zf.file.exists?("dir1/dir11")) assert(zf.file.exists?("dir1/dir11/")) } end end class ZipFsDirectoryTest < Test::Unit::TestCase TEST_ZIP = "#{TRG_DIR}/zipWithDirs_copy.zip" def setup FileUtils.cp("#{SRC_DIR}/zipWithDirs.zip", TEST_ZIP) end def test_delete ZipFile.open(TEST_ZIP) { |zf| assert_raise(Errno::ENOENT, "No such file or directory - NoSuchFile.txt") { zf.dir.delete("NoSuchFile.txt") } assert_raise(Errno::EINVAL, "Invalid argument - file1") { zf.dir.delete("file1") } assert(zf.file.exists?("dir1")) zf.dir.delete("dir1") assert(! zf.file.exists?("dir1")) } end def test_mkdir ZipFile.open(TEST_ZIP) { |zf| assert_raise(Errno::EEXIST, "File exists - dir1") { zf.dir.mkdir("file1") } assert_raise(Errno::EEXIST, "File exists - dir1") { zf.dir.mkdir("dir1") } assert(!zf.file.exists?("newDir")) zf.dir.mkdir("newDir") assert(zf.file.directory?("newDir")) assert(!zf.file.exists?("newDir2")) zf.dir.mkdir("newDir2", 3485) assert(zf.file.directory?("newDir2")) } end def test_pwd_chdir_entries ZipFile.open(TEST_ZIP) { |zf| assert_equal("/", zf.dir.pwd) assert_raise(Errno::ENOENT, "No such file or directory - no such dir") { zf.dir.chdir "no such dir" } assert_raise(Errno::EINVAL, "Invalid argument - file1") { zf.dir.chdir "file1" } assert_equal(["dir1", "dir2", "file1"].sort, zf.dir.entries(".").sort) zf.dir.chdir "dir1" assert_equal("/dir1", zf.dir.pwd) assert_equal(["dir11", "file11", "file12"], zf.dir.entries(".").sort) zf.dir.chdir "../dir2/dir21" assert_equal("/dir2/dir21", zf.dir.pwd) assert_equal(["dir221"].sort, zf.dir.entries(".").sort) } end def test_foreach ZipFile.open(TEST_ZIP) { |zf| blockCalled = false assert_raise(Errno::ENOENT, "No such file or directory - noSuchDir") { zf.dir.foreach("noSuchDir") { |e| blockCalled = true } } assert(! blockCalled) assert_raise(Errno::ENOTDIR, "Not a directory - file1") { zf.dir.foreach("file1") { |e| blockCalled = true } } assert(! blockCalled) entries = [] zf.dir.foreach(".") { |e| entries << e } assert_equal(["dir1", "dir2", "file1"].sort, entries.sort) entries = [] zf.dir.foreach("dir1") { |e| entries << e } assert_equal(["dir11", "file11", "file12"], entries.sort) } end def test_chroot ZipFile.open(TEST_ZIP) { |zf| assert_raise(NotImplementedError) { zf.dir.chroot } } end # Globbing not supported yet #def test_glob # # test alias []-operator too # fail "implement test" #end def test_open_new ZipFile.open(TEST_ZIP) { |zf| assert_raise(Errno::ENOTDIR, "Not a directory - file1") { zf.dir.new("file1") } assert_raise(Errno::ENOENT, "No such file or directory - noSuchFile") { zf.dir.new("noSuchFile") } d = zf.dir.new(".") assert_equal(["file1", "dir1", "dir2"].sort, d.entries.sort) d.close zf.dir.open("dir1") { |dir| assert_equal(["dir11", "file11", "file12"].sort, dir.entries.sort) } } end end class ZipFsDirIteratorTest < Test::Unit::TestCase FILENAME_ARRAY = [ "f1", "f2", "f3", "f4", "f5", "f6" ] def setup @dirIt = ZipFileSystem::ZipFsDirIterator.new(FILENAME_ARRAY) end def test_close @dirIt.close assert_raise(IOError, "closed directory") { @dirIt.each { |e| p e } } assert_raise(IOError, "closed directory") { @dirIt.read } assert_raise(IOError, "closed directory") { @dirIt.rewind } assert_raise(IOError, "closed directory") { @dirIt.seek(0) } assert_raise(IOError, "closed directory") { @dirIt.tell } end def test_each # Tested through Enumerable.entries assert_equal(FILENAME_ARRAY, @dirIt.entries) end def test_read FILENAME_ARRAY.size.times { |i| assert_equal(FILENAME_ARRAY[i], @dirIt.read) } end def test_rewind @dirIt.read @dirIt.read assert_equal(FILENAME_ARRAY[2], @dirIt.read) @dirIt.rewind assert_equal(FILENAME_ARRAY[0], @dirIt.read) end def test_tell_seek @dirIt.read @dirIt.read pos = @dirIt.tell valAtPos = @dirIt.read @dirIt.read @dirIt.seek(pos) assert_equal(valAtPos, @dirIt.read) end end # Copyright (C) 2002, 2003 Thomas Sondergaard # rubyzip is free software; you can redistribute it and/or # modify it under the terms of the ruby license. zip-zip-0.3/test/0.9.9/ziptest.rb000066400000000000000000001446401232145563700164620ustar00rootroot00000000000000require '0.9.9/test_helper' include Zip class ZipEntryTest < Test::Unit::TestCase TEST_ZIPFILE = "someZipFile.zip" TEST_COMMENT = "a comment" TEST_COMPRESSED_SIZE = 1234 TEST_CRC = 325324 TEST_EXTRA = "Some data here" TEST_COMPRESSIONMETHOD = ZipEntry::DEFLATED TEST_NAME = "entry name" TEST_SIZE = 8432 TEST_ISDIRECTORY = false TEST_TIME = Time.now def test_constructorAndGetters entry = ZipEntry.new(TEST_ZIPFILE, TEST_NAME, TEST_COMMENT, TEST_EXTRA, TEST_COMPRESSED_SIZE, TEST_CRC, TEST_COMPRESSIONMETHOD, TEST_SIZE, TEST_TIME) assert_equal(TEST_COMMENT, entry.comment) assert_equal(TEST_COMPRESSED_SIZE, entry.compressed_size) assert_equal(TEST_CRC, entry.crc) assert_instance_of(Zip::ZipExtraField, entry.extra) assert_equal(TEST_COMPRESSIONMETHOD, entry.compression_method) assert_equal(TEST_NAME, entry.name) assert_equal(TEST_SIZE, entry.size) assert_equal(TEST_TIME, entry.time) assert_equal(TEST_ISDIRECTORY, entry.is_directory) end def test_is_directoryAndIsFile assert(ZipEntry.new(TEST_ZIPFILE, "hello").file?) assert(! ZipEntry.new(TEST_ZIPFILE, "hello").directory?) assert(ZipEntry.new(TEST_ZIPFILE, "dir/hello").file?) assert(! ZipEntry.new(TEST_ZIPFILE, "dir/hello").directory?) assert(ZipEntry.new(TEST_ZIPFILE, "hello/").directory?) assert(! ZipEntry.new(TEST_ZIPFILE, "hello/").file?) assert(ZipEntry.new(TEST_ZIPFILE, "dir/hello/").directory?) assert(! ZipEntry.new(TEST_ZIPFILE, "dir/hello/").file?) end def test_equality entry1 = ZipEntry.new("file.zip", "name", "isNotCompared", "something extra", 123, 1234, ZipEntry::DEFLATED, 10000) entry2 = ZipEntry.new("file.zip", "name", "isNotComparedXXX", "something extra", 123, 1234, ZipEntry::DEFLATED, 10000) entry3 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extra", 123, 1234, ZipEntry::DEFLATED, 10000) entry4 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extraXX", 123, 1234, ZipEntry::DEFLATED, 10000) entry5 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extraXX", 12, 1234, ZipEntry::DEFLATED, 10000) entry6 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extraXX", 12, 123, ZipEntry::DEFLATED, 10000) entry7 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extraXX", 12, 123, ZipEntry::STORED, 10000) entry8 = ZipEntry.new("file.zip", "name2", "isNotComparedXXX", "something extraXX", 12, 123, ZipEntry::STORED, 100000) assert_equal(entry1, entry1) assert_equal(entry1, entry2) assert(entry2 != entry3) assert(entry3 != entry4) assert(entry4 != entry5) assert(entry5 != entry6) assert(entry6 != entry7) assert(entry7 != entry8) assert(entry7 != "hello") assert(entry7 != 12) end def test_compare assert_equal(0, (ZipEntry.new("zf.zip", "a") <=> ZipEntry.new("zf.zip", "a"))) assert_equal(1, (ZipEntry.new("zf.zip", "b") <=> ZipEntry.new("zf.zip", "a"))) assert_equal(-1, (ZipEntry.new("zf.zip", "a") <=> ZipEntry.new("zf.zip", "b"))) entries = [ ZipEntry.new("zf.zip", "5"), ZipEntry.new("zf.zip", "1"), ZipEntry.new("zf.zip", "3"), ZipEntry.new("zf.zip", "4"), ZipEntry.new("zf.zip", "0"), ZipEntry.new("zf.zip", "2") ] entries.sort! assert_equal("0", entries[0].to_s) assert_equal("1", entries[1].to_s) assert_equal("2", entries[2].to_s) assert_equal("3", entries[3].to_s) assert_equal("4", entries[4].to_s) assert_equal("5", entries[5].to_s) end def test_parentAsString entry1 = ZipEntry.new("zf.zip", "aa") entry2 = ZipEntry.new("zf.zip", "aa/") entry3 = ZipEntry.new("zf.zip", "aa/bb") entry4 = ZipEntry.new("zf.zip", "aa/bb/") entry5 = ZipEntry.new("zf.zip", "aa/bb/cc") entry6 = ZipEntry.new("zf.zip", "aa/bb/cc/") assert_equal(nil, entry1.parent_as_string) assert_equal(nil, entry2.parent_as_string) assert_equal("aa/", entry3.parent_as_string) assert_equal("aa/", entry4.parent_as_string) assert_equal("aa/bb/", entry5.parent_as_string) assert_equal("aa/bb/", entry6.parent_as_string) end def test_entry_name_cannot_start_with_slash assert_raise(ZipEntryNameError) { ZipEntry.new("zf.zip", "/hej/der") } end end module IOizeString attr_reader :tell def read(count = nil) @tell ||= 0 count = size unless count retVal = slice(@tell, count) @tell += count return retVal end def seek(index, offset) @tell ||= 0 case offset when IO::SEEK_END newPos = size + index when IO::SEEK_SET newPos = index when IO::SEEK_CUR newPos = @tell + index else raise "Error in test method IOizeString::seek" end if (newPos < 0 || newPos >= size) raise Errno::EINVAL else @tell=newPos end end def reset @tell = 0 end end class ZipLocalEntryTest < Test::Unit::TestCase def test_read_local_entryHeaderOfFirstTestZipEntry File.open(TestZipFile::TEST_ZIP3.zip_name, "rb") { |file| entry = ZipEntry.read_local_entry(file) assert_equal("", entry.comment) # Differs from windows and unix because of CR LF # assert_equal(480, entry.compressed_size) # assert_equal(0x2a27930f, entry.crc) # extra field is 21 bytes long # probably contains some unix attrutes or something # disabled: assert_equal(nil, entry.extra) assert_equal(ZipEntry::DEFLATED, entry.compression_method) assert_equal(TestZipFile::TEST_ZIP3.entry_names[0], entry.name) assert_equal(File.size(TestZipFile::TEST_ZIP3.entry_names[0]), entry.size) assert(! entry.is_directory) } end def test_readDateTime File.open("#{SRC_DIR}/rubycode.zip", "rb") { |file| entry = ZipEntry.read_local_entry(file) assert_equal("zippedruby1.rb", entry.name) assert_equal(DOSTime.at(1019261638), entry.time) } end def test_read_local_entryFromNonZipFile File.open("#{SRC_DIR}/file2.txt") { |file| assert_equal(nil, ZipEntry.read_local_entry(file)) } end def test_read_local_entryFromTruncatedZipFile zipFragment="" File.open(TestZipFile::TEST_ZIP2.zip_name) { |f| zipFragment = f.read(12) } # local header is at least 30 bytes zipFragment.extend(IOizeString).reset entry = ZipEntry.new entry.read_local_entry(zipFragment) fail "ZipError expected" rescue ZipError end def test_writeEntry entry = ZipEntry.new("file.zip", "entryName", "my little comment", "thisIsSomeExtraInformation", 100, 987654, ZipEntry::DEFLATED, 400) write_to_file("#{TRG_DIR}/localEntryHeader.bin", "#{TRG_DIR}/centralEntryHeader.bin", entry) entryReadLocal, entryReadCentral = read_from_file("#{TRG_DIR}/localEntryHeader.bin", "#{TRG_DIR}/centralEntryHeader.bin") compare_local_entry_headers(entry, entryReadLocal) compare_c_dir_entry_headers(entry, entryReadCentral) end private def compare_local_entry_headers(entry1, entry2) assert_equal(entry1.compressed_size , entry2.compressed_size) assert_equal(entry1.crc , entry2.crc) assert_equal(entry1.extra , entry2.extra) assert_equal(entry1.compression_method, entry2.compression_method) assert_equal(entry1.name , entry2.name) assert_equal(entry1.size , entry2.size) assert_equal(entry1.localHeaderOffset, entry2.localHeaderOffset) end def compare_c_dir_entry_headers(entry1, entry2) compare_local_entry_headers(entry1, entry2) assert_equal(entry1.comment, entry2.comment) end def write_to_file(localFileName, centralFileName, entry) File.open(localFileName, "wb") { |f| entry.write_local_entry(f) } File.open(centralFileName, "wb") { |f| entry.write_c_dir_entry(f) } end def read_from_file(localFileName, centralFileName) localEntry = nil cdirEntry = nil File.open(localFileName, "rb") { |f| localEntry = ZipEntry.read_local_entry(f) } File.open(centralFileName, "rb") { |f| cdirEntry = ZipEntry.read_c_dir_entry(f) } return [localEntry, cdirEntry] end end module DecompressorTests # expects @refText, @refLines and @decompressor TEST_FILE="#{SRC_DIR}/file1.txt" def setup @refText="" File.open(TEST_FILE) { |f| @refText = f.read } @refLines = @refText.split($/) end def test_readEverything assert_equal(@refText, @decompressor.sysread) end def test_readInChunks chunkSize = 5 while (decompressedChunk = @decompressor.sysread(chunkSize)) assert_equal(@refText.slice!(0, chunkSize), decompressedChunk) end assert_equal(0, @refText.size) end def test_mixingReadsAndProduceInput # Just some preconditions to make sure we have enough data for this test assert(@refText.length > 1000) assert(@refLines.length > 40) assert_equal(@refText[0...100], @decompressor.sysread(100)) assert(! @decompressor.input_finished?) buf = @decompressor.produce_input assert_equal(@refText[100...(100+buf.length)], buf) end end class InflaterTest < Test::Unit::TestCase include DecompressorTests def setup super @file = File.new("#{SRC_DIR}/file1.txt.deflatedData", "rb") @decompressor = Inflater.new(@file) end def teardown @file.close end end class PassThruDecompressorTest < Test::Unit::TestCase include DecompressorTests def setup super @file = File.new(TEST_FILE) @decompressor = PassThruDecompressor.new(@file, File.size(TEST_FILE)) end def teardown @file.close end end module AssertEntry def assert_next_entry(filename, zis) assert_entry(filename, zis, zis.get_next_entry.name) end def assert_entry(filename, zis, entryName) assert_equal(filename, entryName) assert_entryContentsForStream(filename, zis, entryName) end def assert_entryContentsForStream(filename, zis, entryName) File.open(filename, "rb") { |file| expected = file.read actual = zis.read if (expected != actual) if ((expected && actual) && (expected.length > 400 || actual.length > 400)) zipEntryFilename=entryName+".zipEntry" File.open(zipEntryFilename, "wb") { |file| file << actual } fail("File '#{filename}' is different from '#{zipEntryFilename}'") else assert_equal(expected, actual) end end } end def AssertEntry.assert_contents(filename, aString) fileContents = "" File.open(filename, "rb") { |f| fileContents = f.read } if (fileContents != aString) if (fileContents.length > 400 || aString.length > 400) stringFile = filename + ".other" File.open(stringFile, "wb") { |f| f << aString } fail("File '#{filename}' is different from contents of string stored in '#{stringFile}'") else assert_equal(fileContents, aString) end end end def assert_stream_contents(zis, testZipFile) assert(zis != nil) testZipFile.entry_names.each { |entryName| assert_next_entry(entryName, zis) } assert_equal(nil, zis.get_next_entry) end def assert_test_zip_contents(testZipFile) ZipInputStream.open(testZipFile.zip_name) { |zis| assert_stream_contents(zis, testZipFile) } end def assert_entryContents(zipFile, entryName, filename = entryName.to_s) zis = zipFile.get_input_stream(entryName) assert_entryContentsForStream(filename, zis, entryName) ensure zis.close if zis end end class ZipInputStreamTest < Test::Unit::TestCase include AssertEntry def test_new zis = ZipInputStream.new(TestZipFile::TEST_ZIP2.zip_name) assert_stream_contents(zis, TestZipFile::TEST_ZIP2) assert_equal(true, zis.eof?) zis.close end def test_openWithBlock ZipInputStream.open(TestZipFile::TEST_ZIP2.zip_name) { |zis| assert_stream_contents(zis, TestZipFile::TEST_ZIP2) assert_equal(true, zis.eof?) } end def test_openWithoutBlock zis = ZipInputStream.open_buffer(File.new(TestZipFile::TEST_ZIP2.zip_name, "rb")) assert_stream_contents(zis, TestZipFile::TEST_ZIP2) end def test_openBufferWithBlock ZipInputStream.open_buffer(File.new(TestZipFile::TEST_ZIP2.zip_name, "rb")) { |zis| assert_stream_contents(zis, TestZipFile::TEST_ZIP2) assert_equal(true, zis.eof?) } end def test_openBufferWithoutBlock zis = ZipInputStream.open(TestZipFile::TEST_ZIP2.zip_name) assert_stream_contents(zis, TestZipFile::TEST_ZIP2) end def test_incompleteReads ZipInputStream.open(TestZipFile::TEST_ZIP2.zip_name) { |zis| entry = zis.get_next_entry # longAscii.txt assert_equal(false, zis.eof?) assert_equal(TestZipFile::TEST_ZIP2.entry_names[0], entry.name) assert zis.gets.length > 0 assert_equal(false, zis.eof?) entry = zis.get_next_entry # empty.txt assert_equal(TestZipFile::TEST_ZIP2.entry_names[1], entry.name) assert_equal(0, entry.size) assert_equal(nil, zis.gets) assert_equal(true, zis.eof?) entry = zis.get_next_entry # empty_chmod640.txt assert_equal(TestZipFile::TEST_ZIP2.entry_names[2], entry.name) assert_equal(0, entry.size) assert_equal(nil, zis.gets) assert_equal(true, zis.eof?) entry = zis.get_next_entry # short.txt assert_equal(TestZipFile::TEST_ZIP2.entry_names[3], entry.name) assert zis.gets.length > 0 entry = zis.get_next_entry # longBinary.bin assert_equal(TestZipFile::TEST_ZIP2.entry_names[4], entry.name) assert zis.gets.length > 0 } end def test_rewind ZipInputStream.open(TestZipFile::TEST_ZIP2.zip_name) { |zis| e = zis.get_next_entry assert_equal(TestZipFile::TEST_ZIP2.entry_names[0], e.name) # Do a little reading buf = "" buf << zis.read(100) buf << (zis.gets || "") buf << (zis.gets || "") assert_equal(false, zis.eof?) zis.rewind buf2 = "" buf2 << zis.read(100) buf2 << (zis.gets || "") buf2 << (zis.gets || "") assert_equal(buf, buf2) zis.rewind assert_equal(false, zis.eof?) assert_entry(e.name, zis, e.name) } end def test_mix_read_and_gets ZipInputStream.open(TestZipFile::TEST_ZIP2.zip_name) { |zis| e = zis.get_next_entry assert_equal("#!/usr/bin/env ruby", zis.gets.chomp) assert_equal(false, zis.eof?) assert_equal("", zis.gets.chomp) assert_equal(false, zis.eof?) assert_equal("$VERBOSE =", zis.read(10)) assert_equal(false, zis.eof?) } end end module CrcTest class TestOutputStream include IOExtras::AbstractOutputStream attr_accessor :buffer def initialize @buffer = "" end def << (data) @buffer << data self end end def run_crc_test(compressorClass) str = "Here's a nice little text to compute the crc for! Ho hum, it is nice nice nice nice indeed." fakeOut = TestOutputStream.new deflater = compressorClass.new(fakeOut) deflater << str assert_equal(0x919920fc, deflater.crc) end end class PassThruCompressorTest < Test::Unit::TestCase include CrcTest def test_size File.open("#{TRG_DIR}/dummy.txt", "wb") { |file| compressor = PassThruCompressor.new(file) assert_equal(0, compressor.size) t1 = "hello world" t2 = "" t3 = "bingo" compressor << t1 assert_equal(compressor.size, t1.size) compressor << t2 assert_equal(compressor.size, t1.size + t2.size) compressor << t3 assert_equal(compressor.size, t1.size + t2.size + t3.size) } end def test_crc run_crc_test(PassThruCompressor) end end class DeflaterTest < Test::Unit::TestCase include CrcTest def test_outputOperator txt = load_file("#{SRC_DIR}/file2.txt") deflate(txt, "#{TRG_DIR}/deflatertest.bin") inflatedTxt = inflate("#{TRG_DIR}/deflatertest.bin") assert_equal(txt, inflatedTxt) end private def load_file(fileName) txt = nil File.open(fileName, "rb") { |f| txt = f.read } end def deflate(data, fileName) File.open(fileName, "wb") { |file| deflater = Deflater.new(file) deflater << data deflater.finish assert_equal(deflater.size, data.size) file << "trailing data for zlib with -MAX_WBITS" } end def inflate(fileName) txt = nil File.open(fileName, "rb") { |file| inflater = Inflater.new(file) txt = inflater.sysread } end def test_crc run_crc_test(Deflater) end end class ZipOutputStreamTest < Test::Unit::TestCase include AssertEntry TEST_ZIP = TestZipFile::TEST_ZIP2.clone TEST_ZIP.zip_name = "#{TRG_DIR}/output.zip" def test_new zos = ZipOutputStream.new(TEST_ZIP.zip_name) zos.comment = TEST_ZIP.comment write_test_zip(zos) zos.close assert_test_zip_contents(TEST_ZIP) end def test_open ZipOutputStream.open(TEST_ZIP.zip_name) do |zos| zos.comment = TEST_ZIP.comment write_test_zip(zos) end assert_test_zip_contents(TEST_ZIP) end def test_write_buffer buffer = ZipOutputStream.write_buffer do |zos| zos.comment = TEST_ZIP.comment write_test_zip(zos) end File.open(TEST_ZIP.zip_name, 'wb') { |f| f.write buffer.string } assert_test_zip_contents(TEST_ZIP) end def test_writingToClosedStream assert_i_o_error_in_closed_stream { |zos| zos << "hello world" } assert_i_o_error_in_closed_stream { |zos| zos.puts "hello world" } assert_i_o_error_in_closed_stream { |zos| zos.write "hello world" } end def test_cannotOpenFile name = TestFiles::EMPTY_TEST_DIR begin zos = ZipOutputStream.open(name) rescue Exception assert($!.kind_of?(Errno::EISDIR) || # Linux $!.kind_of?(Errno::EEXIST) || # Windows/cygwin $!.kind_of?(Errno::EACCES), # Windows "Expected Errno::EISDIR (or on win/cygwin: Errno::EEXIST), but was: #{$!.class}") end end def test_put_next_entry stored_text = "hello world in stored text" entry_name = "file1" comment = "my comment" ZipOutputStream.open(TEST_ZIP.zip_name) do |zos| zos.put_next_entry(entry_name, comment, nil, ZipEntry::STORED) zos << stored_text end assert(File.read(TEST_ZIP.zip_name)[stored_text]) ZipFile.open(TEST_ZIP.zip_name) do |zf| assert_equal(stored_text, zf.read(entry_name)) end end def test_put_next_entry_using_zip_entry_creates_entries_with_correct_timestamps file = File.open("#{SRC_DIR}/file2.txt", "rb") ZipOutputStream.open(TEST_ZIP.zip_name) do |zos| zip_entry = Zip::ZipEntry.new(zos, file.path, "", "", 0, 0, Zip::ZipEntry::DEFLATED, 0, DOSTime.at(file.mtime)) zos.put_next_entry(zip_entry) zos << file.read end Zip::ZipInputStream::open(TEST_ZIP.zip_name) do |io| while (entry = io.get_next_entry) assert(DOSTime.at(file.mtime).dos_equals(DOSTime.at(entry.mtime))) # Compare DOS Times, since they are stored with two seconds accuracy end end end def assert_i_o_error_in_closed_stream assert_raise(IOError) { zos = ZipOutputStream.new("#{TRG_DIR}/test_putOnClosedStream.zip") zos.close yield zos } end def write_test_zip(zos) TEST_ZIP.entry_names.each do |entryName| zos.put_next_entry(entryName) File.open(entryName, "rb") { |f| zos.write(f.read) } end end end module Enumerable def compare_enumerables(otherEnumerable) otherAsArray = otherEnumerable.to_a index=0 each_with_index { |element, index| return false unless yield(element, otherAsArray[index]) } return self.size == otherAsArray.size end end class ZipCentralDirectoryEntryTest < Test::Unit::TestCase def test_read_from_stream File.open("#{SRC_DIR}/testDirectory.bin", "rb") { |file| entry = ZipEntry.read_c_dir_entry(file) assert_equal("longAscii.txt", entry.name) assert_equal(ZipEntry::DEFLATED, entry.compression_method) assert_equal(106490, entry.size) assert_equal(3784, entry.compressed_size) assert_equal(0xfcd1799c, entry.crc) assert_equal("", entry.comment) entry = ZipEntry.read_c_dir_entry(file) assert_equal("empty.txt", entry.name) assert_equal(ZipEntry::STORED, entry.compression_method) assert_equal(0, entry.size) assert_equal(0, entry.compressed_size) assert_equal(0x0, entry.crc) assert_equal("", entry.comment) entry = ZipEntry.read_c_dir_entry(file) assert_equal("short.txt", entry.name) assert_equal(ZipEntry::STORED, entry.compression_method) assert_equal(6, entry.size) assert_equal(6, entry.compressed_size) assert_equal(0xbb76fe69, entry.crc) assert_equal("", entry.comment) entry = ZipEntry.read_c_dir_entry(file) assert_equal("longBinary.bin", entry.name) assert_equal(ZipEntry::DEFLATED, entry.compression_method) assert_equal(1000024, entry.size) assert_equal(70847, entry.compressed_size) assert_equal(0x10da7d59, entry.crc) assert_equal("", entry.comment) entry = ZipEntry.read_c_dir_entry(file) assert_equal(nil, entry) # Fields that are not check by this test: # version made by 2 bytes # version needed to extract 2 bytes # general purpose bit flag 2 bytes # last mod file time 2 bytes # last mod file date 2 bytes # compressed size 4 bytes # uncompressed size 4 bytes # disk number start 2 bytes # internal file attributes 2 bytes # external file attributes 4 bytes # relative offset of local header 4 bytes # file name (variable size) # extra field (variable size) # file comment (variable size) } end def test_ReadEntryFromTruncatedZipFile fragment="" File.open("#{SRC_DIR}/testDirectory.bin") { |f| fragment = f.read(12) } # cdir entry header is at least 46 bytes fragment.extend(IOizeString) entry = ZipEntry.new entry.read_c_dir_entry(fragment) fail "ZipError expected" rescue ZipError end end class ZipEntrySetTest < Test::Unit::TestCase ZIP_ENTRIES = [ ZipEntry.new("zipfile.zip", "name1", "comment1"), ZipEntry.new("zipfile.zip", "name2", "comment1"), ZipEntry.new("zipfile.zip", "name3", "comment1"), ZipEntry.new("zipfile.zip", "name4", "comment1"), ZipEntry.new("zipfile.zip", "name5", "comment1"), ZipEntry.new("zipfile.zip", "name6", "comment1") ] def setup @zipEntrySet = ZipEntrySet.new(ZIP_ENTRIES) end def test_include assert(@zipEntrySet.include?(ZIP_ENTRIES.first)) assert(! @zipEntrySet.include?(ZipEntry.new("different.zip", "different", "aComment"))) end def test_size assert_equal(ZIP_ENTRIES.size, @zipEntrySet.size) assert_equal(ZIP_ENTRIES.size, @zipEntrySet.length) @zipEntrySet << ZipEntry.new("a", "b", "c") assert_equal(ZIP_ENTRIES.size + 1, @zipEntrySet.length) end def test_add zes = ZipEntrySet.new entry1 = ZipEntry.new("zf.zip", "name1") entry2 = ZipEntry.new("zf.zip", "name2") zes << entry1 assert(zes.include?(entry1)) zes.push(entry2) assert(zes.include?(entry2)) end def test_delete assert_equal(ZIP_ENTRIES.size, @zipEntrySet.size) entry = @zipEntrySet.delete(ZIP_ENTRIES.first) assert_equal(ZIP_ENTRIES.size - 1, @zipEntrySet.size) assert_equal(ZIP_ENTRIES.first, entry) entry = @zipEntrySet.delete(ZIP_ENTRIES.first) assert_equal(ZIP_ENTRIES.size - 1, @zipEntrySet.size) assert_nil(entry) end def test_each # Tested indirectly via each_with_index count = 0 @zipEntrySet.each_with_index { |entry, index| assert(ZIP_ENTRIES.include?(entry)) count = count.succ } assert_equal(ZIP_ENTRIES.size, count) end def test_entries assert_equal(ZIP_ENTRIES.sort, @zipEntrySet.entries.sort) end def test_compound newEntry = ZipEntry.new("zf.zip", "new entry", "new entry's comment") assert_equal(ZIP_ENTRIES.size, @zipEntrySet.size) @zipEntrySet << newEntry assert_equal(ZIP_ENTRIES.size + 1, @zipEntrySet.size) assert(@zipEntrySet.include?(newEntry)) @zipEntrySet.delete(newEntry) assert_equal(ZIP_ENTRIES.size, @zipEntrySet.size) end def test_dup copy = @zipEntrySet.dup assert_equal(@zipEntrySet, copy) # demonstrate that this is a deep copy copy.entries[0].name = "a totally different name" assert(@zipEntrySet != copy) end def test_parent entries = [ ZipEntry.new("zf.zip", "a/"), ZipEntry.new("zf.zip", "a/b/"), ZipEntry.new("zf.zip", "a/b/c/") ] entrySet = ZipEntrySet.new(entries) assert_equal(nil, entrySet.parent(entries[0])) assert_equal(entries[0], entrySet.parent(entries[1])) assert_equal(entries[1], entrySet.parent(entries[2])) end def test_glob res = @zipEntrySet.glob('name[2-4]') assert_equal(3, res.size) assert_equal(ZIP_ENTRIES[1,3].sort, res.sort) end def test_glob2 entries = [ ZipEntry.new("zf.zip", "a/"), ZipEntry.new("zf.zip", "a/b/b1"), ZipEntry.new("zf.zip", "a/b/c/"), ZipEntry.new("zf.zip", "a/b/c/c1") ] entrySet = ZipEntrySet.new(entries) assert_equal(entries[0,1], entrySet.glob("*")) # assert_equal(entries[FIXME], entrySet.glob("**")) # res = entrySet.glob('a*') # assert_equal(entries.size, res.size) # assert_equal(entrySet.map { |e| e.name }, res.map { |e| e.name }) end end class ZipCentralDirectoryTest < Test::Unit::TestCase def test_read_from_stream File.open(TestZipFile::TEST_ZIP2.zip_name, "rb") { |zipFile| cdir = ZipCentralDirectory.read_from_stream(zipFile) assert_equal(TestZipFile::TEST_ZIP2.entry_names.size, cdir.size) assert(cdir.entries.sort.compare_enumerables(TestZipFile::TEST_ZIP2.entry_names.sort) { |cdirEntry, testEntryName| cdirEntry.name == testEntryName }) assert_equal(TestZipFile::TEST_ZIP2.comment, cdir.comment) } end def test_readFromInvalidStream File.open("#{SRC_DIR}/file2.txt", "rb") { |zipFile| cdir = ZipCentralDirectory.new cdir.read_from_stream(zipFile) } fail "ZipError expected!" rescue ZipError end def test_ReadFromTruncatedZipFile fragment="" File.open("#{SRC_DIR}/testDirectory.bin", "rb") { |f| fragment = f.read } fragment.slice!(12) # removed part of first cdir entry. eocd structure still complete fragment.extend(IOizeString) entry = ZipCentralDirectory.new entry.read_from_stream(fragment) fail "ZipError expected" rescue ZipError end def test_write_to_stream entries = [ ZipEntry.new("file.zip", "flimse", "myComment", "somethingExtra"), ZipEntry.new("file.zip", "secondEntryName"), ZipEntry.new("file.zip", "lastEntry.txt", "Has a comment too") ] cdir = ZipCentralDirectory.new(entries, "my zip comment") File.open("#{TRG_DIR}/cdirtest.bin", "wb") { |f| cdir.write_to_stream(f) } cdirReadback = ZipCentralDirectory.new File.open("#{TRG_DIR}/cdirtest.bin", "rb") { |f| cdirReadback.read_from_stream(f) } assert_equal(cdir.entries.sort, cdirReadback.entries.sort) end def test_equality cdir1 = ZipCentralDirectory.new([ ZipEntry.new("file.zip", "flimse", nil, "somethingExtra"), ZipEntry.new("file.zip", "secondEntryName"), ZipEntry.new("file.zip", "lastEntry.txt") ], "my zip comment") cdir2 = ZipCentralDirectory.new([ ZipEntry.new("file.zip", "flimse", nil, "somethingExtra"), ZipEntry.new("file.zip", "secondEntryName"), ZipEntry.new("file.zip", "lastEntry.txt") ], "my zip comment") cdir3 = ZipCentralDirectory.new([ ZipEntry.new("file.zip", "flimse", nil, "somethingExtra"), ZipEntry.new("file.zip", "secondEntryName"), ZipEntry.new("file.zip", "lastEntry.txt") ], "comment?") cdir4 = ZipCentralDirectory.new([ ZipEntry.new("file.zip", "flimse", nil, "somethingExtra"), ZipEntry.new("file.zip", "lastEntry.txt") ], "comment?") assert_equal(cdir1, cdir1) assert_equal(cdir1, cdir2) assert(cdir1 != cdir3) assert(cdir2 != cdir3) assert(cdir2 != cdir3) assert(cdir3 != cdir4) assert(cdir3 != "hello") end end class BasicZipFileTest < Test::Unit::TestCase include AssertEntry def setup @zipFile = ZipFile.new(TestZipFile::TEST_ZIP2.zip_name) @testEntryNameIndex=0 end def test_entries assert_equal(TestZipFile::TEST_ZIP2.entry_names.sort, @zipFile.entries.entries.sort.map {|e| e.name} ) end def test_each count = 0 visited = {} @zipFile.each { |entry| assert(TestZipFile::TEST_ZIP2.entry_names.include?(entry.name)) assert(! visited.include?(entry.name)) visited[entry.name] = nil count = count.succ } assert_equal(TestZipFile::TEST_ZIP2.entry_names.length, count) end def test_foreach count = 0 visited = {} ZipFile.foreach(TestZipFile::TEST_ZIP2.zip_name) { |entry| assert(TestZipFile::TEST_ZIP2.entry_names.include?(entry.name)) assert(! visited.include?(entry.name)) visited[entry.name] = nil count = count.succ } assert_equal(TestZipFile::TEST_ZIP2.entry_names.length, count) end def test_get_input_stream count = 0 visited = {} @zipFile.each { |entry| assert_entry(entry.name, @zipFile.get_input_stream(entry), entry.name) assert(! visited.include?(entry.name)) visited[entry.name] = nil count = count.succ } assert_equal(TestZipFile::TEST_ZIP2.entry_names.length, count) end def test_get_input_streamBlock fileAndEntryName = @zipFile.entries.first.name @zipFile.get_input_stream(fileAndEntryName) { |zis| assert_entryContentsForStream(fileAndEntryName, zis, fileAndEntryName) } end end module CommonZipFileFixture include AssertEntry EMPTY_FILENAME = "emptyZipFile.zip" TEST_ZIP = TestZipFile::TEST_ZIP2.clone TEST_ZIP.zip_name = "#{TRG_DIR}/5entry_copy.zip" def setup File.delete(EMPTY_FILENAME) if File.exists?(EMPTY_FILENAME) FileUtils.cp(TestZipFile::TEST_ZIP2.zip_name, TEST_ZIP.zip_name) end end class ZipFileTest < Test::Unit::TestCase include CommonZipFileFixture def test_createFromScratchToBuffer comment = "a short comment" buffer = ::ZipFile.add_buffer do |zf| zf.get_output_stream("myFile") { |os| os.write "myFile contains just this" } zf.mkdir("dir1") zf.comment = comment end ::File.open(EMPTY_FILENAME, 'wb') { |file| file.write buffer.string } # Not sure if the following line was just accidentally left in, but # it's not related to the tests and breaks on windows `cp #{EMPTY_FILENAME} ~/test.zip` unless Zip::RUNNING_ON_WINDOWS zfRead = ::ZipFile.new(EMPTY_FILENAME) assert_equal(comment, zfRead.comment) assert_equal(2, zfRead.entries.length) end def test_createFromScratch comment = "a short comment" zf = ZipFile.new(EMPTY_FILENAME, ZipFile::CREATE) zf.get_output_stream("myFile") { |os| os.write "myFile contains just this" } zf.mkdir("dir1") zf.comment = comment zf.close zfRead = ZipFile.new(EMPTY_FILENAME) assert_equal(comment, zfRead.comment) assert_equal(2, zfRead.entries.length) end def test_get_output_stream entryCount = nil ZipFile.open(TEST_ZIP.zip_name) { |zf| entryCount = zf.size zf.get_output_stream('newEntry.txt') { |os| os.write "Putting stuff in newEntry.txt" } assert_equal(entryCount+1, zf.size) assert_equal("Putting stuff in newEntry.txt", zf.read("newEntry.txt")) zf.get_output_stream(zf.get_entry("#{GEN_DIR}/empty.txt")) { |os| os.write "Putting stuff in data/generated/empty.txt" } assert_equal(entryCount+1, zf.size) assert_equal("Putting stuff in data/generated/empty.txt", zf.read("#{GEN_DIR}/empty.txt")) zf.get_output_stream('entry.bin') { |os| os.write(File.open("#{GEN_DIR}/5entry.zip", 'rb').read) } } ZipFile.open(TEST_ZIP.zip_name) { |zf| assert_equal(entryCount+2, zf.size) assert_equal("Putting stuff in newEntry.txt", zf.read("newEntry.txt")) assert_equal("Putting stuff in data/generated/empty.txt", zf.read("#{GEN_DIR}/empty.txt")) assert_equal(File.open("#{GEN_DIR}/5entry.zip", 'rb').read, zf.read("entry.bin")) } end def test_add srcFile = "#{SRC_DIR}/file2.txt" entryName = "newEntryName.rb" assert(File.exists?(srcFile)) zf = ZipFile.new(EMPTY_FILENAME, ZipFile::CREATE) zf.add(entryName, srcFile) zf.close zfRead = ZipFile.new(EMPTY_FILENAME) assert_equal("", zfRead.comment) assert_equal(1, zfRead.entries.length) assert_equal(entryName, zfRead.entries.first.name) AssertEntry.assert_contents(srcFile, zfRead.get_input_stream(entryName) { |zis| zis.read }) end def test_addExistingEntryName assert_raise(ZipEntryExistsError) { ZipFile.open(TEST_ZIP.zip_name) { |zf| zf.add(zf.entries.first.name, "#{SRC_DIR}/file2.txt") } } end def test_addExistingEntryNameReplace gotCalled = false replacedEntry = nil ZipFile.open(TEST_ZIP.zip_name) { |zf| replacedEntry = zf.entries.first.name zf.add(replacedEntry, "#{SRC_DIR}/file2.txt") { gotCalled = true; true } } assert(gotCalled) ZipFile.open(TEST_ZIP.zip_name) { |zf| assert_contains(zf, replacedEntry, "#{SRC_DIR}/file2.txt") } end def test_addDirectory ZipFile.open(TEST_ZIP.zip_name) { |zf| zf.add(TestFiles::EMPTY_TEST_DIR, TestFiles::EMPTY_TEST_DIR) } ZipFile.open(TEST_ZIP.zip_name) { |zf| dirEntry = zf.entries.detect { |e| e.name == TestFiles::EMPTY_TEST_DIR+"/" } assert(dirEntry.is_directory) } end def test_remove entryToRemove, *remainingEntries = TEST_ZIP.entry_names FileUtils.cp(TestZipFile::TEST_ZIP2.zip_name, TEST_ZIP.zip_name) zf = ZipFile.new(TEST_ZIP.zip_name) assert(zf.entries.map { |e| e.name }.include?(entryToRemove)) zf.remove(entryToRemove) assert(! zf.entries.map { |e| e.name }.include?(entryToRemove)) assert_equal(zf.entries.map {|x| x.name }.sort, remainingEntries.sort) zf.close zfRead = ZipFile.new(TEST_ZIP.zip_name) assert(! zfRead.entries.map { |e| e.name }.include?(entryToRemove)) assert_equal(zfRead.entries.map {|x| x.name }.sort, remainingEntries.sort) zfRead.close end def test_rename entryToRename, *remainingEntries = TEST_ZIP.entry_names zf = ZipFile.new(TEST_ZIP.zip_name) assert(zf.entries.map { |e| e.name }.include?(entryToRename)) contents = zf.read(entryToRename) newName = "changed entry name" assert(! zf.entries.map { |e| e.name }.include?(newName)) zf.rename(entryToRename, newName) assert(zf.entries.map { |e| e.name }.include?(newName)) assert_equal(contents, zf.read(newName)) zf.close zfRead = ZipFile.new(TEST_ZIP.zip_name) assert(zfRead.entries.map { |e| e.name }.include?(newName)) assert_equal(contents, zfRead.read(newName)) zfRead.close end def test_renameToExistingEntry oldEntries = nil ZipFile.open(TEST_ZIP.zip_name) { |zf| oldEntries = zf.entries } assert_raise(ZipEntryExistsError) do ZipFile.open(TEST_ZIP.zip_name) do |zf| zf.rename(zf.entries[0], zf.entries[1].name) end end ZipFile.open(TEST_ZIP.zip_name) do |zf| assert_equal(oldEntries.sort.map{ |e| e.name }, zf.entries.sort.map{ |e| e.name }) end end def test_renameToExistingEntryOverwrite oldEntries = nil ZipFile.open(TEST_ZIP.zip_name) { |zf| oldEntries = zf.entries } gotCalled = false renamedEntryName = nil ZipFile.open(TEST_ZIP.zip_name) do |zf| renamedEntryName = zf.entries[0].name zf.rename(zf.entries[0], zf.entries[1].name) { gotCalled = true; true } end assert(gotCalled) oldEntries.delete_if { |e| e.name == renamedEntryName } ZipFile.open(TEST_ZIP.zip_name) do |zf| assert_equal(oldEntries.sort.map{ |e| e.name }, zf.entries.sort.map{ |e| e.name }) end end def test_renameNonEntry nonEntry = "bogusEntry" target_entry = "target_entryName" zf = ZipFile.new(TEST_ZIP.zip_name) assert(! zf.entries.include?(nonEntry)) assert_raise(Errno::ENOENT) { zf.rename(nonEntry, target_entry) } zf.commit assert(! zf.entries.include?(target_entry)) ensure zf.close end def test_renameEntryToExistingEntry entry1, entry2, *remaining = TEST_ZIP.entry_names zf = ZipFile.new(TEST_ZIP.zip_name) assert_raise(ZipEntryExistsError) { zf.rename(entry1, entry2) } ensure zf.close end def test_replace entryToReplace = TEST_ZIP.entry_names[2] newEntrySrcFilename = "#{SRC_DIR}/file2.txt" zf = ZipFile.new(TEST_ZIP.zip_name) zf.replace(entryToReplace, newEntrySrcFilename) zf.close zfRead = ZipFile.new(TEST_ZIP.zip_name) AssertEntry::assert_contents(newEntrySrcFilename, zfRead.get_input_stream(entryToReplace) { |is| is.read }) AssertEntry::assert_contents(TEST_ZIP.entry_names[0], zfRead.get_input_stream(TEST_ZIP.entry_names[0]) { |is| is.read }) AssertEntry::assert_contents(TEST_ZIP.entry_names[1], zfRead.get_input_stream(TEST_ZIP.entry_names[1]) { |is| is.read }) AssertEntry::assert_contents(TEST_ZIP.entry_names[3], zfRead.get_input_stream(TEST_ZIP.entry_names[3]) { |is| is.read }) zfRead.close end def test_replaceNonEntry entryToReplace = "nonExistingEntryname" ZipFile.open(TEST_ZIP.zip_name) { |zf| assert_raise(Errno::ENOENT) { zf.replace(entryToReplace, "#{SRC_DIR}/file2.txt") } } end def test_commit newName = "renamedFirst" zf = ZipFile.new(TEST_ZIP.zip_name) oldName = zf.entries.first zf.rename(oldName, newName) zf.commit zfRead = ZipFile.new(TEST_ZIP.zip_name) assert(zfRead.entries.detect { |e| e.name == newName } != nil) assert(zfRead.entries.detect { |e| e.name == oldName } == nil) zfRead.close zf.close end def test_write_buffer newName = "renamedFirst" zf = ZipFile.new(TEST_ZIP.zip_name) oldName = zf.entries.first zf.rename(oldName, newName) buffer = zf.write_buffer File.open(TEST_ZIP.zip_name, 'wb') { |f| f.write buffer.string } zfRead = ZipFile.new(TEST_ZIP.zip_name) assert(zfRead.entries.detect { |e| e.name == newName } != nil) assert(zfRead.entries.detect { |e| e.name == oldName } == nil) zfRead.close zf.close end # This test tests that after commit, you # can delete the file you used to add the entry to the zip file # with def test_commitUseZipEntry FileUtils.cp(TestFiles::RANDOM_ASCII_FILE1, "#{TRG_DIR}/okToDelete.txt") zf = ZipFile.open(TEST_ZIP.zip_name) zf.add("okToDelete.txt", "#{TRG_DIR}/okToDelete.txt") assert_contains(zf, "okToDelete.txt") zf.commit File.rename("#{TRG_DIR}/okToDelete.txt", "#{TRG_DIR}/okToDeleteMoved.txt") assert_contains(zf, "okToDelete.txt", "#{TRG_DIR}/okToDeleteMoved.txt") end # def test_close # zf = ZipFile.new(TEST_ZIP.zip_name) # zf.close # assert_raise(IOError) { # zf.extract(TEST_ZIP.entry_names.first, "hullubullu") # } # end def test_compound1 renamedName = "renamedName" originalEntries = [] begin zf = ZipFile.new(TEST_ZIP.zip_name) originalEntries = zf.entries.dup assert_not_contains(zf, TestFiles::RANDOM_ASCII_FILE1) zf.add(TestFiles::RANDOM_ASCII_FILE1, TestFiles::RANDOM_ASCII_FILE1) assert_contains(zf, TestFiles::RANDOM_ASCII_FILE1) zf.rename(zf.entries[0], renamedName) assert_contains(zf, renamedName) TestFiles::BINARY_TEST_FILES.each { |filename| zf.add(filename, filename) assert_contains(zf, filename) } assert_contains(zf, originalEntries.last.to_s) zf.remove(originalEntries.last.to_s) assert_not_contains(zf, originalEntries.last.to_s) ensure zf.close end begin zfRead = ZipFile.new(TEST_ZIP.zip_name) assert_contains(zfRead, TestFiles::RANDOM_ASCII_FILE1) assert_contains(zfRead, renamedName) TestFiles::BINARY_TEST_FILES.each { |filename| assert_contains(zfRead, filename) } assert_not_contains(zfRead, originalEntries.last.to_s) ensure zfRead.close end end def test_compound2 begin zf = ZipFile.new(TEST_ZIP.zip_name) originalEntries = zf.entries.dup originalEntries.each { |entry| zf.remove(entry) assert_not_contains(zf, entry) } assert(zf.entries.empty?) TestFiles::ASCII_TEST_FILES.each { |filename| zf.add(filename, filename) assert_contains(zf, filename) } assert_equal(zf.entries.sort.map { |e| e.name }, TestFiles::ASCII_TEST_FILES) zf.rename(TestFiles::ASCII_TEST_FILES[0], "newName") assert_not_contains(zf, TestFiles::ASCII_TEST_FILES[0]) assert_contains(zf, "newName") ensure zf.close end begin zfRead = ZipFile.new(TEST_ZIP.zip_name) asciiTestFiles = TestFiles::ASCII_TEST_FILES.dup asciiTestFiles.shift asciiTestFiles.each { |filename| assert_contains(zf, filename) } assert_contains(zf, "newName") ensure zfRead.close end end def test_changeComment ZipFile.open(TEST_ZIP.zip_name) do |zf| zf.comment = "my changed comment" end zfRead = ZipFile.open(TEST_ZIP.zip_name) assert_equal("my changed comment", zfRead.comment) end private def assert_contains(zf, entryName, filename = entryName) assert(zf.entries.detect { |e| e.name == entryName} != nil, "entry #{entryName} not in #{zf.entries.join(', ')} in zip file #{zf}") assert_entryContents(zf, entryName, filename) if File.exists?(filename) end def assert_not_contains(zf, entryName) assert(zf.entries.detect { |e| e.name == entryName} == nil, "entry #{entryName} in #{zf.entries.join(', ')} in zip file #{zf}") end end class ZipFileExtractTest < Test::Unit::TestCase include CommonZipFileFixture EXTRACTED_FILENAME = "extEntry" ENTRY_TO_EXTRACT, *REMAINING_ENTRIES = TEST_ZIP.entry_names.reverse def setup super File.delete(EXTRACTED_FILENAME) if File.exists?(EXTRACTED_FILENAME) end def test_extract ZipFile.open(TEST_ZIP.zip_name) { |zf| zf.extract(ENTRY_TO_EXTRACT, EXTRACTED_FILENAME) assert(File.exists?(EXTRACTED_FILENAME)) AssertEntry::assert_contents(EXTRACTED_FILENAME, zf.get_input_stream(ENTRY_TO_EXTRACT) { |is| is.read }) File::unlink(EXTRACTED_FILENAME) entry = zf.get_entry(ENTRY_TO_EXTRACT) entry.extract(EXTRACTED_FILENAME) assert(File.exists?(EXTRACTED_FILENAME)) AssertEntry::assert_contents(EXTRACTED_FILENAME, entry.get_input_stream() { |is| is.read }) } end def test_extractExists writtenText = "written text" File.open(EXTRACTED_FILENAME, "w") { |f| f.write(writtenText) } assert_raise(ZipDestinationFileExistsError) { ZipFile.open(TEST_ZIP.zip_name) { |zf| zf.extract(zf.entries.first, EXTRACTED_FILENAME) } } File.open(EXTRACTED_FILENAME, "r") { |f| assert_equal(writtenText, f.read) } end def test_extractExistsOverwrite writtenText = "written text" File.open(EXTRACTED_FILENAME, "w") { |f| f.write(writtenText) } gotCalledCorrectly = false ZipFile.open(TEST_ZIP.zip_name) { |zf| zf.extract(zf.entries.first, EXTRACTED_FILENAME) { |entry, extractLoc| gotCalledCorrectly = zf.entries.first == entry && extractLoc == EXTRACTED_FILENAME true } } assert(gotCalledCorrectly) File.open(EXTRACTED_FILENAME, "r") { |f| assert(writtenText != f.read) } end def test_extractNonEntry zf = ZipFile.new(TEST_ZIP.zip_name) assert_raise(Errno::ENOENT) { zf.extract("nonExistingEntry", "nonExistingEntry") } ensure zf.close if zf end def test_extractNonEntry2 outFile = "outfile" assert_raise(Errno::ENOENT) { zf = ZipFile.new(TEST_ZIP.zip_name) nonEntry = "hotdog-diddelidoo" assert(! zf.entries.include?(nonEntry)) zf.extract(nonEntry, outFile) zf.close } assert(! File.exists?(outFile)) end end class ZipFileExtractDirectoryTest < Test::Unit::TestCase include CommonZipFileFixture TEST_OUT_NAME = "#{TRG_DIR}/emptyOutDir" def open_zip(&aProc) assert(aProc != nil) ZipFile.open(TestZipFile::TEST_ZIP4.zip_name, &aProc) end def extract_test_dir(&aProc) open_zip { |zf| zf.extract(TestFiles::EMPTY_TEST_DIR, TEST_OUT_NAME, &aProc) } end def setup super Dir.rmdir(TEST_OUT_NAME) if File.directory? TEST_OUT_NAME File.delete(TEST_OUT_NAME) if File.exists? TEST_OUT_NAME end def test_extractDirectory extract_test_dir assert(File.directory?(TEST_OUT_NAME)) end def test_extractDirectoryExistsAsDir Dir.mkdir TEST_OUT_NAME extract_test_dir assert(File.directory?(TEST_OUT_NAME)) end def test_extractDirectoryExistsAsFile File.open(TEST_OUT_NAME, "w") { |f| f.puts "something" } assert_raise(ZipDestinationFileExistsError) { extract_test_dir } end def test_extractDirectoryExistsAsFileOverwrite File.open(TEST_OUT_NAME, "w") { |f| f.puts "something" } gotCalled = false extract_test_dir { |entry, destPath| gotCalled = true assert_equal(TEST_OUT_NAME, destPath) assert(entry.is_directory) true } assert(gotCalled) assert(File.directory?(TEST_OUT_NAME)) end end class ZipExtraFieldTest < Test::Unit::TestCase def test_new extra_pure = ZipExtraField.new("") extra_withstr = ZipExtraField.new("foo") assert_instance_of(ZipExtraField, extra_pure) assert_instance_of(ZipExtraField, extra_withstr) end def test_unknownfield extra = ZipExtraField.new("foo") assert_equal(extra["Unknown"], "foo") extra.merge("a") assert_equal(extra["Unknown"], "fooa") extra.merge("barbaz") assert_equal(extra.to_s, "fooabarbaz") end def test_merge str = "UT\x5\0\x3\250$\r@Ux\0\0" extra1 = ZipExtraField.new("") extra2 = ZipExtraField.new(str) assert(! extra1.member?("UniversalTime")) assert(extra2.member?("UniversalTime")) extra1.merge(str) assert_equal(extra1["UniversalTime"].mtime, extra2["UniversalTime"].mtime) end def test_length str = "UT\x5\0\x3\250$\r@Ux\0\0Te\0\0testit" extra = ZipExtraField.new(str) assert_equal(extra.local_length, extra.to_local_bin.length) assert_equal(extra.c_dir_length, extra.to_c_dir_bin.length) extra.merge("foo") assert_equal(extra.local_length, extra.to_local_bin.length) assert_equal(extra.c_dir_length, extra.to_c_dir_bin.length) end def test_to_s str = "UT\x5\0\x3\250$\r@Ux\0\0Te\0\0testit" extra = ZipExtraField.new(str) assert_instance_of(String, extra.to_s) s = extra.to_s extra.merge("foo") assert_equal(s.length + 3, extra.to_s.length) end def test_equality str = "UT\x5\0\x3\250$\r@" extra1 = ZipExtraField.new(str) extra2 = ZipExtraField.new(str) extra3 = ZipExtraField.new(str) assert_equal(extra1, extra2) extra2["UniversalTime"].mtime = DOSTime.now assert(extra1 != extra2) extra3.create("IUnix") assert(extra1 != extra3) extra1.create("IUnix") assert_equal(extra1, extra3) end end class ZipUnicodeFileNamesAndComments < Test::Unit::TestCase FILENAME = File.join(File.dirname(__FILE__), "test1.zip") def test_unicode file_entrys = ["текстовыйфайл.txt", "Résumé.txt", "슬레이어스휘.txt"] directory_entrys = ["папка/текстовыйфайл.txt", "Résumé/Résumé.txt", "슬레이어스휘/슬레이어스휘.txt"] stream = ::Zip::ZipOutputStream.open(FILENAME) do |io| file_entrys.each do |filename| io.put_next_entry(filename) io.write(filename) end directory_entrys.each do |filepath| io.put_next_entry(filepath) io.write(filepath) end end assert(!stream.nil?) ::Zip::ZipInputStream.open(FILENAME) do |io| file_entrys.each do |filename| entry = io.get_next_entry entry_name = entry.name entry_name = entry_name.force_encoding("UTF-8") if RUBY_VERSION >= '1.9' assert(filename == entry_name) end directory_entrys.each do |filepath| entry = io.get_next_entry entry_name = entry.name entry_name = entry_name.force_encoding("UTF-8") if RUBY_VERSION >= '1.9' assert(filepath == entry_name) end end ::File.unlink(FILENAME) end end class ZipSettingsTest < Test::Unit::TestCase # TODO Refactor out into common test module include CommonZipFileFixture TEST_OUT_NAME = "#{TRG_DIR}/emptyOutDir" def setup super Dir.rmdir(TEST_OUT_NAME) if File.directory? TEST_OUT_NAME File.delete(TEST_OUT_NAME) if File.exists? TEST_OUT_NAME end def open_zip(&aProc) assert(aProc != nil) ZipFile.open(TestZipFile::TEST_ZIP4.zip_name, &aProc) end def extract_test_dir(&aProc) open_zip { |zf| zf.extract(TestFiles::EMPTY_TEST_DIR, TEST_OUT_NAME, &aProc) } end def test_true_on_exists_proc Zip.options[:on_exists_proc] = true File.open(TEST_OUT_NAME, "w") { |f| f.puts "something" } extract_test_dir assert(File.directory?(TEST_OUT_NAME)) end def test_false_on_exists_proc Zip.options[:on_exists_proc] = false File.open(TEST_OUT_NAME, "w") { |f| f.puts "something" } assert_raise(Zip::ZipDestinationFileExistsError) { extract_test_dir } end def test_false_continue_on_exists_proc Zip.options[:continue_on_exists_proc] = false assert_raise(ZipEntryExistsError) do ZipFile.open(TEST_ZIP.zip_name) do |zf| zf.add(zf.entries.first.name, "#{SRC_DIR}/file2.txt") end end end def test_true_continue_on_exists_proc Zip.options[:continue_on_exists_proc] = true replacedEntry = nil ZipFile.open(TEST_ZIP.zip_name) do |zf| replacedEntry = zf.entries.first.name zf.add(replacedEntry, "#{SRC_DIR}/file2.txt") end ZipFile.open(TEST_ZIP.zip_name) do |zf| assert_contains(zf, replacedEntry, "#{SRC_DIR}/file2.txt") end end private def assert_contains(zf, entryName, filename = entryName) assert(zf.entries.detect { |e| e.name == entryName} != nil, "entry #{entryName} not in #{zf.entries.join(', ')} in zip file #{zf}") assert_entryContents(zf, entryName, filename) if File.exists?(filename) end end # Copyright (C) 2002-2005 Thomas Sondergaard # rubyzip is free software; you can redistribute it and/or # modify it under the terms of the ruby license. zip-zip-0.3/test/test_helper.rb000066400000000000000000000001141232145563700166040ustar00rootroot00000000000000gem "minitest" require 'minitest/autorun' require_relative '../lib/zip/zip' zip-zip-0.3/test/zip/000077500000000000000000000000001232145563700145475ustar00rootroot00000000000000zip-zip-0.3/test/zip/zip_test.rb000066400000000000000000000004601232145563700167350ustar00rootroot00000000000000require 'test_helper' describe Zip, '#options[]' do after { Zip.continue_on_exists_proc = false } it 'translates the 0.9 Zip.options[] interface to the new Zip. interface' do Zip.options[:continue_on_exists_proc] = '123' Zip.continue_on_exists_proc.must_equal('123') end end zip-zip-0.3/zip-zip.gemspec000066400000000000000000000016411232145563700157370ustar00rootroot00000000000000# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = 'zip-zip' spec.version = 0.3 spec.summary = 'Ease the migration to RubyZip v1.0.0' spec.description = ''' In Gem hell migrating to RubyZip v1.0.0? Include zip-zip in your Gemfile and everything\'s coming up roses! ''' spec.authors = ['Orien Madgwick'] spec.email = '_@orien.io' spec.files = ['lib/zip/zip.rb', 'lib/zip/zipfilesystem.rb', 'LICENSE.txt'] spec.homepage = 'https://github.com/orien/zip-zip' spec.license = 'MIT' spec.require_paths = ['lib'] spec.add_runtime_dependency 'rubyzip', '>= 1.0.0' spec.add_development_dependency 'bundler', '~> 1.6' spec.add_development_dependency 'rake' spec.add_development_dependency 'minitest', '4.7.5' spec.add_development_dependency 'pry' end