blob: 3f9e9960b716de5d7ac3802f185f24f26da62f4c [file] [log] [blame]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001import sys
2import os
3import shutil
Georg Brandl38c6a222006-05-10 16:26:03 +00004import StringIO
Brett Cannon7eec2172007-05-30 22:24:28 +00005from hashlib import md5
Lars Gustäbelc64e4022007-03-13 10:47:19 +00006import errno
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00007
8import unittest
9import tarfile
10
11from test import test_support
Serhiy Storchaka7c7b4b52015-09-06 14:16:18 +030012from test import test_support as support
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000013
14# Check for our compression modules.
15try:
16 import gzip
Neal Norwitzae323192003-04-14 01:18:32 +000017 gzip.GzipFile
18except (ImportError, AttributeError):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000019 gzip = None
20try:
21 import bz2
22except ImportError:
23 bz2 = None
24
Lars Gustäbelc64e4022007-03-13 10:47:19 +000025def md5sum(data):
Brett Cannon7eec2172007-05-30 22:24:28 +000026 return md5(data).hexdigest()
Lars Gustäbelc64e4022007-03-13 10:47:19 +000027
Antoine Pitrou310c9fe2009-11-11 20:55:07 +000028TEMPDIR = os.path.abspath(test_support.TESTFN)
29tarname = test_support.findfile("testtar.tar")
Lars Gustäbelc64e4022007-03-13 10:47:19 +000030gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
31bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
32tmpname = os.path.join(TEMPDIR, "tmp.tar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000033
Lars Gustäbelc64e4022007-03-13 10:47:19 +000034md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
35md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000036
37
Lars Gustäbelc64e4022007-03-13 10:47:19 +000038class ReadTest(unittest.TestCase):
39
40 tarname = tarname
41 mode = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000042
43 def setUp(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +000044 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000045
46 def tearDown(self):
47 self.tar.close()
48
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000049
Lars Gustäbelc64e4022007-03-13 10:47:19 +000050class UstarReadTest(ReadTest):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000051
Lars Gustäbelc64e4022007-03-13 10:47:19 +000052 def test_fileobj_regular_file(self):
53 tarinfo = self.tar.getmember("ustar/regtype")
54 fobj = self.tar.extractfile(tarinfo)
55 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000056 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000057 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000058
Lars Gustäbelc64e4022007-03-13 10:47:19 +000059 def test_fileobj_readlines(self):
60 self.tar.extract("ustar/regtype", TEMPDIR)
61 tarinfo = self.tar.getmember("ustar/regtype")
62 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
Ezio Melotti07f24c52016-01-13 22:21:21 +020063 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rU") as fobj1:
64 lines1 = fobj1.readlines()
Lars Gustäbelc64e4022007-03-13 10:47:19 +000065 fobj2 = self.tar.extractfile(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000066
Lars Gustäbelc64e4022007-03-13 10:47:19 +000067 lines2 = fobj2.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000068 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000069 "fileobj.readlines() failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +000070 self.assertTrue(len(lines2) == 114,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000071 "fileobj.readlines() failed")
Florent Xiclunafc5f6a72010-03-20 22:26:42 +000072 self.assertTrue(lines2[83] ==
Lars Gustäbelc64e4022007-03-13 10:47:19 +000073 "I will gladly admit that Python is not the fastest running scripting language.\n",
74 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000075
Lars Gustäbelc64e4022007-03-13 10:47:19 +000076 def test_fileobj_iter(self):
77 self.tar.extract("ustar/regtype", TEMPDIR)
78 tarinfo = self.tar.getmember("ustar/regtype")
Ezio Melotti07f24c52016-01-13 22:21:21 +020079 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rU") as fobj1:
80 lines1 = fobj1.readlines()
Lars Gustäbelc64e4022007-03-13 10:47:19 +000081 fobj2 = self.tar.extractfile(tarinfo)
Lars Gustäbelc64e4022007-03-13 10:47:19 +000082 lines2 = [line for line in fobj2]
Benjamin Peterson5c8da862009-06-30 22:57:08 +000083 self.assertTrue(lines1 == lines2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +000084 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +000085
Lars Gustäbelc64e4022007-03-13 10:47:19 +000086 def test_fileobj_seek(self):
87 self.tar.extract("ustar/regtype", TEMPDIR)
Ezio Melotti07f24c52016-01-13 22:21:21 +020088 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
89 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +000090
Lars Gustäbelc64e4022007-03-13 10:47:19 +000091 tarinfo = self.tar.getmember("ustar/regtype")
92 fobj = self.tar.extractfile(tarinfo)
93
94 text = fobj.read()
95 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000096 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +000097 "seek() to file's start failed")
98 fobj.seek(2048, 0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000099 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000100 "seek() to absolute position failed")
101 fobj.seek(-1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000102 self.assertTrue(1024 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000103 "seek() to negative relative position failed")
104 fobj.seek(1024, 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000105 self.assertTrue(2048 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000106 "seek() to positive relative position failed")
107 s = fobj.read(10)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000108 self.assertTrue(s == data[2048:2058],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000109 "read() after seek failed")
110 fobj.seek(0, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000111 self.assertTrue(tarinfo.size == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000112 "seek() to file's end failed")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000113 self.assertTrue(fobj.read() == "",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000114 "read() at file's end did not return empty string")
115 fobj.seek(-tarinfo.size, 2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000116 self.assertTrue(0 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000117 "relative seek() to file's start failed")
118 fobj.seek(512)
119 s1 = fobj.readlines()
120 fobj.seek(512)
121 s2 = fobj.readlines()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000122 self.assertTrue(s1 == s2,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000123 "readlines() after seek failed")
124 fobj.seek(0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000125 self.assertTrue(len(fobj.readline()) == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000126 "tell() after readline() failed")
127 fobj.seek(512)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000128 self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000129 "tell() after seek() and readline() failed")
130 fobj.seek(0)
131 line = fobj.readline()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000132 self.assertTrue(fobj.read() == data[len(line):],
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000133 "read() after readline() failed")
134 fobj.close()
135
Lars Gustäbel4da7d412010-06-03 12:34:14 +0000136 # Test if symbolic and hard links are resolved by extractfile(). The
137 # test link members each point to a regular member whose data is
138 # supposed to be exported.
139 def _test_fileobj_link(self, lnktype, regtype):
140 a = self.tar.extractfile(lnktype)
141 b = self.tar.extractfile(regtype)
142 self.assertEqual(a.name, b.name)
143
144 def test_fileobj_link1(self):
145 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
146
147 def test_fileobj_link2(self):
148 self._test_fileobj_link("./ustar/linktest2/lnktype", "ustar/linktest1/regtype")
149
150 def test_fileobj_symlink1(self):
151 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
152
153 def test_fileobj_symlink2(self):
154 self._test_fileobj_link("./ustar/linktest2/symtype", "ustar/linktest1/regtype")
155
Lars Gustäbel231d4742012-04-24 22:42:08 +0200156 def test_issue14160(self):
157 self._test_fileobj_link("symtype2", "ustar/regtype")
158
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000159
Serhiy Storchakacfc2c7b2014-02-05 20:55:13 +0200160class ListTest(ReadTest, unittest.TestCase):
161
162 # Override setUp to use default encoding (UTF-8)
163 def setUp(self):
164 self.tar = tarfile.open(self.tarname, mode=self.mode)
165
166 def test_list(self):
167 with test_support.captured_stdout() as t:
168 self.tar.list(verbose=False)
169 out = t.getvalue()
170 self.assertIn('ustar/conttype', out)
171 self.assertIn('ustar/regtype', out)
172 self.assertIn('ustar/lnktype', out)
173 self.assertIn('ustar' + ('/12345' * 40) + '67/longname', out)
174 self.assertIn('./ustar/linktest2/symtype', out)
175 self.assertIn('./ustar/linktest2/lnktype', out)
176 # Make sure it puts trailing slash for directory
177 self.assertIn('ustar/dirtype/', out)
178 self.assertIn('ustar/dirtype-with-size/', out)
179 # Make sure it is able to print non-ASCII characters
180 self.assertIn('ustar/umlauts-'
181 '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out)
182 self.assertIn('misc/regtype-hpux-signed-chksum-'
183 '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out)
184 self.assertIn('misc/regtype-old-v7-signed-chksum-'
185 '\xc4\xd6\xdc\xe4\xf6\xfc\xdf', out)
186 # Make sure it prints files separated by one newline without any
187 # 'ls -l'-like accessories if verbose flag is not being used
188 # ...
189 # ustar/conttype
190 # ustar/regtype
191 # ...
192 self.assertRegexpMatches(out, r'ustar/conttype ?\r?\n'
193 r'ustar/regtype ?\r?\n')
194 # Make sure it does not print the source of link without verbose flag
195 self.assertNotIn('link to', out)
196 self.assertNotIn('->', out)
197
198 def test_list_verbose(self):
199 with test_support.captured_stdout() as t:
200 self.tar.list(verbose=True)
201 out = t.getvalue()
202 # Make sure it prints files separated by one newline with 'ls -l'-like
203 # accessories if verbose flag is being used
204 # ...
205 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
206 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
207 # ...
208 self.assertRegexpMatches(out, (r'-rw-r--r-- tarfile/tarfile\s+7011 '
209 r'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
210 r'ustar/\w+type ?\r?\n') * 2)
211 # Make sure it prints the source of link with verbose flag
212 self.assertIn('ustar/symtype -> regtype', out)
213 self.assertIn('./ustar/linktest2/symtype -> ../linktest1/regtype', out)
214 self.assertIn('./ustar/linktest2/lnktype link to '
215 './ustar/linktest1/regtype', out)
216 self.assertIn('gnu' + ('/123' * 125) + '/longlink link to gnu' +
217 ('/123' * 125) + '/longname', out)
218 self.assertIn('pax' + ('/123' * 125) + '/longlink link to pax' +
219 ('/123' * 125) + '/longname', out)
220
221
222class GzipListTest(ListTest):
223 tarname = gzipname
224 mode = "r:gz"
225 taropen = tarfile.TarFile.gzopen
226
227
228class Bz2ListTest(ListTest):
229 tarname = bz2name
230 mode = "r:bz2"
231 taropen = tarfile.TarFile.bz2open
232
233
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000234class CommonReadTest(ReadTest):
235
236 def test_empty_tarfile(self):
237 # Test for issue6123: Allow opening empty archives.
238 # This test checks if tarfile.open() is able to open an empty tar
239 # archive successfully. Note that an empty tar archive is not the
240 # same as an empty file!
Ezio Melotti07f24c52016-01-13 22:21:21 +0200241 with tarfile.open(tmpname, self.mode.replace("r", "w")):
242 pass
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000243 try:
244 tar = tarfile.open(tmpname, self.mode)
245 tar.getnames()
246 except tarfile.ReadError:
247 self.fail("tarfile.open() failed on empty archive")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200248 else:
249 self.assertListEqual(tar.getmembers(), [])
250 finally:
251 tar.close()
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000252
253 def test_null_tarfile(self):
254 # Test for issue6123: Allow opening empty archives.
255 # This test guarantees that tarfile.open() does not treat an empty
256 # file as an empty tar archive.
Ezio Melotti07f24c52016-01-13 22:21:21 +0200257 with open(tmpname, "wb"):
258 pass
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000259 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
260 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
261
Serhiy Storchakad804f532014-01-13 19:08:51 +0200262 def test_non_existent_tarfile(self):
263 # Test for issue11513: prevent non-existent gzipped tarfiles raising
264 # multiple exceptions.
265 exctype = OSError if '|' in self.mode else IOError
266 with self.assertRaisesRegexp(exctype, "xxx") as ex:
267 tarfile.open("xxx", self.mode)
268 self.assertEqual(ex.exception.errno, errno.ENOENT)
269
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000270 def test_ignore_zeros(self):
271 # Test TarFile's ignore_zeros option.
272 if self.mode.endswith(":gz"):
273 _open = gzip.GzipFile
274 elif self.mode.endswith(":bz2"):
275 _open = bz2.BZ2File
276 else:
277 _open = open
278
279 for char in ('\0', 'a'):
280 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
281 # are ignored correctly.
Ezio Melotti07f24c52016-01-13 22:21:21 +0200282 with _open(tmpname, "wb") as fobj:
283 fobj.write(char * 1024)
284 fobj.write(tarfile.TarInfo("foo").tobuf())
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000285
286 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200287 try:
288 self.assertListEqual(tar.getnames(), ["foo"],
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000289 "ignore_zeros=True should have skipped the %r-blocks" % char)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200290 finally:
291 tar.close()
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000292
Lars Gustäbel518602a2015-07-06 09:23:04 +0200293 def test_premature_end_of_archive(self):
294 for size in (512, 600, 1024, 1200):
295 with tarfile.open(tmpname, "w:") as tar:
296 t = tarfile.TarInfo("foo")
297 t.size = 1024
298 tar.addfile(t, StringIO.StringIO("a" * 1024))
299
300 with open(tmpname, "r+b") as fobj:
301 fobj.truncate(size)
302
303 with tarfile.open(tmpname) as tar:
304 with self.assertRaisesRegexp(tarfile.ReadError, "unexpected end of data"):
305 for t in tar:
306 pass
307
308 with tarfile.open(tmpname) as tar:
309 t = tar.next()
310
311 with self.assertRaisesRegexp(tarfile.ReadError, "unexpected end of data"):
312 tar.extract(t, TEMPDIR)
313
314 with self.assertRaisesRegexp(tarfile.ReadError, "unexpected end of data"):
315 tar.extractfile(t).read()
316
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000317
318class MiscReadTest(CommonReadTest):
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +0200319 taropen = tarfile.TarFile.taropen
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000320
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000321 def test_no_name_argument(self):
Ezio Melotti07f24c52016-01-13 22:21:21 +0200322 with open(self.tarname, "rb") as fobj:
323 tar = tarfile.open(fileobj=fobj, mode=self.mode)
324 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000325
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000326 def test_no_name_attribute(self):
Ezio Melotti07f24c52016-01-13 22:21:21 +0200327 with open(self.tarname, "rb") as fobj:
328 data = fobj.read()
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000329 fobj = StringIO.StringIO(data)
330 self.assertRaises(AttributeError, getattr, fobj, "name")
331 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchaka7cc3b0a2014-07-22 10:39:59 +0300332 self.assertEqual(tar.name, None)
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000333
334 def test_empty_name_attribute(self):
Ezio Melotti07f24c52016-01-13 22:21:21 +0200335 with open(self.tarname, "rb") as fobj:
336 data = fobj.read()
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000337 fobj = StringIO.StringIO(data)
338 fobj.name = ""
339 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchaka7cc3b0a2014-07-22 10:39:59 +0300340 self.assertEqual(tar.name, None)
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000341
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +0200342 def test_illegal_mode_arg(self):
343 with open(tmpname, 'wb'):
344 pass
345 self.addCleanup(os.unlink, tmpname)
346 with self.assertRaisesRegexp(ValueError, 'mode must be '):
347 tar = self.taropen(tmpname, 'q')
348 with self.assertRaisesRegexp(ValueError, 'mode must be '):
349 tar = self.taropen(tmpname, 'rw')
350 with self.assertRaisesRegexp(ValueError, 'mode must be '):
351 tar = self.taropen(tmpname, '')
352
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000353 def test_fileobj_with_offset(self):
354 # Skip the first member and store values from the second member
355 # of the testtar.
356 tar = tarfile.open(self.tarname, mode=self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200357 try:
358 tar.next()
359 t = tar.next()
360 name = t.name
361 offset = t.offset
362 data = tar.extractfile(t).read()
363 finally:
364 tar.close()
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000365
366 # Open the testtar and seek to the offset of the second member.
367 if self.mode.endswith(":gz"):
368 _open = gzip.GzipFile
369 elif self.mode.endswith(":bz2"):
370 _open = bz2.BZ2File
371 else:
372 _open = open
373 fobj = _open(self.tarname, "rb")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200374 try:
375 fobj.seek(offset)
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000376
Ezio Melotti07f24c52016-01-13 22:21:21 +0200377 # Test if the tarfile starts with the second member.
378 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
379 t = tar.next()
380 self.assertEqual(t.name, name)
381 # Read to the end of fileobj and test if seeking back to the
382 # beginning works.
383 tar.getmembers()
384 self.assertEqual(tar.extractfile(t).read(), data,
385 "seek back did not work")
386 tar.close()
387 finally:
388 fobj.close()
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000389
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000390 def test_fail_comp(self):
391 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
392 if self.mode == "r:":
Zachary Ware1f702212013-12-10 14:09:20 -0600393 self.skipTest('needs a gz or bz2 mode')
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000394 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200395 with open(tarname, "rb") as fobj:
396 self.assertRaises(tarfile.ReadError, tarfile.open,
397 fileobj=fobj, mode=self.mode)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000398
399 def test_v7_dirtype(self):
400 # Test old style dirtype member (bug #1336623):
401 # Old V7 tars create directory members using an AREGTYPE
402 # header with a "/" appended to the filename field.
403 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000404 self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000405 "v7 dirtype failed")
406
Lars Gustäbel6bf51da2008-02-11 19:17:10 +0000407 def test_xstar_type(self):
408 # The xstar format stores extra atime and ctime fields inside the
409 # space reserved for the prefix field. The prefix field must be
410 # ignored in this case, otherwise it will mess up the name.
411 try:
412 self.tar.getmember("misc/regtype-xstar")
413 except KeyError:
414 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
415
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000416 def test_check_members(self):
417 for tarinfo in self.tar:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000418 self.assertTrue(int(tarinfo.mtime) == 07606136617,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000419 "wrong mtime for %s" % tarinfo.name)
420 if not tarinfo.name.startswith("ustar/"):
421 continue
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000422 self.assertTrue(tarinfo.uname == "tarfile",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000423 "wrong uname for %s" % tarinfo.name)
424
425 def test_find_members(self):
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000426 self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000427 "could not find all members")
428
429 def test_extract_hardlink(self):
430 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200431 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
432 tar.extract("ustar/regtype", TEMPDIR)
433 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000434
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000435 tar.extract("ustar/lnktype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200436 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
437 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
438 data = f.read()
439 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000440
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000441 tar.extract("ustar/symtype", TEMPDIR)
Serhiy Storchaka421489f2012-12-30 20:15:10 +0200442 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
443 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
444 data = f.read()
445 self.assertEqual(md5sum(data), md5_regtype)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000446
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000447 def test_extractall(self):
448 # Test if extractall() correctly restores directory permissions
449 # and times (see issue1735).
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000450 tar = tarfile.open(tarname, encoding="iso8859-1")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200451 try:
452 directories = [t for t in tar if t.isdir()]
453 tar.extractall(TEMPDIR, directories)
454 for tarinfo in directories:
455 path = os.path.join(TEMPDIR, tarinfo.name)
456 if sys.platform != "win32":
457 # Win32 has no support for fine grained permissions.
458 self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
459 self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
460 finally:
461 tar.close()
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000462
Lars Gustäbel12adc652009-11-23 15:46:19 +0000463 def test_init_close_fobj(self):
464 # Issue #7341: Close the internal file object in the TarFile
465 # constructor in case of an error. For the test we rely on
466 # the fact that opening an empty file raises a ReadError.
467 empty = os.path.join(TEMPDIR, "empty")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200468 with open(empty, "wb") as fobj:
469 fobj.write("")
Lars Gustäbel12adc652009-11-23 15:46:19 +0000470
471 try:
472 tar = object.__new__(tarfile.TarFile)
473 try:
474 tar.__init__(empty)
475 except tarfile.ReadError:
476 self.assertTrue(tar.fileobj.closed)
477 else:
478 self.fail("ReadError not raised")
479 finally:
Ezio Melotti07f24c52016-01-13 22:21:21 +0200480 support.unlink(empty)
Lars Gustäbel12adc652009-11-23 15:46:19 +0000481
Serhiy Storchakace34ba62013-05-09 14:22:05 +0300482 def test_parallel_iteration(self):
483 # Issue #16601: Restarting iteration over tarfile continued
484 # from where it left off.
485 with tarfile.open(self.tarname) as tar:
486 for m1, m2 in zip(tar, tar):
487 self.assertEqual(m1.offset, m2.offset)
488 self.assertEqual(m1.name, m2.name)
489
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000490
Lars Gustäbeldd866d52009-11-22 18:30:53 +0000491class StreamReadTest(CommonReadTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000492
493 mode="r|"
494
495 def test_fileobj_regular_file(self):
496 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
497 fobj = self.tar.extractfile(tarinfo)
498 data = fobj.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000499 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000500 "regular file extraction failed")
501
502 def test_provoke_stream_error(self):
503 tarinfos = self.tar.getmembers()
504 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000505 self.assertRaises(tarfile.StreamError, f.read)
506
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000507 def test_compare_members(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000508 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200509 try:
510 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000511
Ezio Melotti07f24c52016-01-13 22:21:21 +0200512 while True:
513 t1 = tar1.next()
514 t2 = tar2.next()
515 if t1 is None:
516 break
517 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000518
Ezio Melotti07f24c52016-01-13 22:21:21 +0200519 if t2.islnk() or t2.issym():
520 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
521 continue
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000522
Ezio Melotti07f24c52016-01-13 22:21:21 +0200523 v1 = tar1.extractfile(t1)
524 v2 = tar2.extractfile(t2)
525 if v1 is None:
526 continue
527 self.assertTrue(v2 is not None, "stream.extractfile() failed")
528 self.assertTrue(v1.read() == v2.read(), "stream extraction failed")
529 finally:
530 tar1.close()
Lars Gustäbela4b23812006-12-23 17:57:23 +0000531
Georg Brandla32e0a02006-10-24 16:54:16 +0000532
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000533class DetectReadTest(unittest.TestCase):
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000534
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000535 def _testfunc_file(self, name, mode):
536 try:
Ezio Melotti07f24c52016-01-13 22:21:21 +0200537 tar = tarfile.open(name, mode)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000538 except tarfile.ReadError:
539 self.fail()
Ezio Melotti07f24c52016-01-13 22:21:21 +0200540 else:
541 tar.close()
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000542
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000543 def _testfunc_fileobj(self, name, mode):
544 try:
Ezio Melotti07f24c52016-01-13 22:21:21 +0200545 tar = tarfile.open(name, mode, fileobj=open(name, "rb"))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000546 except tarfile.ReadError:
547 self.fail()
Ezio Melotti07f24c52016-01-13 22:21:21 +0200548 else:
549 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000550
551 def _test_modes(self, testfunc):
552 testfunc(tarname, "r")
553 testfunc(tarname, "r:")
554 testfunc(tarname, "r:*")
555 testfunc(tarname, "r|")
556 testfunc(tarname, "r|*")
557
558 if gzip:
559 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
560 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
561 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
562 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
563
564 testfunc(gzipname, "r")
565 testfunc(gzipname, "r:*")
566 testfunc(gzipname, "r:gz")
567 testfunc(gzipname, "r|*")
568 testfunc(gzipname, "r|gz")
569
570 if bz2:
571 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
572 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
573 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
574 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
575
576 testfunc(bz2name, "r")
577 testfunc(bz2name, "r:*")
578 testfunc(bz2name, "r:bz2")
579 testfunc(bz2name, "r|*")
580 testfunc(bz2name, "r|bz2")
581
582 def test_detect_file(self):
583 self._test_modes(self._testfunc_file)
584
585 def test_detect_fileobj(self):
586 self._test_modes(self._testfunc_fileobj)
587
Zachary Ware1f702212013-12-10 14:09:20 -0600588 @unittest.skipUnless(bz2, 'requires bz2')
Lars Gustäbel9a388632011-12-06 13:07:09 +0100589 def test_detect_stream_bz2(self):
590 # Originally, tarfile's stream detection looked for the string
591 # "BZh91" at the start of the file. This is incorrect because
592 # the '9' represents the blocksize (900kB). If the file was
593 # compressed using another blocksize autodetection fails.
Lars Gustäbel9a388632011-12-06 13:07:09 +0100594 with open(tarname, "rb") as fobj:
595 data = fobj.read()
596
597 # Compress with blocksize 100kB, the file starts with "BZh11".
598 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
599 fobj.write(data)
600
601 self._testfunc_file(tmpname, "r|*")
602
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000603
604class MemberReadTest(ReadTest):
605
606 def _test_member(self, tarinfo, chksum=None, **kwargs):
607 if chksum is not None:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000608 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000609 "wrong md5sum for %s" % tarinfo.name)
610
611 kwargs["mtime"] = 07606136617
612 kwargs["uid"] = 1000
613 kwargs["gid"] = 100
614 if "old-v7" not in tarinfo.name:
615 # V7 tar can't handle alphabetic owners.
616 kwargs["uname"] = "tarfile"
617 kwargs["gname"] = "tarfile"
618 for k, v in kwargs.iteritems():
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000619 self.assertTrue(getattr(tarinfo, k) == v,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000620 "wrong value in %s field of %s" % (k, tarinfo.name))
621
622 def test_find_regtype(self):
623 tarinfo = self.tar.getmember("ustar/regtype")
624 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
625
626 def test_find_conttype(self):
627 tarinfo = self.tar.getmember("ustar/conttype")
628 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
629
630 def test_find_dirtype(self):
631 tarinfo = self.tar.getmember("ustar/dirtype")
632 self._test_member(tarinfo, size=0)
633
634 def test_find_dirtype_with_size(self):
635 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
636 self._test_member(tarinfo, size=255)
637
638 def test_find_lnktype(self):
639 tarinfo = self.tar.getmember("ustar/lnktype")
640 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
641
642 def test_find_symtype(self):
643 tarinfo = self.tar.getmember("ustar/symtype")
644 self._test_member(tarinfo, size=0, linkname="regtype")
645
646 def test_find_blktype(self):
647 tarinfo = self.tar.getmember("ustar/blktype")
648 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
649
650 def test_find_chrtype(self):
651 tarinfo = self.tar.getmember("ustar/chrtype")
652 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
653
654 def test_find_fifotype(self):
655 tarinfo = self.tar.getmember("ustar/fifotype")
656 self._test_member(tarinfo, size=0)
657
658 def test_find_sparse(self):
659 tarinfo = self.tar.getmember("ustar/sparse")
660 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
661
662 def test_find_umlauts(self):
Ezio Melotti8861b292016-01-13 19:36:49 +0200663 tarinfo = self.tar.getmember("ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000664 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
665
666 def test_find_ustar_longname(self):
667 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Ezio Melottiaa980582010-01-23 23:04:36 +0000668 self.assertIn(name, self.tar.getnames())
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000669
670 def test_find_regtype_oldv7(self):
671 tarinfo = self.tar.getmember("misc/regtype-old-v7")
672 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
673
674 def test_find_pax_umlauts(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000675 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Ezio Melotti8861b292016-01-13 19:36:49 +0200676 tarinfo = self.tar.getmember("pax/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000677 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
678
679
680class LongnameTest(ReadTest):
681
682 def test_read_longname(self):
683 # Test reading of longname (bug #1471427).
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000684 longname = self.subdir + "/" + "123/" * 125 + "longname"
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000685 try:
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000686 tarinfo = self.tar.getmember(longname)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000687 except KeyError:
688 self.fail("longname not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000689 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000690
691 def test_read_longlink(self):
692 longname = self.subdir + "/" + "123/" * 125 + "longname"
693 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
694 try:
695 tarinfo = self.tar.getmember(longlink)
696 except KeyError:
697 self.fail("longlink not found")
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000698 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000699
700 def test_truncated_longname(self):
701 longname = self.subdir + "/" + "123/" * 125 + "longname"
702 tarinfo = self.tar.getmember(longname)
703 offset = tarinfo.offset
704 self.tar.fileobj.seek(offset)
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000705 fobj = StringIO.StringIO(self.tar.fileobj.read(3 * 512))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000706 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
707
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000708 def test_header_offset(self):
709 # Test if the start offset of the TarInfo object includes
710 # the preceding extended header.
711 longname = self.subdir + "/" + "123/" * 125 + "longname"
712 offset = self.tar.getmember(longname).offset
713 fobj = open(tarname)
714 fobj.seek(offset)
715 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512))
716 self.assertEqual(tarinfo.type, self.longnametype)
717
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000718
719class GNUReadTest(LongnameTest):
720
721 subdir = "gnu"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000722 longnametype = tarfile.GNUTYPE_LONGNAME
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000723
724 def test_sparse_file(self):
725 tarinfo1 = self.tar.getmember("ustar/sparse")
726 fobj1 = self.tar.extractfile(tarinfo1)
727 tarinfo2 = self.tar.getmember("gnu/sparse")
728 fobj2 = self.tar.extractfile(tarinfo2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000729 self.assertTrue(fobj1.read() == fobj2.read(),
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000730 "sparse file extraction failed")
731
732
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000733class PaxReadTest(LongnameTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000734
735 subdir = "pax"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000736 longnametype = tarfile.XHDTYPE
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000737
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000738 def test_pax_global_headers(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000739 tar = tarfile.open(tarname, encoding="iso8859-1")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200740 try:
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000741
Ezio Melotti07f24c52016-01-13 22:21:21 +0200742 tarinfo = tar.getmember("pax/regtype1")
743 self.assertEqual(tarinfo.uname, "foo")
744 self.assertEqual(tarinfo.gname, "bar")
745 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000746
Ezio Melotti07f24c52016-01-13 22:21:21 +0200747 tarinfo = tar.getmember("pax/regtype2")
748 self.assertEqual(tarinfo.uname, "")
749 self.assertEqual(tarinfo.gname, "bar")
750 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000751
Ezio Melotti07f24c52016-01-13 22:21:21 +0200752 tarinfo = tar.getmember("pax/regtype3")
753 self.assertEqual(tarinfo.uname, "tarfile")
754 self.assertEqual(tarinfo.gname, "tarfile")
755 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
756 finally:
757 tar.close()
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000758
759 def test_pax_number_fields(self):
760 # All following number fields are read from the pax header.
761 tar = tarfile.open(tarname, encoding="iso8859-1")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200762 try:
763 tarinfo = tar.getmember("pax/regtype4")
764 self.assertEqual(tarinfo.size, 7011)
765 self.assertEqual(tarinfo.uid, 123)
766 self.assertEqual(tarinfo.gid, 123)
767 self.assertEqual(tarinfo.mtime, 1041808783.0)
768 self.assertEqual(type(tarinfo.mtime), float)
769 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
770 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
771 finally:
772 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000773
774
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000775class WriteTestBase(unittest.TestCase):
776 # Put all write tests in here that are supposed to be tested
777 # in all possible mode combinations.
778
779 def test_fileobj_no_close(self):
780 fobj = StringIO.StringIO()
781 tar = tarfile.open(fileobj=fobj, mode=self.mode)
782 tar.addfile(tarfile.TarInfo("foo"))
783 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000784 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Serhiy Storchakacdf1ebd2014-01-18 15:54:32 +0200785 # Issue #20238: Incomplete gzip output with mode="w:gz"
786 data = fobj.getvalue()
787 del tar
788 test_support.gc_collect()
789 self.assertFalse(fobj.closed)
790 self.assertEqual(data, fobj.getvalue())
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000791
792
793class WriteTest(WriteTestBase):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000794
795 mode = "w:"
796
797 def test_100_char_name(self):
798 # The name field in a tar header stores strings of at most 100 chars.
799 # If a string is shorter than 100 chars it has to be padded with '\0',
800 # which implies that a string of exactly 100 chars is stored without
801 # a trailing '\0'.
802 name = "0123456789" * 10
803 tar = tarfile.open(tmpname, self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200804 try:
805 t = tarfile.TarInfo(name)
806 tar.addfile(t)
807 finally:
808 tar.close()
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000809
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000810 tar = tarfile.open(tmpname)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200811 try:
812 self.assertTrue(tar.getnames()[0] == name,
813 "failed to store 100 char filename")
814 finally:
815 tar.close()
Georg Brandla32e0a02006-10-24 16:54:16 +0000816
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000817 def test_tar_size(self):
818 # Test for bug #1013882.
819 tar = tarfile.open(tmpname, self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200820 try:
821 path = os.path.join(TEMPDIR, "file")
822 with open(path, "wb") as fobj:
823 fobj.write("aaa")
824 tar.add(path)
825 finally:
826 tar.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000827 self.assertTrue(os.path.getsize(tmpname) > 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000828 "tarfile is empty")
Georg Brandla32e0a02006-10-24 16:54:16 +0000829
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000830 # The test_*_size tests test for bug #1167128.
831 def test_file_size(self):
832 tar = tarfile.open(tmpname, self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200833 try:
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000834
Ezio Melotti07f24c52016-01-13 22:21:21 +0200835 path = os.path.join(TEMPDIR, "file")
836 with open(path, "wb"):
837 pass
838 tarinfo = tar.gettarinfo(path)
839 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000840
Ezio Melotti07f24c52016-01-13 22:21:21 +0200841 with open(path, "wb") as fobj:
842 fobj.write("aaa")
843 tarinfo = tar.gettarinfo(path)
844 self.assertEqual(tarinfo.size, 3)
845 finally:
846 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000847
848 def test_directory_size(self):
849 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000850 os.mkdir(path)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000851 try:
852 tar = tarfile.open(tmpname, self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200853 try:
854 tarinfo = tar.gettarinfo(path)
855 self.assertEqual(tarinfo.size, 0)
856 finally:
857 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000858 finally:
859 os.rmdir(path)
860
861 def test_link_size(self):
862 if hasattr(os, "link"):
863 link = os.path.join(TEMPDIR, "link")
864 target = os.path.join(TEMPDIR, "link_target")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200865 with open(target, "wb") as fobj:
866 fobj.write("aaa")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000867 os.link(target, link)
868 try:
869 tar = tarfile.open(tmpname, self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200870 try:
871 # Record the link target in the inodes list.
872 tar.gettarinfo(target)
873 tarinfo = tar.gettarinfo(link)
874 self.assertEqual(tarinfo.size, 0)
875 finally:
876 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000877 finally:
878 os.remove(target)
879 os.remove(link)
880
881 def test_symlink_size(self):
882 if hasattr(os, "symlink"):
883 path = os.path.join(TEMPDIR, "symlink")
884 os.symlink("link_target", path)
885 try:
886 tar = tarfile.open(tmpname, self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200887 try:
888 tarinfo = tar.gettarinfo(path)
889 self.assertEqual(tarinfo.size, 0)
890 finally:
891 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000892 finally:
893 os.remove(path)
894
895 def test_add_self(self):
896 # Test for #1257255.
897 dstname = os.path.abspath(tmpname)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000898 tar = tarfile.open(tmpname, self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200899 try:
900 self.assertTrue(tar.name == dstname, "archive name must be absolute")
901 tar.add(dstname)
902 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000903
Ezio Melotti07f24c52016-01-13 22:21:21 +0200904 cwd = os.getcwd()
905 os.chdir(TEMPDIR)
906 tar.add(dstname)
907 os.chdir(cwd)
908 self.assertTrue(tar.getnames() == [], "added the archive to itself")
909 finally:
910 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000911
Lars Gustäbel104490e2007-06-18 11:42:11 +0000912 def test_exclude(self):
913 tempdir = os.path.join(TEMPDIR, "exclude")
914 os.mkdir(tempdir)
915 try:
916 for name in ("foo", "bar", "baz"):
917 name = os.path.join(tempdir, name)
918 open(name, "wb").close()
919
Florent Xiclunafc5f6a72010-03-20 22:26:42 +0000920 exclude = os.path.isfile
Lars Gustäbel104490e2007-06-18 11:42:11 +0000921
922 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200923 try:
924 with test_support.check_warnings(("use the filter argument",
925 DeprecationWarning)):
926 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
927 finally:
928 tar.close()
Lars Gustäbel104490e2007-06-18 11:42:11 +0000929
930 tar = tarfile.open(tmpname, "r")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200931 try:
932 self.assertEqual(len(tar.getmembers()), 1)
933 self.assertEqual(tar.getnames()[0], "empty_dir")
934 finally:
935 tar.close()
Lars Gustäbel104490e2007-06-18 11:42:11 +0000936 finally:
937 shutil.rmtree(tempdir)
938
Lars Gustäbel21121e62009-09-12 10:28:15 +0000939 def test_filter(self):
940 tempdir = os.path.join(TEMPDIR, "filter")
941 os.mkdir(tempdir)
942 try:
943 for name in ("foo", "bar", "baz"):
944 name = os.path.join(tempdir, name)
945 open(name, "wb").close()
946
947 def filter(tarinfo):
948 if os.path.basename(tarinfo.name) == "bar":
949 return
950 tarinfo.uid = 123
951 tarinfo.uname = "foo"
952 return tarinfo
953
954 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200955 try:
956 tar.add(tempdir, arcname="empty_dir", filter=filter)
957 finally:
958 tar.close()
Lars Gustäbel21121e62009-09-12 10:28:15 +0000959
960 tar = tarfile.open(tmpname, "r")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200961 try:
962 for tarinfo in tar:
963 self.assertEqual(tarinfo.uid, 123)
964 self.assertEqual(tarinfo.uname, "foo")
965 self.assertEqual(len(tar.getmembers()), 3)
966 finally:
967 tar.close()
Lars Gustäbel21121e62009-09-12 10:28:15 +0000968 finally:
969 shutil.rmtree(tempdir)
970
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000971 # Guarantee that stored pathnames are not modified. Don't
972 # remove ./ or ../ or double slashes. Still make absolute
973 # pathnames relative.
974 # For details see bug #6054.
975 def _test_pathname(self, path, cmp_path=None, dir=False):
976 # Create a tarfile with an empty member named path
977 # and compare the stored name with the original.
978 foo = os.path.join(TEMPDIR, "foo")
979 if not dir:
980 open(foo, "w").close()
981 else:
982 os.mkdir(foo)
983
984 tar = tarfile.open(tmpname, self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +0200985 try:
986 tar.add(foo, arcname=path)
987 finally:
988 tar.close()
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000989
990 tar = tarfile.open(tmpname, "r")
Ezio Melotti07f24c52016-01-13 22:21:21 +0200991 try:
992 t = tar.next()
993 finally:
994 tar.close()
Lars Gustäbelf7cda522009-08-28 19:23:44 +0000995
996 if not dir:
997 os.remove(foo)
998 else:
999 os.rmdir(foo)
1000
1001 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1002
1003 def test_pathnames(self):
1004 self._test_pathname("foo")
1005 self._test_pathname(os.path.join("foo", ".", "bar"))
1006 self._test_pathname(os.path.join("foo", "..", "bar"))
1007 self._test_pathname(os.path.join(".", "foo"))
1008 self._test_pathname(os.path.join(".", "foo", "."))
1009 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1010 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1011 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1012 self._test_pathname(os.path.join("..", "foo"))
1013 self._test_pathname(os.path.join("..", "foo", ".."))
1014 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1015 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1016
1017 self._test_pathname("foo" + os.sep + os.sep + "bar")
1018 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1019
1020 def test_abs_pathnames(self):
1021 if sys.platform == "win32":
1022 self._test_pathname("C:\\foo", "foo")
1023 else:
1024 self._test_pathname("/foo", "foo")
1025 self._test_pathname("///foo", "foo")
1026
1027 def test_cwd(self):
1028 # Test adding the current working directory.
Serhiy Storchaka7c7b4b52015-09-06 14:16:18 +03001029 with support.change_cwd(TEMPDIR):
Lars Gustäbelf7cda522009-08-28 19:23:44 +00001030 tar = tarfile.open(tmpname, self.mode)
Ezio Melotti07f24c52016-01-13 22:21:21 +02001031 try:
1032 tar.add(".")
1033 finally:
1034 tar.close()
Lars Gustäbelf7cda522009-08-28 19:23:44 +00001035
1036 tar = tarfile.open(tmpname, "r")
Ezio Melotti07f24c52016-01-13 22:21:21 +02001037 try:
1038 for t in tar:
1039 self.assertTrue(t.name == "." or t.name.startswith("./"))
1040 finally:
1041 tar.close()
Lars Gustäbelf7cda522009-08-28 19:23:44 +00001042
Senthil Kumaranf3eb7d32011-04-28 17:00:19 +08001043 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
Senthil Kumaran011525e2011-04-28 15:30:31 +08001044 def test_extractall_symlinks(self):
1045 # Test if extractall works properly when tarfile contains symlinks
1046 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1047 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1048 os.mkdir(tempdir)
1049 try:
1050 source_file = os.path.join(tempdir,'source')
1051 target_file = os.path.join(tempdir,'symlink')
1052 with open(source_file,'w') as f:
1053 f.write('something\n')
1054 os.symlink(source_file, target_file)
1055 tar = tarfile.open(temparchive,'w')
1056 tar.add(source_file, arcname=os.path.basename(source_file))
1057 tar.add(target_file, arcname=os.path.basename(target_file))
1058 tar.close()
1059 # Let's extract it to the location which contains the symlink
1060 tar = tarfile.open(temparchive,'r')
1061 # this should not raise OSError: [Errno 17] File exists
1062 try:
1063 tar.extractall(path=tempdir)
1064 except OSError:
1065 self.fail("extractall failed with symlinked files")
1066 finally:
1067 tar.close()
1068 finally:
1069 os.unlink(temparchive)
1070 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001071
Senthil Kumaran4dd89ce2011-05-17 10:12:18 +08001072 @unittest.skipUnless(hasattr(os, 'symlink'), "needs os.symlink")
1073 def test_extractall_broken_symlinks(self):
1074 # Test if extractall works properly when tarfile contains broken
1075 # symlinks
1076 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1077 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1078 os.mkdir(tempdir)
1079 try:
1080 source_file = os.path.join(tempdir,'source')
1081 target_file = os.path.join(tempdir,'symlink')
1082 with open(source_file,'w') as f:
1083 f.write('something\n')
1084 os.symlink(source_file, target_file)
1085 tar = tarfile.open(temparchive,'w')
1086 tar.add(target_file, arcname=os.path.basename(target_file))
1087 tar.close()
1088 # remove the real file
1089 os.unlink(source_file)
1090 # Let's extract it to the location which contains the symlink
1091 tar = tarfile.open(temparchive,'r')
1092 # this should not raise OSError: [Errno 17] File exists
1093 try:
1094 tar.extractall(path=tempdir)
1095 except OSError:
1096 self.fail("extractall failed with broken symlinked files")
1097 finally:
1098 tar.close()
1099 finally:
1100 os.unlink(temparchive)
1101 shutil.rmtree(tempdir)
1102
1103 @unittest.skipUnless(hasattr(os, 'link'), "needs os.link")
1104 def test_extractall_hardlinks(self):
1105 # Test if extractall works properly when tarfile contains symlinks
1106 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1107 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1108 os.mkdir(tempdir)
1109 try:
1110 source_file = os.path.join(tempdir,'source')
1111 target_file = os.path.join(tempdir,'symlink')
1112 with open(source_file,'w') as f:
1113 f.write('something\n')
1114 os.link(source_file, target_file)
1115 tar = tarfile.open(temparchive,'w')
1116 tar.add(source_file, arcname=os.path.basename(source_file))
1117 tar.add(target_file, arcname=os.path.basename(target_file))
1118 tar.close()
1119 # Let's extract it to the location which contains the symlink
1120 tar = tarfile.open(temparchive,'r')
1121 # this should not raise OSError: [Errno 17] File exists
1122 try:
1123 tar.extractall(path=tempdir)
1124 except OSError:
1125 self.fail("extractall failed with linked files")
1126 finally:
1127 tar.close()
1128 finally:
1129 os.unlink(temparchive)
1130 shutil.rmtree(tempdir)
1131
Serhiy Storchaka7a278da2014-01-18 16:14:00 +02001132 def test_open_nonwritable_fileobj(self):
1133 for exctype in IOError, EOFError, RuntimeError:
1134 class BadFile(StringIO.StringIO):
1135 first = True
1136 def write(self, data):
1137 if self.first:
1138 self.first = False
1139 raise exctype
1140
1141 f = BadFile()
1142 with self.assertRaises(exctype):
1143 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1144 format=tarfile.PAX_FORMAT,
1145 pax_headers={'non': 'empty'})
1146 self.assertFalse(f.closed)
1147
Lars Gustäbelb1a54a32008-05-27 12:39:23 +00001148class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001149
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001150 mode = "w|"
Neal Norwitz8a519392006-08-21 17:59:46 +00001151
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001152 def test_stream_padding(self):
1153 # Test for bug #1543303.
1154 tar = tarfile.open(tmpname, self.mode)
1155 tar.close()
1156
1157 if self.mode.endswith("gz"):
Ezio Melotti07f24c52016-01-13 22:21:21 +02001158 with gzip.GzipFile(tmpname) as fobj:
1159 data = fobj.read()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001160 elif self.mode.endswith("bz2"):
1161 dec = bz2.BZ2Decompressor()
Ezio Melotti07f24c52016-01-13 22:21:21 +02001162 with open(tmpname, "rb") as fobj:
1163 data = fobj.read()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001164 data = dec.decompress(data)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001165 self.assertTrue(len(dec.unused_data) == 0,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001166 "found trailing data")
Neal Norwitz8a519392006-08-21 17:59:46 +00001167 else:
Ezio Melotti07f24c52016-01-13 22:21:21 +02001168 with open(tmpname, "rb") as fobj:
1169 data = fobj.read()
Neal Norwitz8a519392006-08-21 17:59:46 +00001170
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001171 self.assertTrue(data.count("\0") == tarfile.RECORDSIZE,
Neal Norwitz8a519392006-08-21 17:59:46 +00001172 "incorrect zero padding")
1173
Zachary Ware1f702212013-12-10 14:09:20 -06001174 @unittest.skipIf(sys.platform == 'win32', 'not appropriate for Windows')
1175 @unittest.skipUnless(hasattr(os, 'umask'), 'requires os.umask')
Lars Gustäbel5c4c4612010-04-29 15:23:38 +00001176 def test_file_mode(self):
1177 # Test for issue #8464: Create files with correct
1178 # permissions.
Lars Gustäbel5c4c4612010-04-29 15:23:38 +00001179 if os.path.exists(tmpname):
1180 os.remove(tmpname)
1181
1182 original_umask = os.umask(0022)
1183 try:
1184 tar = tarfile.open(tmpname, self.mode)
1185 tar.close()
1186 mode = os.stat(tmpname).st_mode & 0777
1187 self.assertEqual(mode, 0644, "wrong file permissions")
1188 finally:
1189 os.umask(original_umask)
1190
Lars Gustäbel7d4d0742011-12-21 19:27:50 +01001191 def test_issue13639(self):
1192 try:
1193 with tarfile.open(unicode(tmpname, sys.getfilesystemencoding()), self.mode):
1194 pass
1195 except UnicodeDecodeError:
1196 self.fail("_Stream failed to write unicode filename")
1197
Neal Norwitz8a519392006-08-21 17:59:46 +00001198
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001199class GNUWriteTest(unittest.TestCase):
1200 # This testcase checks for correct creation of GNU Longname
1201 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001202
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001203 def _length(self, s):
1204 blocks, remainder = divmod(len(s) + 1, 512)
1205 if remainder:
1206 blocks += 1
1207 return blocks * 512
1208
1209 def _calc_size(self, name, link=None):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001210 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001211 count = 512
1212
1213 if len(name) > tarfile.LENGTH_NAME:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001214 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001215 count += 512
1216 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001217 if link is not None and len(link) > tarfile.LENGTH_LINK:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001218 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001219 count += 512
1220 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001221 return count
1222
1223 def _test(self, name, link=None):
1224 tarinfo = tarfile.TarInfo(name)
1225 if link:
1226 tarinfo.linkname = link
1227 tarinfo.type = tarfile.LNKTYPE
1228
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001229 tar = tarfile.open(tmpname, "w")
Ezio Melotti07f24c52016-01-13 22:21:21 +02001230 try:
1231 tar.format = tarfile.GNU_FORMAT
1232 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001233
Ezio Melotti07f24c52016-01-13 22:21:21 +02001234 v1 = self._calc_size(name, link)
1235 v2 = tar.offset
1236 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
1237 finally:
1238 tar.close()
Georg Brandl87fa5592006-12-06 22:21:18 +00001239
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001240 tar = tarfile.open(tmpname)
Ezio Melotti07f24c52016-01-13 22:21:21 +02001241 try:
1242 member = tar.next()
1243 self.assertIsNotNone(member,
1244 "unable to read longname member")
1245 self.assertEqual(tarinfo.name, member.name,
1246 "unable to read longname member")
1247 self.assertEqual(tarinfo.linkname, member.linkname,
1248 "unable to read longname member")
1249 finally:
1250 tar.close()
Georg Brandl87fa5592006-12-06 22:21:18 +00001251
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001252 def test_longname_1023(self):
1253 self._test(("longnam/" * 127) + "longnam")
1254
1255 def test_longname_1024(self):
1256 self._test(("longnam/" * 127) + "longname")
1257
1258 def test_longname_1025(self):
1259 self._test(("longnam/" * 127) + "longname_")
1260
1261 def test_longlink_1023(self):
1262 self._test("name", ("longlnk/" * 127) + "longlnk")
1263
1264 def test_longlink_1024(self):
1265 self._test("name", ("longlnk/" * 127) + "longlink")
1266
1267 def test_longlink_1025(self):
1268 self._test("name", ("longlnk/" * 127) + "longlink_")
1269
1270 def test_longnamelink_1023(self):
1271 self._test(("longnam/" * 127) + "longnam",
1272 ("longlnk/" * 127) + "longlnk")
1273
1274 def test_longnamelink_1024(self):
1275 self._test(("longnam/" * 127) + "longname",
1276 ("longlnk/" * 127) + "longlink")
1277
1278 def test_longnamelink_1025(self):
1279 self._test(("longnam/" * 127) + "longname_",
1280 ("longlnk/" * 127) + "longlink_")
1281
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001282
1283class HardlinkTest(unittest.TestCase):
1284 # Test the creation of LNKTYPE (hardlink) members in an archive.
Georg Brandl38c6a222006-05-10 16:26:03 +00001285
1286 def setUp(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001287 self.foo = os.path.join(TEMPDIR, "foo")
1288 self.bar = os.path.join(TEMPDIR, "bar")
Georg Brandl38c6a222006-05-10 16:26:03 +00001289
Ezio Melotti07f24c52016-01-13 22:21:21 +02001290 with open(self.foo, "wb") as fobj:
1291 fobj.write("foo")
Georg Brandl38c6a222006-05-10 16:26:03 +00001292
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001293 os.link(self.foo, self.bar)
Georg Brandl38c6a222006-05-10 16:26:03 +00001294
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001295 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001296 self.tar.add(self.foo)
1297
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001298 def tearDown(self):
Hirokazu Yamamoto56d380d2008-09-21 11:44:23 +00001299 self.tar.close()
Ezio Melotti07f24c52016-01-13 22:21:21 +02001300 support.unlink(self.foo)
1301 support.unlink(self.bar)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001302
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001303 def test_add_twice(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001304 # The same name will be added as a REGTYPE every
1305 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001306 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001307 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001308 "add file as regular failed")
1309
1310 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001311 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001312 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001313 "add file as hardlink failed")
1314
1315 def test_dereference_hardlink(self):
1316 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001317 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001318 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001319 "dereferencing hardlink failed")
1320
Neal Norwitza4f651a2004-07-20 22:07:44 +00001321
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001322class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001323
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001324 def _test(self, name, link=None):
1325 # See GNUWriteTest.
1326 tarinfo = tarfile.TarInfo(name)
1327 if link:
1328 tarinfo.linkname = link
1329 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001330
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001331 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Ezio Melotti07f24c52016-01-13 22:21:21 +02001332 try:
1333 tar.addfile(tarinfo)
1334 finally:
1335 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001336
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001337 tar = tarfile.open(tmpname)
Ezio Melotti07f24c52016-01-13 22:21:21 +02001338 try:
1339 if link:
1340 l = tar.getmembers()[0].linkname
1341 self.assertTrue(link == l, "PAX longlink creation failed")
1342 else:
1343 n = tar.getmembers()[0].name
1344 self.assertTrue(name == n, "PAX longname creation failed")
1345 finally:
1346 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001347
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001348 def test_pax_global_header(self):
1349 pax_headers = {
1350 u"foo": u"bar",
1351 u"uid": u"0",
1352 u"mtime": u"1.23",
Ezio Melotti8861b292016-01-13 19:36:49 +02001353 u"test": u"\xe4\xf6\xfc",
1354 u"\xe4\xf6\xfc": u"test"}
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001355
Florent Xiclunafc5f6a72010-03-20 22:26:42 +00001356 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001357 pax_headers=pax_headers)
Ezio Melotti07f24c52016-01-13 22:21:21 +02001358 try:
1359 tar.addfile(tarfile.TarInfo("test"))
1360 finally:
1361 tar.close()
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001362
1363 # Test if the global header was written correctly.
1364 tar = tarfile.open(tmpname, encoding="iso8859-1")
Ezio Melotti07f24c52016-01-13 22:21:21 +02001365 try:
1366 self.assertEqual(tar.pax_headers, pax_headers)
1367 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001368
Ezio Melotti07f24c52016-01-13 22:21:21 +02001369 # Test if all the fields are unicode.
1370 for key, val in tar.pax_headers.iteritems():
1371 self.assertTrue(type(key) is unicode)
1372 self.assertTrue(type(val) is unicode)
1373 if key in tarfile.PAX_NUMBER_FIELDS:
1374 try:
1375 tarfile.PAX_NUMBER_FIELDS[key](val)
1376 except (TypeError, ValueError):
1377 self.fail("unable to convert pax header field")
1378 finally:
1379 tar.close()
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001380
1381 def test_pax_extended_header(self):
1382 # The fields from the pax header have priority over the
1383 # TarInfo.
1384 pax_headers = {u"path": u"foo", u"uid": u"123"}
1385
1386 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
Ezio Melotti07f24c52016-01-13 22:21:21 +02001387 try:
1388 t = tarfile.TarInfo()
1389 t.name = u"\xe4\xf6\xfc" # non-ASCII
1390 t.uid = 8**8 # too large
1391 t.pax_headers = pax_headers
1392 tar.addfile(t)
1393 finally:
1394 tar.close()
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001395
1396 tar = tarfile.open(tmpname, encoding="iso8859-1")
Ezio Melotti07f24c52016-01-13 22:21:21 +02001397 try:
1398 t = tar.getmembers()[0]
1399 self.assertEqual(t.pax_headers, pax_headers)
1400 self.assertEqual(t.name, "foo")
1401 self.assertEqual(t.uid, 123)
1402 finally:
1403 tar.close()
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001404
1405
1406class UstarUnicodeTest(unittest.TestCase):
1407 # All *UnicodeTests FIXME
1408
1409 format = tarfile.USTAR_FORMAT
1410
1411 def test_iso8859_1_filename(self):
1412 self._test_unicode_filename("iso8859-1")
1413
1414 def test_utf7_filename(self):
1415 self._test_unicode_filename("utf7")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001416
1417 def test_utf8_filename(self):
1418 self._test_unicode_filename("utf8")
1419
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001420 def _test_unicode_filename(self, encoding):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001421 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
Ezio Melotti07f24c52016-01-13 22:21:21 +02001422 try:
1423 name = u"\xe4\xf6\xfc"
1424 tar.addfile(tarfile.TarInfo(name))
1425 finally:
1426 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001427
1428 tar = tarfile.open(tmpname, encoding=encoding)
Ezio Melotti07f24c52016-01-13 22:21:21 +02001429 try:
1430 self.assertTrue(type(tar.getnames()[0]) is not unicode)
1431 self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
1432 finally:
1433 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001434
1435 def test_unicode_filename_error(self):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001436 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
Ezio Melotti07f24c52016-01-13 22:21:21 +02001437 try:
1438 tarinfo = tarfile.TarInfo()
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001439
Ezio Melotti07f24c52016-01-13 22:21:21 +02001440 tarinfo.name = "\xe4\xf6\xfc"
1441 if self.format == tarfile.PAX_FORMAT:
1442 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1443 else:
1444 tar.addfile(tarinfo)
1445
1446 tarinfo.name = u"\xe4\xf6\xfc"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001447 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001448
Ezio Melotti07f24c52016-01-13 22:21:21 +02001449 tarinfo.name = "foo"
1450 tarinfo.uname = u"\xe4\xf6\xfc"
1451 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1452 finally:
1453 tar.close()
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001454
1455 def test_unicode_argument(self):
1456 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
Ezio Melotti07f24c52016-01-13 22:21:21 +02001457 try:
1458 for t in tar:
1459 self.assertTrue(type(t.name) is str)
1460 self.assertTrue(type(t.linkname) is str)
1461 self.assertTrue(type(t.uname) is str)
1462 self.assertTrue(type(t.gname) is str)
1463 finally:
1464 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001465
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001466 def test_uname_unicode(self):
Ezio Melotti8861b292016-01-13 19:36:49 +02001467 for name in (u"\xe4\xf6\xfc", "\xe4\xf6\xfc"):
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001468 t = tarfile.TarInfo("foo")
1469 t.uname = name
1470 t.gname = name
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001471
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001472 fobj = StringIO.StringIO()
1473 tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
Ezio Melotti07f24c52016-01-13 22:21:21 +02001474 try:
1475 tar.addfile(t)
1476 finally:
1477 tar.close()
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001478 fobj.seek(0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001479
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001480 tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
1481 t = tar.getmember("foo")
Ezio Melotti8861b292016-01-13 19:36:49 +02001482 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1483 self.assertEqual(t.gname, "\xe4\xf6\xfc")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001484
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001485
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001486class GNUUnicodeTest(UstarUnicodeTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001487
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001488 format = tarfile.GNU_FORMAT
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001489
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001490
1491class PaxUnicodeTest(UstarUnicodeTest):
1492
1493 format = tarfile.PAX_FORMAT
1494
1495 def _create_unicode_name(self, name):
1496 tar = tarfile.open(tmpname, "w", format=self.format)
1497 t = tarfile.TarInfo()
1498 t.pax_headers["path"] = name
1499 tar.addfile(t)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001500 tar.close()
1501
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001502 def test_error_handlers(self):
1503 # Test if the unicode error handlers work correctly for characters
1504 # that cannot be expressed in a given encoding.
Ezio Melotti8861b292016-01-13 19:36:49 +02001505 self._create_unicode_name(u"\xe4\xf6\xfc")
Georg Brandlded1c4d2006-12-20 11:55:16 +00001506
Ezio Melotti8861b292016-01-13 19:36:49 +02001507 for handler, name in (("utf-8", u"\xe4\xf6\xfc".encode("utf8")),
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001508 ("replace", "???"), ("ignore", "")):
1509 tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
1510 errors=handler)
1511 self.assertEqual(tar.getnames()[0], name)
Georg Brandlded1c4d2006-12-20 11:55:16 +00001512
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001513 self.assertRaises(UnicodeError, tarfile.open, tmpname,
1514 encoding="ascii", errors="strict")
1515
1516 def test_error_handler_utf8(self):
1517 # Create a pathname that has one component representable using
1518 # iso8859-1 and the other only in iso8859-15.
Ezio Melotti8861b292016-01-13 19:36:49 +02001519 self._create_unicode_name(u"\xe4\xf6\xfc/\u20ac")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001520
1521 tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
1522 errors="utf-8")
Ezio Melotti8861b292016-01-13 19:36:49 +02001523 self.assertEqual(tar.getnames()[0], "\xe4\xf6\xfc/" + u"\u20ac".encode("utf8"))
Georg Brandlded1c4d2006-12-20 11:55:16 +00001524
Georg Brandlded1c4d2006-12-20 11:55:16 +00001525
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001526class AppendTest(unittest.TestCase):
1527 # Test append mode (cp. patch #1652681).
Tim Peters8ceefc52004-10-25 03:19:41 +00001528
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001529 def setUp(self):
1530 self.tarname = tmpname
1531 if os.path.exists(self.tarname):
1532 os.remove(self.tarname)
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001533
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001534 def _add_testfile(self, fileobj=None):
Ezio Melotti07f24c52016-01-13 22:21:21 +02001535 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1536 tar.addfile(tarfile.TarInfo("bar"))
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001537
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001538 def _create_testtar(self, mode="w:"):
Ezio Melotti07f24c52016-01-13 22:21:21 +02001539 with tarfile.open(tarname, encoding="iso8859-1") as src:
1540 t = src.getmember("ustar/regtype")
1541 t.name = "foo"
1542 f = src.extractfile(t)
1543 with tarfile.open(self.tarname, mode) as tar:
1544 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001545
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001546 def _test(self, names=["bar"], fileobj=None):
Ezio Melotti07f24c52016-01-13 22:21:21 +02001547 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1548 self.assertEqual(tar.getnames(), names)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001549
1550 def test_non_existing(self):
1551 self._add_testfile()
1552 self._test()
1553
1554 def test_empty(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001555 tarfile.open(self.tarname, "w:").close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001556 self._add_testfile()
1557 self._test()
1558
1559 def test_empty_fileobj(self):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001560 fobj = StringIO.StringIO("\0" * 1024)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001561 self._add_testfile(fobj)
1562 fobj.seek(0)
1563 self._test(fileobj=fobj)
1564
1565 def test_fileobj(self):
1566 self._create_testtar()
Ezio Melotti07f24c52016-01-13 22:21:21 +02001567 with open(self.tarname) as fobj:
1568 data = fobj.read()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001569 fobj = StringIO.StringIO(data)
1570 self._add_testfile(fobj)
1571 fobj.seek(0)
1572 self._test(names=["foo", "bar"], fileobj=fobj)
1573
1574 def test_existing(self):
1575 self._create_testtar()
1576 self._add_testfile()
1577 self._test(names=["foo", "bar"])
1578
Zachary Ware1f702212013-12-10 14:09:20 -06001579 @unittest.skipUnless(gzip, 'requires gzip')
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001580 def test_append_gz(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001581 self._create_testtar("w:gz")
1582 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1583
Zachary Ware1f702212013-12-10 14:09:20 -06001584 @unittest.skipUnless(bz2, 'requires bz2')
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001585 def test_append_bz2(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001586 self._create_testtar("w:bz2")
1587 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1588
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001589 # Append mode is supposed to fail if the tarfile to append to
1590 # does not end with a zero block.
1591 def _test_error(self, data):
Ezio Melotti07f24c52016-01-13 22:21:21 +02001592 with open(self.tarname, "wb") as fobj:
1593 fobj.write(data)
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001594 self.assertRaises(tarfile.ReadError, self._add_testfile)
1595
1596 def test_null(self):
1597 self._test_error("")
1598
1599 def test_incomplete(self):
1600 self._test_error("\0" * 13)
1601
1602 def test_premature_eof(self):
1603 data = tarfile.TarInfo("foo").tobuf()
1604 self._test_error(data)
1605
1606 def test_trailing_garbage(self):
1607 data = tarfile.TarInfo("foo").tobuf()
1608 self._test_error(data + "\0" * 13)
1609
1610 def test_invalid(self):
1611 self._test_error("a" * 512)
1612
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001613
1614class LimitsTest(unittest.TestCase):
1615
1616 def test_ustar_limits(self):
1617 # 100 char name
1618 tarinfo = tarfile.TarInfo("0123456789" * 10)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001619 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001620
1621 # 101 char name that cannot be stored
1622 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001623 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001624
1625 # 256 char name with a slash at pos 156
1626 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001627 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001628
1629 # 256 char name that cannot be stored
1630 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001631 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001632
1633 # 512 char name
1634 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001635 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001636
1637 # 512 char linkname
1638 tarinfo = tarfile.TarInfo("longlink")
1639 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001640 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001641
1642 # uid > 8 digits
1643 tarinfo = tarfile.TarInfo("name")
1644 tarinfo.uid = 010000000
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001645 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001646
1647 def test_gnu_limits(self):
1648 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001649 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001650
1651 tarinfo = tarfile.TarInfo("longlink")
1652 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001653 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001654
1655 # uid >= 256 ** 7
1656 tarinfo = tarfile.TarInfo("name")
1657 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001658 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001659
1660 def test_pax_limits(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001661 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001662 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001663
1664 tarinfo = tarfile.TarInfo("longlink")
1665 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001666 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001667
1668 tarinfo = tarfile.TarInfo("name")
1669 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001670 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001671
1672
Lars Gustäbeld0480032015-07-02 19:37:08 +02001673class MiscTest(unittest.TestCase):
1674
1675 def test_read_number_fields(self):
1676 # Issue 24514: Test if empty number fields are converted to zero.
1677 self.assertEqual(tarfile.nti("\0"), 0)
1678 self.assertEqual(tarfile.nti(" \0"), 0)
1679
1680
Lars Gustäbel64581042010-03-03 11:55:48 +00001681class ContextManagerTest(unittest.TestCase):
1682
1683 def test_basic(self):
1684 with tarfile.open(tarname) as tar:
1685 self.assertFalse(tar.closed, "closed inside runtime context")
1686 self.assertTrue(tar.closed, "context manager failed")
1687
1688 def test_closed(self):
1689 # The __enter__() method is supposed to raise IOError
1690 # if the TarFile object is already closed.
1691 tar = tarfile.open(tarname)
1692 tar.close()
1693 with self.assertRaises(IOError):
1694 with tar:
1695 pass
1696
1697 def test_exception(self):
1698 # Test if the IOError exception is passed through properly.
1699 with self.assertRaises(Exception) as exc:
1700 with tarfile.open(tarname) as tar:
1701 raise IOError
1702 self.assertIsInstance(exc.exception, IOError,
1703 "wrong exception raised in context manager")
1704 self.assertTrue(tar.closed, "context manager failed")
1705
1706 def test_no_eof(self):
1707 # __exit__() must not write end-of-archive blocks if an
1708 # exception was raised.
1709 try:
1710 with tarfile.open(tmpname, "w") as tar:
1711 raise Exception
1712 except:
1713 pass
1714 self.assertEqual(os.path.getsize(tmpname), 0,
1715 "context manager wrote an end-of-archive block")
1716 self.assertTrue(tar.closed, "context manager failed")
1717
1718 def test_eof(self):
1719 # __exit__() must write end-of-archive blocks, i.e. call
1720 # TarFile.close() if there was no error.
1721 with tarfile.open(tmpname, "w"):
1722 pass
1723 self.assertNotEqual(os.path.getsize(tmpname), 0,
1724 "context manager wrote no end-of-archive block")
1725
1726 def test_fileobj(self):
1727 # Test that __exit__() did not close the external file
1728 # object.
Ezio Melotti07f24c52016-01-13 22:21:21 +02001729 with open(tmpname, "wb") as fobj:
1730 try:
1731 with tarfile.open(fileobj=fobj, mode="w") as tar:
1732 raise Exception
1733 except:
1734 pass
1735 self.assertFalse(fobj.closed, "external file object was closed")
1736 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel64581042010-03-03 11:55:48 +00001737
1738
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001739class LinkEmulationTest(ReadTest):
1740
1741 # Test for issue #8741 regression. On platforms that do not support
1742 # symbolic or hard links tarfile tries to extract these types of members as
1743 # the regular files they point to.
1744 def _test_link_extraction(self, name):
1745 self.tar.extract(name, TEMPDIR)
1746 data = open(os.path.join(TEMPDIR, name), "rb").read()
1747 self.assertEqual(md5sum(data), md5_regtype)
1748
1749 def test_hardlink_extraction1(self):
1750 self._test_link_extraction("ustar/lnktype")
1751
1752 def test_hardlink_extraction2(self):
1753 self._test_link_extraction("./ustar/linktest2/lnktype")
1754
1755 def test_symlink_extraction1(self):
1756 self._test_link_extraction("ustar/symtype")
1757
1758 def test_symlink_extraction2(self):
1759 self._test_link_extraction("./ustar/linktest2/symtype")
1760
1761
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001762class GzipMiscReadTest(MiscReadTest):
1763 tarname = gzipname
1764 mode = "r:gz"
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +02001765 taropen = tarfile.TarFile.gzopen
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001766class GzipUstarReadTest(UstarReadTest):
1767 tarname = gzipname
1768 mode = "r:gz"
1769class GzipStreamReadTest(StreamReadTest):
1770 tarname = gzipname
1771 mode = "r|gz"
1772class GzipWriteTest(WriteTest):
1773 mode = "w:gz"
1774class GzipStreamWriteTest(StreamWriteTest):
1775 mode = "w|gz"
1776
1777
1778class Bz2MiscReadTest(MiscReadTest):
1779 tarname = bz2name
1780 mode = "r:bz2"
Serhiy Storchaka75ba21a2014-01-18 15:35:19 +02001781 taropen = tarfile.TarFile.bz2open
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001782class Bz2UstarReadTest(UstarReadTest):
1783 tarname = bz2name
1784 mode = "r:bz2"
1785class Bz2StreamReadTest(StreamReadTest):
1786 tarname = bz2name
1787 mode = "r|bz2"
1788class Bz2WriteTest(WriteTest):
1789 mode = "w:bz2"
1790class Bz2StreamWriteTest(StreamWriteTest):
1791 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001792
Lars Gustäbel2020a592009-03-22 20:09:33 +00001793class Bz2PartialReadTest(unittest.TestCase):
1794 # Issue5068: The _BZ2Proxy.read() method loops forever
1795 # on an empty or partial bzipped file.
1796
1797 def _test_partial_input(self, mode):
1798 class MyStringIO(StringIO.StringIO):
1799 hit_eof = False
1800 def read(self, n):
1801 if self.hit_eof:
1802 raise AssertionError("infinite loop detected in tarfile.open()")
1803 self.hit_eof = self.pos == self.len
1804 return StringIO.StringIO.read(self, n)
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001805 def seek(self, *args):
1806 self.hit_eof = False
1807 return StringIO.StringIO.seek(self, *args)
Lars Gustäbel2020a592009-03-22 20:09:33 +00001808
1809 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1810 for x in range(len(data) + 1):
Lars Gustäbeldd866d52009-11-22 18:30:53 +00001811 try:
1812 tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
1813 except tarfile.ReadError:
1814 pass # we have no interest in ReadErrors
Lars Gustäbel2020a592009-03-22 20:09:33 +00001815
1816 def test_partial_input(self):
1817 self._test_partial_input("r")
1818
1819 def test_partial_input_bz2(self):
1820 self._test_partial_input("r:bz2")
1821
1822
Neal Norwitz996acf12003-02-17 14:51:41 +00001823def test_main():
Ezio Melotti07f24c52016-01-13 22:21:21 +02001824 support.unlink(TEMPDIR)
Antoine Pitrou310c9fe2009-11-11 20:55:07 +00001825 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001826
Walter Dörwald21d3a322003-05-01 17:45:56 +00001827 tests = [
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001828 UstarReadTest,
1829 MiscReadTest,
1830 StreamReadTest,
1831 DetectReadTest,
1832 MemberReadTest,
1833 GNUReadTest,
1834 PaxReadTest,
Serhiy Storchakacfc2c7b2014-02-05 20:55:13 +02001835 ListTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001836 WriteTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001837 StreamWriteTest,
1838 GNUWriteTest,
1839 PaxWriteTest,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001840 UstarUnicodeTest,
1841 GNUUnicodeTest,
1842 PaxUnicodeTest,
Lars Gustäbel3f8aca12007-02-06 18:38:13 +00001843 AppendTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001844 LimitsTest,
Lars Gustäbeld0480032015-07-02 19:37:08 +02001845 MiscTest,
Lars Gustäbel64581042010-03-03 11:55:48 +00001846 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001847 ]
1848
Neal Norwitza4f651a2004-07-20 22:07:44 +00001849 if hasattr(os, "link"):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001850 tests.append(HardlinkTest)
Lars Gustäbel4da7d412010-06-03 12:34:14 +00001851 else:
1852 tests.append(LinkEmulationTest)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001853
Ezio Melotti07f24c52016-01-13 22:21:21 +02001854 with open(tarname, "rb") as fobj:
1855 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001856
Walter Dörwald21d3a322003-05-01 17:45:56 +00001857 if gzip:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001858 # Create testtar.tar.gz and add gzip-specific tests.
Ezio Melotti07f24c52016-01-13 22:21:21 +02001859 support.unlink(gzipname)
1860 with gzip.open(gzipname, "wb") as tar:
1861 tar.write(data)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001862
1863 tests += [
1864 GzipMiscReadTest,
1865 GzipUstarReadTest,
1866 GzipStreamReadTest,
Serhiy Storchakacfc2c7b2014-02-05 20:55:13 +02001867 GzipListTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001868 GzipWriteTest,
1869 GzipStreamWriteTest,
1870 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001871
1872 if bz2:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001873 # Create testtar.tar.bz2 and add bz2-specific tests.
Ezio Melotti07f24c52016-01-13 22:21:21 +02001874 support.unlink(bz2name)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001875 tar = bz2.BZ2File(bz2name, "wb")
Ezio Melotti07f24c52016-01-13 22:21:21 +02001876 try:
1877 tar.write(data)
1878 finally:
1879 tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001880
1881 tests += [
1882 Bz2MiscReadTest,
1883 Bz2UstarReadTest,
1884 Bz2StreamReadTest,
Serhiy Storchakacfc2c7b2014-02-05 20:55:13 +02001885 Bz2ListTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001886 Bz2WriteTest,
1887 Bz2StreamWriteTest,
Lars Gustäbel2020a592009-03-22 20:09:33 +00001888 Bz2PartialReadTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001889 ]
1890
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001891 try:
Walter Dörwald21d3a322003-05-01 17:45:56 +00001892 test_support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001893 finally:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001894 if os.path.exists(TEMPDIR):
1895 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001896
Neal Norwitz996acf12003-02-17 14:51:41 +00001897if __name__ == "__main__":
1898 test_main()