]> git.proxmox.com Git - mirror_edk2.git/blame - AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_zipfile.py
EmbeddedPkg: Extend NvVarStoreFormattedLib LIBRARY_CLASS
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.2 / Lib / test / test_zipfile.py
CommitLineData
4710c53d 1# We can test part of the module without zlib.\r
2try:\r
3 import zlib\r
4except ImportError:\r
5 zlib = None\r
6\r
7import os\r
8import io\r
9import sys\r
10import time\r
11import shutil\r
12import struct\r
13import zipfile\r
14import unittest\r
15\r
16from StringIO import StringIO\r
17from tempfile import TemporaryFile\r
18from random import randint, random\r
19from unittest import skipUnless\r
20\r
21from test.test_support import TESTFN, run_unittest, findfile, unlink\r
22\r
23TESTFN2 = TESTFN + "2"\r
24TESTFNDIR = TESTFN + "d"\r
25FIXEDTEST_SIZE = 1000\r
26\r
27SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),\r
28 ('ziptest2dir/_ziptest2', 'qawsedrftg'),\r
29 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),\r
30 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]\r
31\r
32\r
33class TestsWithSourceFile(unittest.TestCase):\r
34 def setUp(self):\r
35 self.line_gen = ["Zipfile test line %d. random float: %f" % (i, random())\r
36 for i in xrange(FIXEDTEST_SIZE)]\r
37 self.data = '\n'.join(self.line_gen) + '\n'\r
38\r
39 # Make a source file with some lines\r
40 with open(TESTFN, "wb") as fp:\r
41 fp.write(self.data)\r
42\r
43 def make_test_archive(self, f, compression):\r
44 # Create the ZIP archive\r
45 with zipfile.ZipFile(f, "w", compression) as zipfp:\r
46 zipfp.write(TESTFN, "another.name")\r
47 zipfp.write(TESTFN, TESTFN)\r
48 zipfp.writestr("strfile", self.data)\r
49\r
50 def zip_test(self, f, compression):\r
51 self.make_test_archive(f, compression)\r
52\r
53 # Read the ZIP archive\r
54 with zipfile.ZipFile(f, "r", compression) as zipfp:\r
55 self.assertEqual(zipfp.read(TESTFN), self.data)\r
56 self.assertEqual(zipfp.read("another.name"), self.data)\r
57 self.assertEqual(zipfp.read("strfile"), self.data)\r
58\r
59 # Print the ZIP directory\r
60 fp = StringIO()\r
61 stdout = sys.stdout\r
62 try:\r
63 sys.stdout = fp\r
64 zipfp.printdir()\r
65 finally:\r
66 sys.stdout = stdout\r
67\r
68 directory = fp.getvalue()\r
69 lines = directory.splitlines()\r
70 self.assertEqual(len(lines), 4) # Number of files + header\r
71\r
72 self.assertIn('File Name', lines[0])\r
73 self.assertIn('Modified', lines[0])\r
74 self.assertIn('Size', lines[0])\r
75\r
76 fn, date, time_, size = lines[1].split()\r
77 self.assertEqual(fn, 'another.name')\r
78 self.assertTrue(time.strptime(date, '%Y-%m-%d'))\r
79 self.assertTrue(time.strptime(time_, '%H:%M:%S'))\r
80 self.assertEqual(size, str(len(self.data)))\r
81\r
82 # Check the namelist\r
83 names = zipfp.namelist()\r
84 self.assertEqual(len(names), 3)\r
85 self.assertIn(TESTFN, names)\r
86 self.assertIn("another.name", names)\r
87 self.assertIn("strfile", names)\r
88\r
89 # Check infolist\r
90 infos = zipfp.infolist()\r
91 names = [i.filename for i in infos]\r
92 self.assertEqual(len(names), 3)\r
93 self.assertIn(TESTFN, names)\r
94 self.assertIn("another.name", names)\r
95 self.assertIn("strfile", names)\r
96 for i in infos:\r
97 self.assertEqual(i.file_size, len(self.data))\r
98\r
99 # check getinfo\r
100 for nm in (TESTFN, "another.name", "strfile"):\r
101 info = zipfp.getinfo(nm)\r
102 self.assertEqual(info.filename, nm)\r
103 self.assertEqual(info.file_size, len(self.data))\r
104\r
105 # Check that testzip doesn't raise an exception\r
106 zipfp.testzip()\r
107\r
108 def test_stored(self):\r
109 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
110 self.zip_test(f, zipfile.ZIP_STORED)\r
111\r
112 def zip_open_test(self, f, compression):\r
113 self.make_test_archive(f, compression)\r
114\r
115 # Read the ZIP archive\r
116 with zipfile.ZipFile(f, "r", compression) as zipfp:\r
117 zipdata1 = []\r
118 with zipfp.open(TESTFN) as zipopen1:\r
119 while True:\r
120 read_data = zipopen1.read(256)\r
121 if not read_data:\r
122 break\r
123 zipdata1.append(read_data)\r
124\r
125 zipdata2 = []\r
126 with zipfp.open("another.name") as zipopen2:\r
127 while True:\r
128 read_data = zipopen2.read(256)\r
129 if not read_data:\r
130 break\r
131 zipdata2.append(read_data)\r
132\r
133 self.assertEqual(''.join(zipdata1), self.data)\r
134 self.assertEqual(''.join(zipdata2), self.data)\r
135\r
136 def test_open_stored(self):\r
137 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
138 self.zip_open_test(f, zipfile.ZIP_STORED)\r
139\r
140 def test_open_via_zip_info(self):\r
141 # Create the ZIP archive\r
142 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:\r
143 zipfp.writestr("name", "foo")\r
144 zipfp.writestr("name", "bar")\r
145\r
146 with zipfile.ZipFile(TESTFN2, "r") as zipfp:\r
147 infos = zipfp.infolist()\r
148 data = ""\r
149 for info in infos:\r
150 with zipfp.open(info) as f:\r
151 data += f.read()\r
152 self.assertTrue(data == "foobar" or data == "barfoo")\r
153 data = ""\r
154 for info in infos:\r
155 data += zipfp.read(info)\r
156 self.assertTrue(data == "foobar" or data == "barfoo")\r
157\r
158 def zip_random_open_test(self, f, compression):\r
159 self.make_test_archive(f, compression)\r
160\r
161 # Read the ZIP archive\r
162 with zipfile.ZipFile(f, "r", compression) as zipfp:\r
163 zipdata1 = []\r
164 with zipfp.open(TESTFN) as zipopen1:\r
165 while True:\r
166 read_data = zipopen1.read(randint(1, 1024))\r
167 if not read_data:\r
168 break\r
169 zipdata1.append(read_data)\r
170\r
171 self.assertEqual(''.join(zipdata1), self.data)\r
172\r
173 def test_random_open_stored(self):\r
174 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
175 self.zip_random_open_test(f, zipfile.ZIP_STORED)\r
176\r
177 def test_univeral_readaheads(self):\r
178 f = StringIO()\r
179\r
180 data = 'a\r\n' * 16 * 1024\r
181 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:\r
182 zipfp.writestr(TESTFN, data)\r
183\r
184 data2 = ''\r
185 with zipfile.ZipFile(f, 'r') as zipfp:\r
186 with zipfp.open(TESTFN, 'rU') as zipopen:\r
187 for line in zipopen:\r
188 data2 += line\r
189\r
190 self.assertEqual(data, data2.replace('\n', '\r\n'))\r
191\r
192 def zip_readline_read_test(self, f, compression):\r
193 self.make_test_archive(f, compression)\r
194\r
195 # Read the ZIP archive\r
196 with zipfile.ZipFile(f, "r") as zipfp:\r
197 with zipfp.open(TESTFN) as zipopen:\r
198 data = ''\r
199 while True:\r
200 read = zipopen.readline()\r
201 if not read:\r
202 break\r
203 data += read\r
204\r
205 read = zipopen.read(100)\r
206 if not read:\r
207 break\r
208 data += read\r
209\r
210 self.assertEqual(data, self.data)\r
211\r
212 def zip_readline_test(self, f, compression):\r
213 self.make_test_archive(f, compression)\r
214\r
215 # Read the ZIP archive\r
216 with zipfile.ZipFile(f, "r") as zipfp:\r
217 with zipfp.open(TESTFN) as zipopen:\r
218 for line in self.line_gen:\r
219 linedata = zipopen.readline()\r
220 self.assertEqual(linedata, line + '\n')\r
221\r
222 def zip_readlines_test(self, f, compression):\r
223 self.make_test_archive(f, compression)\r
224\r
225 # Read the ZIP archive\r
226 with zipfile.ZipFile(f, "r") as zipfp:\r
227 with zipfp.open(TESTFN) as zo:\r
228 ziplines = zo.readlines()\r
229 for line, zipline in zip(self.line_gen, ziplines):\r
230 self.assertEqual(zipline, line + '\n')\r
231\r
232 def zip_iterlines_test(self, f, compression):\r
233 self.make_test_archive(f, compression)\r
234\r
235 # Read the ZIP archive\r
236 with zipfile.ZipFile(f, "r") as zipfp:\r
237 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):\r
238 self.assertEqual(zipline, line + '\n')\r
239\r
240 def test_readline_read_stored(self):\r
241 # Issue #7610: calls to readline() interleaved with calls to read().\r
242 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
243 self.zip_readline_read_test(f, zipfile.ZIP_STORED)\r
244\r
245 def test_readline_stored(self):\r
246 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
247 self.zip_readline_test(f, zipfile.ZIP_STORED)\r
248\r
249 def test_readlines_stored(self):\r
250 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
251 self.zip_readlines_test(f, zipfile.ZIP_STORED)\r
252\r
253 def test_iterlines_stored(self):\r
254 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
255 self.zip_iterlines_test(f, zipfile.ZIP_STORED)\r
256\r
257 @skipUnless(zlib, "requires zlib")\r
258 def test_deflated(self):\r
259 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
260 self.zip_test(f, zipfile.ZIP_DEFLATED)\r
261\r
262 @skipUnless(zlib, "requires zlib")\r
263 def test_open_deflated(self):\r
264 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
265 self.zip_open_test(f, zipfile.ZIP_DEFLATED)\r
266\r
267 @skipUnless(zlib, "requires zlib")\r
268 def test_random_open_deflated(self):\r
269 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
270 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)\r
271\r
272 @skipUnless(zlib, "requires zlib")\r
273 def test_readline_read_deflated(self):\r
274 # Issue #7610: calls to readline() interleaved with calls to read().\r
275 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
276 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)\r
277\r
278 @skipUnless(zlib, "requires zlib")\r
279 def test_readline_deflated(self):\r
280 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
281 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)\r
282\r
283 @skipUnless(zlib, "requires zlib")\r
284 def test_readlines_deflated(self):\r
285 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
286 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)\r
287\r
288 @skipUnless(zlib, "requires zlib")\r
289 def test_iterlines_deflated(self):\r
290 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
291 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)\r
292\r
293 @skipUnless(zlib, "requires zlib")\r
294 def test_low_compression(self):\r
295 """Check for cases where compressed data is larger than original."""\r
296 # Create the ZIP archive\r
297 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:\r
298 zipfp.writestr("strfile", '12')\r
299\r
300 # Get an open object for strfile\r
301 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:\r
302 with zipfp.open("strfile") as openobj:\r
303 self.assertEqual(openobj.read(1), '1')\r
304 self.assertEqual(openobj.read(1), '2')\r
305\r
306 def test_absolute_arcnames(self):\r
307 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:\r
308 zipfp.write(TESTFN, "/absolute")\r
309\r
310 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:\r
311 self.assertEqual(zipfp.namelist(), ["absolute"])\r
312\r
313 def test_append_to_zip_file(self):\r
314 """Test appending to an existing zipfile."""\r
315 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:\r
316 zipfp.write(TESTFN, TESTFN)\r
317\r
318 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:\r
319 zipfp.writestr("strfile", self.data)\r
320 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])\r
321\r
322 def test_append_to_non_zip_file(self):\r
323 """Test appending to an existing file that is not a zipfile."""\r
324 # NOTE: this test fails if len(d) < 22 because of the first\r
325 # line "fpin.seek(-22, 2)" in _EndRecData\r
326 data = 'I am not a ZipFile!'*10\r
327 with open(TESTFN2, 'wb') as f:\r
328 f.write(data)\r
329\r
330 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:\r
331 zipfp.write(TESTFN, TESTFN)\r
332\r
333 with open(TESTFN2, 'rb') as f:\r
334 f.seek(len(data))\r
335 with zipfile.ZipFile(f, "r") as zipfp:\r
336 self.assertEqual(zipfp.namelist(), [TESTFN])\r
337\r
338 def test_write_default_name(self):\r
339 """Check that calling ZipFile.write without arcname specified\r
340 produces the expected result."""\r
341 with zipfile.ZipFile(TESTFN2, "w") as zipfp:\r
342 zipfp.write(TESTFN)\r
343 self.assertEqual(zipfp.read(TESTFN), open(TESTFN).read())\r
344\r
345 @skipUnless(zlib, "requires zlib")\r
346 def test_per_file_compression(self):\r
347 """Check that files within a Zip archive can have different\r
348 compression options."""\r
349 with zipfile.ZipFile(TESTFN2, "w") as zipfp:\r
350 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)\r
351 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)\r
352 sinfo = zipfp.getinfo('storeme')\r
353 dinfo = zipfp.getinfo('deflateme')\r
354 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)\r
355 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)\r
356\r
357 def test_write_to_readonly(self):\r
358 """Check that trying to call write() on a readonly ZipFile object\r
359 raises a RuntimeError."""\r
360 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:\r
361 zipfp.writestr("somefile.txt", "bogus")\r
362\r
363 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:\r
364 self.assertRaises(RuntimeError, zipfp.write, TESTFN)\r
365\r
366 def test_extract(self):\r
367 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:\r
368 for fpath, fdata in SMALL_TEST_DATA:\r
369 zipfp.writestr(fpath, fdata)\r
370\r
371 with zipfile.ZipFile(TESTFN2, "r") as zipfp:\r
372 for fpath, fdata in SMALL_TEST_DATA:\r
373 writtenfile = zipfp.extract(fpath)\r
374\r
375 # make sure it was written to the right place\r
376 if os.path.isabs(fpath):\r
377 correctfile = os.path.join(os.getcwd(), fpath[1:])\r
378 else:\r
379 correctfile = os.path.join(os.getcwd(), fpath)\r
380 correctfile = os.path.normpath(correctfile)\r
381\r
382 self.assertEqual(writtenfile, correctfile)\r
383\r
384 # make sure correct data is in correct file\r
385 self.assertEqual(fdata, open(writtenfile, "rb").read())\r
386 os.remove(writtenfile)\r
387\r
388 # remove the test file subdirectories\r
389 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))\r
390\r
391 def test_extract_all(self):\r
392 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:\r
393 for fpath, fdata in SMALL_TEST_DATA:\r
394 zipfp.writestr(fpath, fdata)\r
395\r
396 with zipfile.ZipFile(TESTFN2, "r") as zipfp:\r
397 zipfp.extractall()\r
398 for fpath, fdata in SMALL_TEST_DATA:\r
399 if os.path.isabs(fpath):\r
400 outfile = os.path.join(os.getcwd(), fpath[1:])\r
401 else:\r
402 outfile = os.path.join(os.getcwd(), fpath)\r
403\r
404 self.assertEqual(fdata, open(outfile, "rb").read())\r
405 os.remove(outfile)\r
406\r
407 # remove the test file subdirectories\r
408 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))\r
409\r
410 def test_writestr_compression(self):\r
411 zipfp = zipfile.ZipFile(TESTFN2, "w")\r
412 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)\r
413 if zlib:\r
414 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)\r
415\r
416 info = zipfp.getinfo('a.txt')\r
417 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)\r
418\r
419 if zlib:\r
420 info = zipfp.getinfo('b.txt')\r
421 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)\r
422\r
423\r
424 def zip_test_writestr_permissions(self, f, compression):\r
425 # Make sure that writestr creates files with mode 0600,\r
426 # when it is passed a name rather than a ZipInfo instance.\r
427\r
428 self.make_test_archive(f, compression)\r
429 with zipfile.ZipFile(f, "r") as zipfp:\r
430 zinfo = zipfp.getinfo('strfile')\r
431 self.assertEqual(zinfo.external_attr, 0600 << 16)\r
432\r
433 def test_writestr_permissions(self):\r
434 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
435 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)\r
436\r
437 def test_close(self):\r
438 """Check that the zipfile is closed after the 'with' block."""\r
439 with zipfile.ZipFile(TESTFN2, "w") as zipfp:\r
440 for fpath, fdata in SMALL_TEST_DATA:\r
441 zipfp.writestr(fpath, fdata)\r
442 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')\r
443 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')\r
444\r
445 with zipfile.ZipFile(TESTFN2, "r") as zipfp:\r
446 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')\r
447 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')\r
448\r
449 def test_close_on_exception(self):\r
450 """Check that the zipfile is closed if an exception is raised in the\r
451 'with' block."""\r
452 with zipfile.ZipFile(TESTFN2, "w") as zipfp:\r
453 for fpath, fdata in SMALL_TEST_DATA:\r
454 zipfp.writestr(fpath, fdata)\r
455\r
456 try:\r
457 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:\r
458 raise zipfile.BadZipfile()\r
459 except zipfile.BadZipfile:\r
460 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')\r
461\r
462 def tearDown(self):\r
463 unlink(TESTFN)\r
464 unlink(TESTFN2)\r
465\r
466\r
467class TestZip64InSmallFiles(unittest.TestCase):\r
468 # These tests test the ZIP64 functionality without using large files,\r
469 # see test_zipfile64 for proper tests.\r
470\r
471 def setUp(self):\r
472 self._limit = zipfile.ZIP64_LIMIT\r
473 zipfile.ZIP64_LIMIT = 5\r
474\r
475 line_gen = ("Test of zipfile line %d." % i\r
476 for i in range(0, FIXEDTEST_SIZE))\r
477 self.data = '\n'.join(line_gen)\r
478\r
479 # Make a source file with some lines\r
480 with open(TESTFN, "wb") as fp:\r
481 fp.write(self.data)\r
482\r
483 def large_file_exception_test(self, f, compression):\r
484 with zipfile.ZipFile(f, "w", compression) as zipfp:\r
485 self.assertRaises(zipfile.LargeZipFile,\r
486 zipfp.write, TESTFN, "another.name")\r
487\r
488 def large_file_exception_test2(self, f, compression):\r
489 with zipfile.ZipFile(f, "w", compression) as zipfp:\r
490 self.assertRaises(zipfile.LargeZipFile,\r
491 zipfp.writestr, "another.name", self.data)\r
492\r
493 def test_large_file_exception(self):\r
494 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
495 self.large_file_exception_test(f, zipfile.ZIP_STORED)\r
496 self.large_file_exception_test2(f, zipfile.ZIP_STORED)\r
497\r
498 def zip_test(self, f, compression):\r
499 # Create the ZIP archive\r
500 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:\r
501 zipfp.write(TESTFN, "another.name")\r
502 zipfp.write(TESTFN, TESTFN)\r
503 zipfp.writestr("strfile", self.data)\r
504\r
505 # Read the ZIP archive\r
506 with zipfile.ZipFile(f, "r", compression) as zipfp:\r
507 self.assertEqual(zipfp.read(TESTFN), self.data)\r
508 self.assertEqual(zipfp.read("another.name"), self.data)\r
509 self.assertEqual(zipfp.read("strfile"), self.data)\r
510\r
511 # Print the ZIP directory\r
512 fp = StringIO()\r
513 stdout = sys.stdout\r
514 try:\r
515 sys.stdout = fp\r
516 zipfp.printdir()\r
517 finally:\r
518 sys.stdout = stdout\r
519\r
520 directory = fp.getvalue()\r
521 lines = directory.splitlines()\r
522 self.assertEqual(len(lines), 4) # Number of files + header\r
523\r
524 self.assertIn('File Name', lines[0])\r
525 self.assertIn('Modified', lines[0])\r
526 self.assertIn('Size', lines[0])\r
527\r
528 fn, date, time_, size = lines[1].split()\r
529 self.assertEqual(fn, 'another.name')\r
530 self.assertTrue(time.strptime(date, '%Y-%m-%d'))\r
531 self.assertTrue(time.strptime(time_, '%H:%M:%S'))\r
532 self.assertEqual(size, str(len(self.data)))\r
533\r
534 # Check the namelist\r
535 names = zipfp.namelist()\r
536 self.assertEqual(len(names), 3)\r
537 self.assertIn(TESTFN, names)\r
538 self.assertIn("another.name", names)\r
539 self.assertIn("strfile", names)\r
540\r
541 # Check infolist\r
542 infos = zipfp.infolist()\r
543 names = [i.filename for i in infos]\r
544 self.assertEqual(len(names), 3)\r
545 self.assertIn(TESTFN, names)\r
546 self.assertIn("another.name", names)\r
547 self.assertIn("strfile", names)\r
548 for i in infos:\r
549 self.assertEqual(i.file_size, len(self.data))\r
550\r
551 # check getinfo\r
552 for nm in (TESTFN, "another.name", "strfile"):\r
553 info = zipfp.getinfo(nm)\r
554 self.assertEqual(info.filename, nm)\r
555 self.assertEqual(info.file_size, len(self.data))\r
556\r
557 # Check that testzip doesn't raise an exception\r
558 zipfp.testzip()\r
559\r
560 def test_stored(self):\r
561 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
562 self.zip_test(f, zipfile.ZIP_STORED)\r
563\r
564 @skipUnless(zlib, "requires zlib")\r
565 def test_deflated(self):\r
566 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
567 self.zip_test(f, zipfile.ZIP_DEFLATED)\r
568\r
569 def test_absolute_arcnames(self):\r
570 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,\r
571 allowZip64=True) as zipfp:\r
572 zipfp.write(TESTFN, "/absolute")\r
573\r
574 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:\r
575 self.assertEqual(zipfp.namelist(), ["absolute"])\r
576\r
577 def tearDown(self):\r
578 zipfile.ZIP64_LIMIT = self._limit\r
579 unlink(TESTFN)\r
580 unlink(TESTFN2)\r
581\r
582\r
583class PyZipFileTests(unittest.TestCase):\r
584 def test_write_pyfile(self):\r
585 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:\r
586 fn = __file__\r
587 if fn.endswith('.pyc') or fn.endswith('.pyo'):\r
588 fn = fn[:-1]\r
589\r
590 zipfp.writepy(fn)\r
591\r
592 bn = os.path.basename(fn)\r
593 self.assertNotIn(bn, zipfp.namelist())\r
594 self.assertTrue(bn + 'o' in zipfp.namelist() or\r
595 bn + 'c' in zipfp.namelist())\r
596\r
597 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:\r
598 fn = __file__\r
599 if fn.endswith(('.pyc', '.pyo')):\r
600 fn = fn[:-1]\r
601\r
602 zipfp.writepy(fn, "testpackage")\r
603\r
604 bn = "%s/%s" % ("testpackage", os.path.basename(fn))\r
605 self.assertNotIn(bn, zipfp.namelist())\r
606 self.assertTrue(bn + 'o' in zipfp.namelist() or\r
607 bn + 'c' in zipfp.namelist())\r
608\r
609 def test_write_python_package(self):\r
610 import email\r
611 packagedir = os.path.dirname(email.__file__)\r
612\r
613 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:\r
614 zipfp.writepy(packagedir)\r
615\r
616 # Check for a couple of modules at different levels of the\r
617 # hierarchy\r
618 names = zipfp.namelist()\r
619 self.assertTrue('email/__init__.pyo' in names or\r
620 'email/__init__.pyc' in names)\r
621 self.assertTrue('email/mime/text.pyo' in names or\r
622 'email/mime/text.pyc' in names)\r
623\r
624 def test_write_python_directory(self):\r
625 os.mkdir(TESTFN2)\r
626 try:\r
627 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:\r
628 fp.write("print(42)\n")\r
629\r
630 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:\r
631 fp.write("print(42 * 42)\n")\r
632\r
633 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:\r
634 fp.write("bla bla bla\n")\r
635\r
636 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")\r
637 zipfp.writepy(TESTFN2)\r
638\r
639 names = zipfp.namelist()\r
640 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)\r
641 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)\r
642 self.assertNotIn('mod2.txt', names)\r
643\r
644 finally:\r
645 shutil.rmtree(TESTFN2)\r
646\r
647 def test_write_non_pyfile(self):\r
648 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:\r
649 open(TESTFN, 'w').write('most definitely not a python file')\r
650 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)\r
651 os.remove(TESTFN)\r
652\r
653\r
654class OtherTests(unittest.TestCase):\r
655 zips_with_bad_crc = {\r
656 zipfile.ZIP_STORED: (\r
657 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'\r
658 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'\r
659 b'ilehello,AworldP'\r
660 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'\r
661 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'\r
662 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'\r
663 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'\r
664 b'\0\0/\0\0\0\0\0'),\r
665 zipfile.ZIP_DEFLATED: (\r
666 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'\r
667 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'\r
668 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'\r
669 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'\r
670 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'\r
671 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'\r
672 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'\r
673 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),\r
674 }\r
675\r
676 def test_unicode_filenames(self):\r
677 with zipfile.ZipFile(TESTFN, "w") as zf:\r
678 zf.writestr(u"foo.txt", "Test for unicode filename")\r
679 zf.writestr(u"\xf6.txt", "Test for unicode filename")\r
680 self.assertIsInstance(zf.infolist()[0].filename, unicode)\r
681\r
682 with zipfile.ZipFile(TESTFN, "r") as zf:\r
683 self.assertEqual(zf.filelist[0].filename, "foo.txt")\r
684 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")\r
685\r
686 def test_create_non_existent_file_for_append(self):\r
687 if os.path.exists(TESTFN):\r
688 os.unlink(TESTFN)\r
689\r
690 filename = 'testfile.txt'\r
691 content = 'hello, world. this is some content.'\r
692\r
693 try:\r
694 with zipfile.ZipFile(TESTFN, 'a') as zf:\r
695 zf.writestr(filename, content)\r
696 except IOError:\r
697 self.fail('Could not append data to a non-existent zip file.')\r
698\r
699 self.assertTrue(os.path.exists(TESTFN))\r
700\r
701 with zipfile.ZipFile(TESTFN, 'r') as zf:\r
702 self.assertEqual(zf.read(filename), content)\r
703\r
704 def test_close_erroneous_file(self):\r
705 # This test checks that the ZipFile constructor closes the file object\r
706 # it opens if there's an error in the file. If it doesn't, the\r
707 # traceback holds a reference to the ZipFile object and, indirectly,\r
708 # the file object.\r
709 # On Windows, this causes the os.unlink() call to fail because the\r
710 # underlying file is still open. This is SF bug #412214.\r
711 #\r
712 with open(TESTFN, "w") as fp:\r
713 fp.write("this is not a legal zip file\n")\r
714 try:\r
715 zf = zipfile.ZipFile(TESTFN)\r
716 except zipfile.BadZipfile:\r
717 pass\r
718\r
719 def test_is_zip_erroneous_file(self):\r
720 """Check that is_zipfile() correctly identifies non-zip files."""\r
721 # - passing a filename\r
722 with open(TESTFN, "w") as fp:\r
723 fp.write("this is not a legal zip file\n")\r
724 chk = zipfile.is_zipfile(TESTFN)\r
725 self.assertFalse(chk)\r
726 # - passing a file object\r
727 with open(TESTFN, "rb") as fp:\r
728 chk = zipfile.is_zipfile(fp)\r
729 self.assertTrue(not chk)\r
730 # - passing a file-like object\r
731 fp = StringIO()\r
732 fp.write("this is not a legal zip file\n")\r
733 chk = zipfile.is_zipfile(fp)\r
734 self.assertTrue(not chk)\r
735 fp.seek(0, 0)\r
736 chk = zipfile.is_zipfile(fp)\r
737 self.assertTrue(not chk)\r
738\r
739 def test_is_zip_valid_file(self):\r
740 """Check that is_zipfile() correctly identifies zip files."""\r
741 # - passing a filename\r
742 with zipfile.ZipFile(TESTFN, mode="w") as zipf:\r
743 zipf.writestr("foo.txt", "O, for a Muse of Fire!")\r
744 chk = zipfile.is_zipfile(TESTFN)\r
745 self.assertTrue(chk)\r
746 # - passing a file object\r
747 with open(TESTFN, "rb") as fp:\r
748 chk = zipfile.is_zipfile(fp)\r
749 self.assertTrue(chk)\r
750 fp.seek(0, 0)\r
751 zip_contents = fp.read()\r
752 # - passing a file-like object\r
753 fp = StringIO()\r
754 fp.write(zip_contents)\r
755 chk = zipfile.is_zipfile(fp)\r
756 self.assertTrue(chk)\r
757 fp.seek(0, 0)\r
758 chk = zipfile.is_zipfile(fp)\r
759 self.assertTrue(chk)\r
760\r
761 def test_non_existent_file_raises_IOError(self):\r
762 # make sure we don't raise an AttributeError when a partially-constructed\r
763 # ZipFile instance is finalized; this tests for regression on SF tracker\r
764 # bug #403871.\r
765\r
766 # The bug we're testing for caused an AttributeError to be raised\r
767 # when a ZipFile instance was created for a file that did not\r
768 # exist; the .fp member was not initialized but was needed by the\r
769 # __del__() method. Since the AttributeError is in the __del__(),\r
770 # it is ignored, but the user should be sufficiently annoyed by\r
771 # the message on the output that regression will be noticed\r
772 # quickly.\r
773 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)\r
774\r
775 def test_empty_file_raises_BadZipFile(self):\r
776 with open(TESTFN, 'w') as f:\r
777 pass\r
778 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)\r
779\r
780 with open(TESTFN, 'w') as fp:\r
781 fp.write("short file")\r
782 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)\r
783\r
784 def test_closed_zip_raises_RuntimeError(self):\r
785 """Verify that testzip() doesn't swallow inappropriate exceptions."""\r
786 data = StringIO()\r
787 with zipfile.ZipFile(data, mode="w") as zipf:\r
788 zipf.writestr("foo.txt", "O, for a Muse of Fire!")\r
789\r
790 # This is correct; calling .read on a closed ZipFile should throw\r
791 # a RuntimeError, and so should calling .testzip. An earlier\r
792 # version of .testzip would swallow this exception (and any other)\r
793 # and report that the first file in the archive was corrupt.\r
794 self.assertRaises(RuntimeError, zipf.read, "foo.txt")\r
795 self.assertRaises(RuntimeError, zipf.open, "foo.txt")\r
796 self.assertRaises(RuntimeError, zipf.testzip)\r
797 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")\r
798 open(TESTFN, 'w').write('zipfile test data')\r
799 self.assertRaises(RuntimeError, zipf.write, TESTFN)\r
800\r
801 def test_bad_constructor_mode(self):\r
802 """Check that bad modes passed to ZipFile constructor are caught."""\r
803 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")\r
804\r
805 def test_bad_open_mode(self):\r
806 """Check that bad modes passed to ZipFile.open are caught."""\r
807 with zipfile.ZipFile(TESTFN, mode="w") as zipf:\r
808 zipf.writestr("foo.txt", "O, for a Muse of Fire!")\r
809\r
810 with zipfile.ZipFile(TESTFN, mode="r") as zipf:\r
811 # read the data to make sure the file is there\r
812 zipf.read("foo.txt")\r
813 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")\r
814\r
815 def test_read0(self):\r
816 """Check that calling read(0) on a ZipExtFile object returns an empty\r
817 string and doesn't advance file pointer."""\r
818 with zipfile.ZipFile(TESTFN, mode="w") as zipf:\r
819 zipf.writestr("foo.txt", "O, for a Muse of Fire!")\r
820 # read the data to make sure the file is there\r
821 with zipf.open("foo.txt") as f:\r
822 for i in xrange(FIXEDTEST_SIZE):\r
823 self.assertEqual(f.read(0), '')\r
824\r
825 self.assertEqual(f.read(), "O, for a Muse of Fire!")\r
826\r
827 def test_open_non_existent_item(self):\r
828 """Check that attempting to call open() for an item that doesn't\r
829 exist in the archive raises a RuntimeError."""\r
830 with zipfile.ZipFile(TESTFN, mode="w") as zipf:\r
831 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")\r
832\r
833 def test_bad_compression_mode(self):\r
834 """Check that bad compression methods passed to ZipFile.open are\r
835 caught."""\r
836 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)\r
837\r
838 def test_null_byte_in_filename(self):\r
839 """Check that a filename containing a null byte is properly\r
840 terminated."""\r
841 with zipfile.ZipFile(TESTFN, mode="w") as zipf:\r
842 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")\r
843 self.assertEqual(zipf.namelist(), ['foo.txt'])\r
844\r
845 def test_struct_sizes(self):\r
846 """Check that ZIP internal structure sizes are calculated correctly."""\r
847 self.assertEqual(zipfile.sizeEndCentDir, 22)\r
848 self.assertEqual(zipfile.sizeCentralDir, 46)\r
849 self.assertEqual(zipfile.sizeEndCentDir64, 56)\r
850 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)\r
851\r
852 def test_comments(self):\r
853 """Check that comments on the archive are handled properly."""\r
854\r
855 # check default comment is empty\r
856 with zipfile.ZipFile(TESTFN, mode="w") as zipf:\r
857 self.assertEqual(zipf.comment, '')\r
858 zipf.writestr("foo.txt", "O, for a Muse of Fire!")\r
859\r
860 with zipfile.ZipFile(TESTFN, mode="r") as zipf:\r
861 self.assertEqual(zipf.comment, '')\r
862\r
863 # check a simple short comment\r
864 comment = 'Bravely taking to his feet, he beat a very brave retreat.'\r
865 with zipfile.ZipFile(TESTFN, mode="w") as zipf:\r
866 zipf.comment = comment\r
867 zipf.writestr("foo.txt", "O, for a Muse of Fire!")\r
868 with zipfile.ZipFile(TESTFN, mode="r") as zipf:\r
869 self.assertEqual(zipf.comment, comment)\r
870\r
871 # check a comment of max length\r
872 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])\r
873 with zipfile.ZipFile(TESTFN, mode="w") as zipf:\r
874 zipf.comment = comment2\r
875 zipf.writestr("foo.txt", "O, for a Muse of Fire!")\r
876\r
877 with zipfile.ZipFile(TESTFN, mode="r") as zipf:\r
878 self.assertEqual(zipf.comment, comment2)\r
879\r
880 # check a comment that is too long is truncated\r
881 with zipfile.ZipFile(TESTFN, mode="w") as zipf:\r
882 zipf.comment = comment2 + 'oops'\r
883 zipf.writestr("foo.txt", "O, for a Muse of Fire!")\r
884 with zipfile.ZipFile(TESTFN, mode="r") as zipf:\r
885 self.assertEqual(zipf.comment, comment2)\r
886\r
887 def check_testzip_with_bad_crc(self, compression):\r
888 """Tests that files with bad CRCs return their name from testzip."""\r
889 zipdata = self.zips_with_bad_crc[compression]\r
890\r
891 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:\r
892 # testzip returns the name of the first corrupt file, or None\r
893 self.assertEqual('afile', zipf.testzip())\r
894\r
895 def test_testzip_with_bad_crc_stored(self):\r
896 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)\r
897\r
898 @skipUnless(zlib, "requires zlib")\r
899 def test_testzip_with_bad_crc_deflated(self):\r
900 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)\r
901\r
902 def check_read_with_bad_crc(self, compression):\r
903 """Tests that files with bad CRCs raise a BadZipfile exception when read."""\r
904 zipdata = self.zips_with_bad_crc[compression]\r
905\r
906 # Using ZipFile.read()\r
907 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:\r
908 self.assertRaises(zipfile.BadZipfile, zipf.read, 'afile')\r
909\r
910 # Using ZipExtFile.read()\r
911 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:\r
912 with zipf.open('afile', 'r') as corrupt_file:\r
913 self.assertRaises(zipfile.BadZipfile, corrupt_file.read)\r
914\r
915 # Same with small reads (in order to exercise the buffering logic)\r
916 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:\r
917 with zipf.open('afile', 'r') as corrupt_file:\r
918 corrupt_file.MIN_READ_SIZE = 2\r
919 with self.assertRaises(zipfile.BadZipfile):\r
920 while corrupt_file.read(2):\r
921 pass\r
922\r
923 def test_read_with_bad_crc_stored(self):\r
924 self.check_read_with_bad_crc(zipfile.ZIP_STORED)\r
925\r
926 @skipUnless(zlib, "requires zlib")\r
927 def test_read_with_bad_crc_deflated(self):\r
928 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)\r
929\r
930 def check_read_return_size(self, compression):\r
931 # Issue #9837: ZipExtFile.read() shouldn't return more bytes\r
932 # than requested.\r
933 for test_size in (1, 4095, 4096, 4097, 16384):\r
934 file_size = test_size + 1\r
935 junk = b''.join(struct.pack('B', randint(0, 255))\r
936 for x in range(file_size))\r
937 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:\r
938 zipf.writestr('foo', junk)\r
939 with zipf.open('foo', 'r') as fp:\r
940 buf = fp.read(test_size)\r
941 self.assertEqual(len(buf), test_size)\r
942\r
943 def test_read_return_size_stored(self):\r
944 self.check_read_return_size(zipfile.ZIP_STORED)\r
945\r
946 @skipUnless(zlib, "requires zlib")\r
947 def test_read_return_size_deflated(self):\r
948 self.check_read_return_size(zipfile.ZIP_DEFLATED)\r
949\r
950 def test_empty_zipfile(self):\r
951 # Check that creating a file in 'w' or 'a' mode and closing without\r
952 # adding any files to the archives creates a valid empty ZIP file\r
953 with zipfile.ZipFile(TESTFN, mode="w") as zipf:\r
954 pass\r
955 try:\r
956 zipf = zipfile.ZipFile(TESTFN, mode="r")\r
957 except zipfile.BadZipfile:\r
958 self.fail("Unable to create empty ZIP file in 'w' mode")\r
959\r
960 with zipfile.ZipFile(TESTFN, mode="a") as zipf:\r
961 pass\r
962 try:\r
963 zipf = zipfile.ZipFile(TESTFN, mode="r")\r
964 except:\r
965 self.fail("Unable to create empty ZIP file in 'a' mode")\r
966\r
967 def test_open_empty_file(self):\r
968 # Issue 1710703: Check that opening a file with less than 22 bytes\r
969 # raises a BadZipfile exception (rather than the previously unhelpful\r
970 # IOError)\r
971 with open(TESTFN, 'w') as f:\r
972 pass\r
973 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN, 'r')\r
974\r
975 def tearDown(self):\r
976 unlink(TESTFN)\r
977 unlink(TESTFN2)\r
978\r
979\r
980class DecryptionTests(unittest.TestCase):\r
981 """Check that ZIP decryption works. Since the library does not\r
982 support encryption at the moment, we use a pre-generated encrypted\r
983 ZIP file."""\r
984\r
985 data = (\r
986 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'\r
987 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'\r
988 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'\r
989 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'\r
990 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'\r
991 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'\r
992 '\x00\x00L\x00\x00\x00\x00\x00' )\r
993 data2 = (\r
994 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'\r
995 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'\r
996 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'\r
997 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'\r
998 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'\r
999 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'\r
1000 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'\r
1001 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )\r
1002\r
1003 plain = 'zipfile.py encryption test'\r
1004 plain2 = '\x00'*512\r
1005\r
1006 def setUp(self):\r
1007 with open(TESTFN, "wb") as fp:\r
1008 fp.write(self.data)\r
1009 self.zip = zipfile.ZipFile(TESTFN, "r")\r
1010 with open(TESTFN2, "wb") as fp:\r
1011 fp.write(self.data2)\r
1012 self.zip2 = zipfile.ZipFile(TESTFN2, "r")\r
1013\r
1014 def tearDown(self):\r
1015 self.zip.close()\r
1016 os.unlink(TESTFN)\r
1017 self.zip2.close()\r
1018 os.unlink(TESTFN2)\r
1019\r
1020 def test_no_password(self):\r
1021 # Reading the encrypted file without password\r
1022 # must generate a RunTime exception\r
1023 self.assertRaises(RuntimeError, self.zip.read, "test.txt")\r
1024 self.assertRaises(RuntimeError, self.zip2.read, "zero")\r
1025\r
1026 def test_bad_password(self):\r
1027 self.zip.setpassword("perl")\r
1028 self.assertRaises(RuntimeError, self.zip.read, "test.txt")\r
1029 self.zip2.setpassword("perl")\r
1030 self.assertRaises(RuntimeError, self.zip2.read, "zero")\r
1031\r
1032 @skipUnless(zlib, "requires zlib")\r
1033 def test_good_password(self):\r
1034 self.zip.setpassword("python")\r
1035 self.assertEqual(self.zip.read("test.txt"), self.plain)\r
1036 self.zip2.setpassword("12345")\r
1037 self.assertEqual(self.zip2.read("zero"), self.plain2)\r
1038\r
1039\r
1040class TestsWithRandomBinaryFiles(unittest.TestCase):\r
1041 def setUp(self):\r
1042 datacount = randint(16, 64)*1024 + randint(1, 1024)\r
1043 self.data = ''.join(struct.pack('<f', random()*randint(-1000, 1000))\r
1044 for i in xrange(datacount))\r
1045\r
1046 # Make a source file with some lines\r
1047 with open(TESTFN, "wb") as fp:\r
1048 fp.write(self.data)\r
1049\r
1050 def tearDown(self):\r
1051 unlink(TESTFN)\r
1052 unlink(TESTFN2)\r
1053\r
1054 def make_test_archive(self, f, compression):\r
1055 # Create the ZIP archive\r
1056 with zipfile.ZipFile(f, "w", compression) as zipfp:\r
1057 zipfp.write(TESTFN, "another.name")\r
1058 zipfp.write(TESTFN, TESTFN)\r
1059\r
1060 def zip_test(self, f, compression):\r
1061 self.make_test_archive(f, compression)\r
1062\r
1063 # Read the ZIP archive\r
1064 with zipfile.ZipFile(f, "r", compression) as zipfp:\r
1065 testdata = zipfp.read(TESTFN)\r
1066 self.assertEqual(len(testdata), len(self.data))\r
1067 self.assertEqual(testdata, self.data)\r
1068 self.assertEqual(zipfp.read("another.name"), self.data)\r
1069\r
1070 def test_stored(self):\r
1071 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1072 self.zip_test(f, zipfile.ZIP_STORED)\r
1073\r
1074 @skipUnless(zlib, "requires zlib")\r
1075 def test_deflated(self):\r
1076 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):\r
1077 self.zip_test(f, zipfile.ZIP_DEFLATED)\r
1078\r
1079 def zip_open_test(self, f, compression):\r
1080 self.make_test_archive(f, compression)\r
1081\r
1082 # Read the ZIP archive\r
1083 with zipfile.ZipFile(f, "r", compression) as zipfp:\r
1084 zipdata1 = []\r
1085 with zipfp.open(TESTFN) as zipopen1:\r
1086 while True:\r
1087 read_data = zipopen1.read(256)\r
1088 if not read_data:\r
1089 break\r
1090 zipdata1.append(read_data)\r
1091\r
1092 zipdata2 = []\r
1093 with zipfp.open("another.name") as zipopen2:\r
1094 while True:\r
1095 read_data = zipopen2.read(256)\r
1096 if not read_data:\r
1097 break\r
1098 zipdata2.append(read_data)\r
1099\r
1100 testdata1 = ''.join(zipdata1)\r
1101 self.assertEqual(len(testdata1), len(self.data))\r
1102 self.assertEqual(testdata1, self.data)\r
1103\r
1104 testdata2 = ''.join(zipdata2)\r
1105 self.assertEqual(len(testdata2), len(self.data))\r
1106 self.assertEqual(testdata2, self.data)\r
1107\r
1108 def test_open_stored(self):\r
1109 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1110 self.zip_open_test(f, zipfile.ZIP_STORED)\r
1111\r
1112 @skipUnless(zlib, "requires zlib")\r
1113 def test_open_deflated(self):\r
1114 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):\r
1115 self.zip_open_test(f, zipfile.ZIP_DEFLATED)\r
1116\r
1117 def zip_random_open_test(self, f, compression):\r
1118 self.make_test_archive(f, compression)\r
1119\r
1120 # Read the ZIP archive\r
1121 with zipfile.ZipFile(f, "r", compression) as zipfp:\r
1122 zipdata1 = []\r
1123 with zipfp.open(TESTFN) as zipopen1:\r
1124 while True:\r
1125 read_data = zipopen1.read(randint(1, 1024))\r
1126 if not read_data:\r
1127 break\r
1128 zipdata1.append(read_data)\r
1129\r
1130 testdata = ''.join(zipdata1)\r
1131 self.assertEqual(len(testdata), len(self.data))\r
1132 self.assertEqual(testdata, self.data)\r
1133\r
1134 def test_random_open_stored(self):\r
1135 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1136 self.zip_random_open_test(f, zipfile.ZIP_STORED)\r
1137\r
1138 @skipUnless(zlib, "requires zlib")\r
1139 def test_random_open_deflated(self):\r
1140 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):\r
1141 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)\r
1142\r
1143\r
1144@skipUnless(zlib, "requires zlib")\r
1145class TestsWithMultipleOpens(unittest.TestCase):\r
1146 def setUp(self):\r
1147 # Create the ZIP archive\r
1148 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:\r
1149 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)\r
1150 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)\r
1151\r
1152 def test_same_file(self):\r
1153 # Verify that (when the ZipFile is in control of creating file objects)\r
1154 # multiple open() calls can be made without interfering with each other.\r
1155 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:\r
1156 zopen1 = zipf.open('ones')\r
1157 zopen2 = zipf.open('ones')\r
1158 data1 = zopen1.read(500)\r
1159 data2 = zopen2.read(500)\r
1160 data1 += zopen1.read(500)\r
1161 data2 += zopen2.read(500)\r
1162 self.assertEqual(data1, data2)\r
1163\r
1164 def test_different_file(self):\r
1165 # Verify that (when the ZipFile is in control of creating file objects)\r
1166 # multiple open() calls can be made without interfering with each other.\r
1167 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:\r
1168 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:\r
1169 data1 = zopen1.read(500)\r
1170 data2 = zopen2.read(500)\r
1171 data1 += zopen1.read(500)\r
1172 data2 += zopen2.read(500)\r
1173 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)\r
1174 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)\r
1175\r
1176 def test_interleaved(self):\r
1177 # Verify that (when the ZipFile is in control of creating file objects)\r
1178 # multiple open() calls can be made without interfering with each other.\r
1179 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:\r
1180 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:\r
1181 data1 = zopen1.read(500)\r
1182 data2 = zopen2.read(500)\r
1183 data1 += zopen1.read(500)\r
1184 data2 += zopen2.read(500)\r
1185 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)\r
1186 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)\r
1187\r
1188 def tearDown(self):\r
1189 unlink(TESTFN2)\r
1190\r
1191\r
1192class TestWithDirectory(unittest.TestCase):\r
1193 def setUp(self):\r
1194 os.mkdir(TESTFN2)\r
1195\r
1196 def test_extract_dir(self):\r
1197 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:\r
1198 zipf.extractall(TESTFN2)\r
1199 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))\r
1200 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))\r
1201 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))\r
1202\r
1203 def test_bug_6050(self):\r
1204 # Extraction should succeed if directories already exist\r
1205 os.mkdir(os.path.join(TESTFN2, "a"))\r
1206 self.test_extract_dir()\r
1207\r
1208 def test_store_dir(self):\r
1209 os.mkdir(os.path.join(TESTFN2, "x"))\r
1210 zipf = zipfile.ZipFile(TESTFN, "w")\r
1211 zipf.write(os.path.join(TESTFN2, "x"), "x")\r
1212 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))\r
1213\r
1214 def tearDown(self):\r
1215 shutil.rmtree(TESTFN2)\r
1216 if os.path.exists(TESTFN):\r
1217 unlink(TESTFN)\r
1218\r
1219\r
1220class UniversalNewlineTests(unittest.TestCase):\r
1221 def setUp(self):\r
1222 self.line_gen = ["Test of zipfile line %d." % i\r
1223 for i in xrange(FIXEDTEST_SIZE)]\r
1224 self.seps = ('\r', '\r\n', '\n')\r
1225 self.arcdata, self.arcfiles = {}, {}\r
1226 for n, s in enumerate(self.seps):\r
1227 self.arcdata[s] = s.join(self.line_gen) + s\r
1228 self.arcfiles[s] = '%s-%d' % (TESTFN, n)\r
1229 open(self.arcfiles[s], "wb").write(self.arcdata[s])\r
1230\r
1231 def make_test_archive(self, f, compression):\r
1232 # Create the ZIP archive\r
1233 with zipfile.ZipFile(f, "w", compression) as zipfp:\r
1234 for fn in self.arcfiles.values():\r
1235 zipfp.write(fn, fn)\r
1236\r
1237 def read_test(self, f, compression):\r
1238 self.make_test_archive(f, compression)\r
1239\r
1240 # Read the ZIP archive\r
1241 with zipfile.ZipFile(f, "r") as zipfp:\r
1242 for sep, fn in self.arcfiles.items():\r
1243 with zipfp.open(fn, "rU") as fp:\r
1244 zipdata = fp.read()\r
1245 self.assertEqual(self.arcdata[sep], zipdata)\r
1246\r
1247 def readline_read_test(self, f, compression):\r
1248 self.make_test_archive(f, compression)\r
1249\r
1250 # Read the ZIP archive\r
1251 zipfp = zipfile.ZipFile(f, "r")\r
1252 for sep, fn in self.arcfiles.items():\r
1253 with zipfp.open(fn, "rU") as zipopen:\r
1254 data = ''\r
1255 while True:\r
1256 read = zipopen.readline()\r
1257 if not read:\r
1258 break\r
1259 data += read\r
1260\r
1261 read = zipopen.read(5)\r
1262 if not read:\r
1263 break\r
1264 data += read\r
1265\r
1266 self.assertEqual(data, self.arcdata['\n'])\r
1267\r
1268 zipfp.close()\r
1269\r
1270 def readline_test(self, f, compression):\r
1271 self.make_test_archive(f, compression)\r
1272\r
1273 # Read the ZIP archive\r
1274 with zipfile.ZipFile(f, "r") as zipfp:\r
1275 for sep, fn in self.arcfiles.items():\r
1276 with zipfp.open(fn, "rU") as zipopen:\r
1277 for line in self.line_gen:\r
1278 linedata = zipopen.readline()\r
1279 self.assertEqual(linedata, line + '\n')\r
1280\r
1281 def readlines_test(self, f, compression):\r
1282 self.make_test_archive(f, compression)\r
1283\r
1284 # Read the ZIP archive\r
1285 with zipfile.ZipFile(f, "r") as zipfp:\r
1286 for sep, fn in self.arcfiles.items():\r
1287 with zipfp.open(fn, "rU") as fp:\r
1288 ziplines = fp.readlines()\r
1289 for line, zipline in zip(self.line_gen, ziplines):\r
1290 self.assertEqual(zipline, line + '\n')\r
1291\r
1292 def iterlines_test(self, f, compression):\r
1293 self.make_test_archive(f, compression)\r
1294\r
1295 # Read the ZIP archive\r
1296 with zipfile.ZipFile(f, "r") as zipfp:\r
1297 for sep, fn in self.arcfiles.items():\r
1298 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):\r
1299 self.assertEqual(zipline, line + '\n')\r
1300\r
1301 def test_read_stored(self):\r
1302 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1303 self.read_test(f, zipfile.ZIP_STORED)\r
1304\r
1305 def test_readline_read_stored(self):\r
1306 # Issue #7610: calls to readline() interleaved with calls to read().\r
1307 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1308 self.readline_read_test(f, zipfile.ZIP_STORED)\r
1309\r
1310 def test_readline_stored(self):\r
1311 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1312 self.readline_test(f, zipfile.ZIP_STORED)\r
1313\r
1314 def test_readlines_stored(self):\r
1315 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1316 self.readlines_test(f, zipfile.ZIP_STORED)\r
1317\r
1318 def test_iterlines_stored(self):\r
1319 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1320 self.iterlines_test(f, zipfile.ZIP_STORED)\r
1321\r
1322 @skipUnless(zlib, "requires zlib")\r
1323 def test_read_deflated(self):\r
1324 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1325 self.read_test(f, zipfile.ZIP_DEFLATED)\r
1326\r
1327 @skipUnless(zlib, "requires zlib")\r
1328 def test_readline_read_deflated(self):\r
1329 # Issue #7610: calls to readline() interleaved with calls to read().\r
1330 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1331 self.readline_read_test(f, zipfile.ZIP_DEFLATED)\r
1332\r
1333 @skipUnless(zlib, "requires zlib")\r
1334 def test_readline_deflated(self):\r
1335 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1336 self.readline_test(f, zipfile.ZIP_DEFLATED)\r
1337\r
1338 @skipUnless(zlib, "requires zlib")\r
1339 def test_readlines_deflated(self):\r
1340 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1341 self.readlines_test(f, zipfile.ZIP_DEFLATED)\r
1342\r
1343 @skipUnless(zlib, "requires zlib")\r
1344 def test_iterlines_deflated(self):\r
1345 for f in (TESTFN2, TemporaryFile(), StringIO()):\r
1346 self.iterlines_test(f, zipfile.ZIP_DEFLATED)\r
1347\r
1348 def tearDown(self):\r
1349 for sep, fn in self.arcfiles.items():\r
1350 os.remove(fn)\r
1351 unlink(TESTFN)\r
1352 unlink(TESTFN2)\r
1353\r
1354\r
1355def test_main():\r
1356 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,\r
1357 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,\r
1358 TestWithDirectory, UniversalNewlineTests,\r
1359 TestsWithRandomBinaryFiles)\r
1360\r
1361if __name__ == "__main__":\r
1362 test_main()\r