blob: 909b08cece87098a46f7133c1f21e3a9c59bed97 [file] [log] [blame]
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001# -*- coding: iso-8859-15 -*-
Lars Gustäbelc64e4022007-03-13 10:47:19 +00002
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00003import sys
4import os
5import shutil
Brett Cannon455ea532003-06-12 08:01:06 +00006import tempfile
Georg Brandl38c6a222006-05-10 16:26:03 +00007import StringIO
Brett Cannon7eec2172007-05-30 22:24:28 +00008from hashlib import md5
Lars Gustäbelc64e4022007-03-13 10:47:19 +00009import errno
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000010
11import unittest
12import tarfile
13
14from test import test_support
15
16# Check for our compression modules.
17try:
18 import gzip
Neal Norwitzae323192003-04-14 01:18:32 +000019 gzip.GzipFile
20except (ImportError, AttributeError):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000021 gzip = None
22try:
23 import bz2
24except ImportError:
25 bz2 = None
26
Lars Gustäbelc64e4022007-03-13 10:47:19 +000027def md5sum(data):
Brett Cannon7eec2172007-05-30 22:24:28 +000028 return md5(data).hexdigest()
Lars Gustäbelc64e4022007-03-13 10:47:19 +000029
Antoine Pitrou80e44f82009-11-11 20:57:55 +000030TEMPDIR = os.path.abspath(test_support.TESTFN)
31tarname = test_support.findfile("testtar.tar")
Lars Gustäbelc64e4022007-03-13 10:47:19 +000032gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
33bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
34tmpname = os.path.join(TEMPDIR, "tmp.tar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000035
Lars Gustäbelc64e4022007-03-13 10:47:19 +000036md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
37md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000038
39
Lars Gustäbelc64e4022007-03-13 10:47:19 +000040class ReadTest(unittest.TestCase):
41
42 tarname = tarname
43 mode = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000044
45 def setUp(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +000046 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000047
48 def tearDown(self):
49 self.tar.close()
50
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000051
Lars Gustäbelc64e4022007-03-13 10:47:19 +000052class UstarReadTest(ReadTest):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000053
Lars Gustäbelc64e4022007-03-13 10:47:19 +000054 def test_fileobj_regular_file(self):
55 tarinfo = self.tar.getmember("ustar/regtype")
56 fobj = self.tar.extractfile(tarinfo)
57 data = fobj.read()
58 self.assert_((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
59 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000060
Lars Gustäbelc64e4022007-03-13 10:47:19 +000061 def test_fileobj_readlines(self):
62 self.tar.extract("ustar/regtype", TEMPDIR)
63 tarinfo = self.tar.getmember("ustar/regtype")
64 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
65 fobj2 = self.tar.extractfile(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000066
Lars Gustäbelc64e4022007-03-13 10:47:19 +000067 lines1 = fobj1.readlines()
68 lines2 = fobj2.readlines()
69 self.assert_(lines1 == lines2,
70 "fileobj.readlines() failed")
71 self.assert_(len(lines2) == 114,
72 "fileobj.readlines() failed")
73 self.assert_(lines2[83] == \
74 "I will gladly admit that Python is not the fastest running scripting language.\n",
75 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000076
Lars Gustäbelc64e4022007-03-13 10:47:19 +000077 def test_fileobj_iter(self):
78 self.tar.extract("ustar/regtype", TEMPDIR)
79 tarinfo = self.tar.getmember("ustar/regtype")
80 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
81 fobj2 = self.tar.extractfile(tarinfo)
82 lines1 = fobj1.readlines()
83 lines2 = [line for line in fobj2]
84 self.assert_(lines1 == lines2,
85 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +000086
Lars Gustäbelc64e4022007-03-13 10:47:19 +000087 def test_fileobj_seek(self):
88 self.tar.extract("ustar/regtype", TEMPDIR)
89 fobj = open(os.path.join(TEMPDIR, "ustar/regtype"), "rb")
90 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +000091 fobj.close()
92
Lars Gustäbelc64e4022007-03-13 10:47:19 +000093 tarinfo = self.tar.getmember("ustar/regtype")
94 fobj = self.tar.extractfile(tarinfo)
95
96 text = fobj.read()
97 fobj.seek(0)
98 self.assert_(0 == fobj.tell(),
99 "seek() to file's start failed")
100 fobj.seek(2048, 0)
101 self.assert_(2048 == fobj.tell(),
102 "seek() to absolute position failed")
103 fobj.seek(-1024, 1)
104 self.assert_(1024 == fobj.tell(),
105 "seek() to negative relative position failed")
106 fobj.seek(1024, 1)
107 self.assert_(2048 == fobj.tell(),
108 "seek() to positive relative position failed")
109 s = fobj.read(10)
110 self.assert_(s == data[2048:2058],
111 "read() after seek failed")
112 fobj.seek(0, 2)
113 self.assert_(tarinfo.size == fobj.tell(),
114 "seek() to file's end failed")
115 self.assert_(fobj.read() == "",
116 "read() at file's end did not return empty string")
117 fobj.seek(-tarinfo.size, 2)
118 self.assert_(0 == fobj.tell(),
119 "relative seek() to file's start failed")
120 fobj.seek(512)
121 s1 = fobj.readlines()
122 fobj.seek(512)
123 s2 = fobj.readlines()
124 self.assert_(s1 == s2,
125 "readlines() after seek failed")
126 fobj.seek(0)
127 self.assert_(len(fobj.readline()) == fobj.tell(),
128 "tell() after readline() failed")
129 fobj.seek(512)
130 self.assert_(len(fobj.readline()) + 512 == fobj.tell(),
131 "tell() after seek() and readline() failed")
132 fobj.seek(0)
133 line = fobj.readline()
134 self.assert_(fobj.read() == data[len(line):],
135 "read() after readline() failed")
136 fobj.close()
137
138
139class MiscReadTest(ReadTest):
140
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000141 def test_no_name_argument(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000142 fobj = open(self.tarname, "rb")
143 tar = tarfile.open(fileobj=fobj, mode=self.mode)
144 self.assertEqual(tar.name, os.path.abspath(fobj.name))
145
Lars Gustäbel0f4a14b2007-08-28 12:31:09 +0000146 def test_no_name_attribute(self):
147 data = open(self.tarname, "rb").read()
148 fobj = StringIO.StringIO(data)
149 self.assertRaises(AttributeError, getattr, fobj, "name")
150 tar = tarfile.open(fileobj=fobj, mode=self.mode)
151 self.assertEqual(tar.name, None)
152
153 def test_empty_name_attribute(self):
154 data = open(self.tarname, "rb").read()
155 fobj = StringIO.StringIO(data)
156 fobj.name = ""
157 tar = tarfile.open(fileobj=fobj, mode=self.mode)
158 self.assertEqual(tar.name, None)
159
Lars Gustäbel77b2d632007-12-01 21:02:12 +0000160 def test_fileobj_with_offset(self):
161 # Skip the first member and store values from the second member
162 # of the testtar.
163 tar = tarfile.open(self.tarname, mode=self.mode)
164 tar.next()
165 t = tar.next()
166 name = t.name
167 offset = t.offset
168 data = tar.extractfile(t).read()
169 tar.close()
170
171 # Open the testtar and seek to the offset of the second member.
172 if self.mode.endswith(":gz"):
173 _open = gzip.GzipFile
174 elif self.mode.endswith(":bz2"):
175 _open = bz2.BZ2File
176 else:
177 _open = open
178 fobj = _open(self.tarname, "rb")
179 fobj.seek(offset)
180
181 # Test if the tarfile starts with the second member.
182 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
183 t = tar.next()
184 self.assertEqual(t.name, name)
185 # Read to the end of fileobj and test if seeking back to the
186 # beginning works.
187 tar.getmembers()
188 self.assertEqual(tar.extractfile(t).read(), data,
189 "seek back did not work")
190 tar.close()
191
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000192 def test_fail_comp(self):
193 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
194 if self.mode == "r:":
195 return
196 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
197 fobj = open(tarname, "rb")
198 self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode)
199
200 def test_v7_dirtype(self):
201 # Test old style dirtype member (bug #1336623):
202 # Old V7 tars create directory members using an AREGTYPE
203 # header with a "/" appended to the filename field.
204 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
205 self.assert_(tarinfo.type == tarfile.DIRTYPE,
206 "v7 dirtype failed")
207
Lars Gustäbel6bf51da2008-02-11 19:17:10 +0000208 def test_xstar_type(self):
209 # The xstar format stores extra atime and ctime fields inside the
210 # space reserved for the prefix field. The prefix field must be
211 # ignored in this case, otherwise it will mess up the name.
212 try:
213 self.tar.getmember("misc/regtype-xstar")
214 except KeyError:
215 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
216
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000217 def test_check_members(self):
218 for tarinfo in self.tar:
219 self.assert_(int(tarinfo.mtime) == 07606136617,
220 "wrong mtime for %s" % tarinfo.name)
221 if not tarinfo.name.startswith("ustar/"):
222 continue
223 self.assert_(tarinfo.uname == "tarfile",
224 "wrong uname for %s" % tarinfo.name)
225
226 def test_find_members(self):
227 self.assert_(self.tar.getmembers()[-1].name == "misc/eof",
228 "could not find all members")
229
230 def test_extract_hardlink(self):
231 # Test hardlink extraction (e.g. bug #857297).
Lars Gustäbela36cde42007-03-13 15:47:07 +0000232 tar = tarfile.open(tarname, errorlevel=1, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000233
234 tar.extract("ustar/regtype", TEMPDIR)
Neal Norwitzf3396542005-10-28 05:52:22 +0000235 try:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000236 tar.extract("ustar/lnktype", TEMPDIR)
237 except EnvironmentError, e:
238 if e.errno == errno.ENOENT:
239 self.fail("hardlink not extracted properly")
Neal Norwitzf3396542005-10-28 05:52:22 +0000240
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000241 data = open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb").read()
242 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000243
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000244 try:
245 tar.extract("ustar/symtype", TEMPDIR)
246 except EnvironmentError, e:
247 if e.errno == errno.ENOENT:
248 self.fail("symlink not extracted properly")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000249
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000250 data = open(os.path.join(TEMPDIR, "ustar/symtype"), "rb").read()
251 self.assertEqual(md5sum(data), md5_regtype)
252
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000253 def test_extractall(self):
254 # Test if extractall() correctly restores directory permissions
255 # and times (see issue1735).
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000256 tar = tarfile.open(tarname, encoding="iso8859-1")
257 directories = [t for t in tar if t.isdir()]
258 tar.extractall(TEMPDIR, directories)
259 for tarinfo in directories:
260 path = os.path.join(TEMPDIR, tarinfo.name)
Lars Gustäbel696d6ba2008-12-12 14:14:42 +0000261 if sys.platform != "win32":
262 # Win32 has no support for fine grained permissions.
263 self.assertEqual(tarinfo.mode & 0777, os.stat(path).st_mode & 0777)
Lars Gustäbel2ee1c762008-01-04 14:00:33 +0000264 self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
265 tar.close()
266
Lars Gustäbel55fa13c2009-11-23 16:01:56 +0000267 def test_init_close_fobj(self):
268 # Issue #7341: Close the internal file object in the TarFile
269 # constructor in case of an error. For the test we rely on
270 # the fact that opening an invalid file raises a ReadError.
271 invalid = os.path.join(TEMPDIR, "invalid")
272 open(invalid, "wb").write("foo")
273
274 try:
275 tar = object.__new__(tarfile.TarFile)
276 try:
277 tar.__init__(invalid)
278 except tarfile.ReadError:
279 self.assertTrue(tar.fileobj.closed)
280 else:
281 self.fail("ReadError not raised")
282 finally:
283 os.remove(invalid)
284
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000285
286class StreamReadTest(ReadTest):
287
288 mode="r|"
289
290 def test_fileobj_regular_file(self):
291 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
292 fobj = self.tar.extractfile(tarinfo)
293 data = fobj.read()
294 self.assert_((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
295 "regular file extraction failed")
296
297 def test_provoke_stream_error(self):
298 tarinfos = self.tar.getmembers()
299 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000300 self.assertRaises(tarfile.StreamError, f.read)
301
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000302 def test_compare_members(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000303 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000304 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000305
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000306 while True:
307 t1 = tar1.next()
308 t2 = tar2.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000309 if t1 is None:
310 break
311 self.assert_(t2 is not None, "stream.next() failed.")
312
313 if t2.islnk() or t2.issym():
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000314 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000315 continue
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000316
317 v1 = tar1.extractfile(t1)
318 v2 = tar2.extractfile(t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000319 if v1 is None:
320 continue
321 self.assert_(v2 is not None, "stream.extractfile() failed")
322 self.assert_(v1.read() == v2.read(), "stream extraction failed")
323
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000324 tar1.close()
Lars Gustäbela4b23812006-12-23 17:57:23 +0000325
Georg Brandla32e0a02006-10-24 16:54:16 +0000326
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000327class DetectReadTest(unittest.TestCase):
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000328
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000329 def _testfunc_file(self, name, mode):
330 try:
331 tarfile.open(name, mode)
332 except tarfile.ReadError:
333 self.fail()
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000334
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000335 def _testfunc_fileobj(self, name, mode):
336 try:
337 tarfile.open(name, mode, fileobj=open(name, "rb"))
338 except tarfile.ReadError:
339 self.fail()
340
341 def _test_modes(self, testfunc):
342 testfunc(tarname, "r")
343 testfunc(tarname, "r:")
344 testfunc(tarname, "r:*")
345 testfunc(tarname, "r|")
346 testfunc(tarname, "r|*")
347
348 if gzip:
349 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
350 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
351 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
352 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
353
354 testfunc(gzipname, "r")
355 testfunc(gzipname, "r:*")
356 testfunc(gzipname, "r:gz")
357 testfunc(gzipname, "r|*")
358 testfunc(gzipname, "r|gz")
359
360 if bz2:
361 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
362 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
363 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
364 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
365
366 testfunc(bz2name, "r")
367 testfunc(bz2name, "r:*")
368 testfunc(bz2name, "r:bz2")
369 testfunc(bz2name, "r|*")
370 testfunc(bz2name, "r|bz2")
371
372 def test_detect_file(self):
373 self._test_modes(self._testfunc_file)
374
375 def test_detect_fileobj(self):
376 self._test_modes(self._testfunc_fileobj)
377
378
379class MemberReadTest(ReadTest):
380
381 def _test_member(self, tarinfo, chksum=None, **kwargs):
382 if chksum is not None:
383 self.assert_(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
384 "wrong md5sum for %s" % tarinfo.name)
385
386 kwargs["mtime"] = 07606136617
387 kwargs["uid"] = 1000
388 kwargs["gid"] = 100
389 if "old-v7" not in tarinfo.name:
390 # V7 tar can't handle alphabetic owners.
391 kwargs["uname"] = "tarfile"
392 kwargs["gname"] = "tarfile"
393 for k, v in kwargs.iteritems():
394 self.assert_(getattr(tarinfo, k) == v,
395 "wrong value in %s field of %s" % (k, tarinfo.name))
396
397 def test_find_regtype(self):
398 tarinfo = self.tar.getmember("ustar/regtype")
399 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
400
401 def test_find_conttype(self):
402 tarinfo = self.tar.getmember("ustar/conttype")
403 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
404
405 def test_find_dirtype(self):
406 tarinfo = self.tar.getmember("ustar/dirtype")
407 self._test_member(tarinfo, size=0)
408
409 def test_find_dirtype_with_size(self):
410 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
411 self._test_member(tarinfo, size=255)
412
413 def test_find_lnktype(self):
414 tarinfo = self.tar.getmember("ustar/lnktype")
415 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
416
417 def test_find_symtype(self):
418 tarinfo = self.tar.getmember("ustar/symtype")
419 self._test_member(tarinfo, size=0, linkname="regtype")
420
421 def test_find_blktype(self):
422 tarinfo = self.tar.getmember("ustar/blktype")
423 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
424
425 def test_find_chrtype(self):
426 tarinfo = self.tar.getmember("ustar/chrtype")
427 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
428
429 def test_find_fifotype(self):
430 tarinfo = self.tar.getmember("ustar/fifotype")
431 self._test_member(tarinfo, size=0)
432
433 def test_find_sparse(self):
434 tarinfo = self.tar.getmember("ustar/sparse")
435 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
436
437 def test_find_umlauts(self):
438 tarinfo = self.tar.getmember("ustar/umlauts-ÄÖÜäöüß")
439 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
440
441 def test_find_ustar_longname(self):
442 name = "ustar/" + "12345/" * 39 + "1234567/longname"
443 self.assert_(name in self.tar.getnames())
444
445 def test_find_regtype_oldv7(self):
446 tarinfo = self.tar.getmember("misc/regtype-old-v7")
447 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
448
449 def test_find_pax_umlauts(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000450 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000451 tarinfo = self.tar.getmember("pax/umlauts-ÄÖÜäöüß")
452 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
453
454
455class LongnameTest(ReadTest):
456
457 def test_read_longname(self):
458 # Test reading of longname (bug #1471427).
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000459 longname = self.subdir + "/" + "123/" * 125 + "longname"
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000460 try:
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000461 tarinfo = self.tar.getmember(longname)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000462 except KeyError:
463 self.fail("longname not found")
464 self.assert_(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
465
466 def test_read_longlink(self):
467 longname = self.subdir + "/" + "123/" * 125 + "longname"
468 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
469 try:
470 tarinfo = self.tar.getmember(longlink)
471 except KeyError:
472 self.fail("longlink not found")
473 self.assert_(tarinfo.linkname == longname, "linkname wrong")
474
475 def test_truncated_longname(self):
476 longname = self.subdir + "/" + "123/" * 125 + "longname"
477 tarinfo = self.tar.getmember(longname)
478 offset = tarinfo.offset
479 self.tar.fileobj.seek(offset)
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000480 fobj = StringIO.StringIO(self.tar.fileobj.read(3 * 512))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000481 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
482
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000483 def test_header_offset(self):
484 # Test if the start offset of the TarInfo object includes
485 # the preceding extended header.
486 longname = self.subdir + "/" + "123/" * 125 + "longname"
487 offset = self.tar.getmember(longname).offset
488 fobj = open(tarname)
489 fobj.seek(offset)
490 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512))
491 self.assertEqual(tarinfo.type, self.longnametype)
492
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000493
494class GNUReadTest(LongnameTest):
495
496 subdir = "gnu"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000497 longnametype = tarfile.GNUTYPE_LONGNAME
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000498
499 def test_sparse_file(self):
500 tarinfo1 = self.tar.getmember("ustar/sparse")
501 fobj1 = self.tar.extractfile(tarinfo1)
502 tarinfo2 = self.tar.getmember("gnu/sparse")
503 fobj2 = self.tar.extractfile(tarinfo2)
504 self.assert_(fobj1.read() == fobj2.read(),
505 "sparse file extraction failed")
506
507
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000508class PaxReadTest(LongnameTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000509
510 subdir = "pax"
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000511 longnametype = tarfile.XHDTYPE
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000512
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000513 def test_pax_global_headers(self):
Lars Gustäbela36cde42007-03-13 15:47:07 +0000514 tar = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000515
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000516 tarinfo = tar.getmember("pax/regtype1")
517 self.assertEqual(tarinfo.uname, "foo")
518 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000519 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000520
521 tarinfo = tar.getmember("pax/regtype2")
522 self.assertEqual(tarinfo.uname, "")
523 self.assertEqual(tarinfo.gname, "bar")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000524 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000525
526 tarinfo = tar.getmember("pax/regtype3")
527 self.assertEqual(tarinfo.uname, "tarfile")
528 self.assertEqual(tarinfo.gname, "tarfile")
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000529 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), u"ÄÖÜäöüß")
530
531 def test_pax_number_fields(self):
532 # All following number fields are read from the pax header.
533 tar = tarfile.open(tarname, encoding="iso8859-1")
534 tarinfo = tar.getmember("pax/regtype4")
535 self.assertEqual(tarinfo.size, 7011)
536 self.assertEqual(tarinfo.uid, 123)
537 self.assertEqual(tarinfo.gid, 123)
538 self.assertEqual(tarinfo.mtime, 1041808783.0)
539 self.assertEqual(type(tarinfo.mtime), float)
540 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
541 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000542
543
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000544class WriteTestBase(unittest.TestCase):
545 # Put all write tests in here that are supposed to be tested
546 # in all possible mode combinations.
547
548 def test_fileobj_no_close(self):
549 fobj = StringIO.StringIO()
550 tar = tarfile.open(fileobj=fobj, mode=self.mode)
551 tar.addfile(tarfile.TarInfo("foo"))
552 tar.close()
553 self.assert_(fobj.closed is False, "external fileobjs must never closed")
554
555
556class WriteTest(WriteTestBase):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000557
558 mode = "w:"
559
560 def test_100_char_name(self):
561 # The name field in a tar header stores strings of at most 100 chars.
562 # If a string is shorter than 100 chars it has to be padded with '\0',
563 # which implies that a string of exactly 100 chars is stored without
564 # a trailing '\0'.
565 name = "0123456789" * 10
566 tar = tarfile.open(tmpname, self.mode)
567 t = tarfile.TarInfo(name)
568 tar.addfile(t)
Lars Gustäbel3f8aca12007-02-06 18:38:13 +0000569 tar.close()
570
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000571 tar = tarfile.open(tmpname)
572 self.assert_(tar.getnames()[0] == name,
Georg Brandla32e0a02006-10-24 16:54:16 +0000573 "failed to store 100 char filename")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000574 tar.close()
Georg Brandla32e0a02006-10-24 16:54:16 +0000575
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000576 def test_tar_size(self):
577 # Test for bug #1013882.
578 tar = tarfile.open(tmpname, self.mode)
579 path = os.path.join(TEMPDIR, "file")
580 fobj = open(path, "wb")
581 fobj.write("aaa")
582 fobj.close()
583 tar.add(path)
584 tar.close()
585 self.assert_(os.path.getsize(tmpname) > 0,
586 "tarfile is empty")
Georg Brandla32e0a02006-10-24 16:54:16 +0000587
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000588 # The test_*_size tests test for bug #1167128.
589 def test_file_size(self):
590 tar = tarfile.open(tmpname, self.mode)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000591
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000592 path = os.path.join(TEMPDIR, "file")
593 fobj = open(path, "wb")
594 fobj.close()
595 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000596 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000597
598 fobj = open(path, "wb")
599 fobj.write("aaa")
600 fobj.close()
601 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000602 self.assertEqual(tarinfo.size, 3)
603
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000604 tar.close()
605
606 def test_directory_size(self):
607 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000608 os.mkdir(path)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000609 try:
610 tar = tarfile.open(tmpname, self.mode)
611 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000612 self.assertEqual(tarinfo.size, 0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000613 finally:
614 os.rmdir(path)
615
616 def test_link_size(self):
617 if hasattr(os, "link"):
618 link = os.path.join(TEMPDIR, "link")
619 target = os.path.join(TEMPDIR, "link_target")
Lars Gustäbel9bcbe492010-06-03 10:07:08 +0000620 fobj = open(target, "wb")
621 fobj.write("aaa")
622 fobj.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000623 os.link(target, link)
624 try:
625 tar = tarfile.open(tmpname, self.mode)
Lars Gustäbel9bcbe492010-06-03 10:07:08 +0000626 # Record the link target in the inodes list.
627 tar.gettarinfo(target)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000628 tarinfo = tar.gettarinfo(link)
629 self.assertEqual(tarinfo.size, 0)
630 finally:
631 os.remove(target)
632 os.remove(link)
633
634 def test_symlink_size(self):
635 if hasattr(os, "symlink"):
636 path = os.path.join(TEMPDIR, "symlink")
637 os.symlink("link_target", path)
638 try:
639 tar = tarfile.open(tmpname, self.mode)
640 tarinfo = tar.gettarinfo(path)
641 self.assertEqual(tarinfo.size, 0)
642 finally:
643 os.remove(path)
644
645 def test_add_self(self):
646 # Test for #1257255.
647 dstname = os.path.abspath(tmpname)
648
649 tar = tarfile.open(tmpname, self.mode)
650 self.assert_(tar.name == dstname, "archive name must be absolute")
651
652 tar.add(dstname)
653 self.assert_(tar.getnames() == [], "added the archive to itself")
654
655 cwd = os.getcwd()
656 os.chdir(TEMPDIR)
657 tar.add(dstname)
658 os.chdir(cwd)
659 self.assert_(tar.getnames() == [], "added the archive to itself")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000660
Lars Gustäbel104490e2007-06-18 11:42:11 +0000661 def test_exclude(self):
662 tempdir = os.path.join(TEMPDIR, "exclude")
663 os.mkdir(tempdir)
664 try:
665 for name in ("foo", "bar", "baz"):
666 name = os.path.join(tempdir, name)
667 open(name, "wb").close()
668
669 def exclude(name):
670 return os.path.isfile(name)
671
672 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
673 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
674 tar.close()
675
676 tar = tarfile.open(tmpname, "r")
677 self.assertEqual(len(tar.getmembers()), 1)
678 self.assertEqual(tar.getnames()[0], "empty_dir")
679 finally:
680 shutil.rmtree(tempdir)
681
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000682
Lars Gustäbelb1a54a32008-05-27 12:39:23 +0000683class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000684
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000685 mode = "w|"
Neal Norwitz8a519392006-08-21 17:59:46 +0000686
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000687 def test_stream_padding(self):
688 # Test for bug #1543303.
689 tar = tarfile.open(tmpname, self.mode)
690 tar.close()
691
692 if self.mode.endswith("gz"):
693 fobj = gzip.GzipFile(tmpname)
694 data = fobj.read()
695 fobj.close()
696 elif self.mode.endswith("bz2"):
697 dec = bz2.BZ2Decompressor()
698 data = open(tmpname, "rb").read()
699 data = dec.decompress(data)
700 self.assert_(len(dec.unused_data) == 0,
701 "found trailing data")
Neal Norwitz8a519392006-08-21 17:59:46 +0000702 else:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000703 fobj = open(tmpname, "rb")
704 data = fobj.read()
705 fobj.close()
Neal Norwitz8a519392006-08-21 17:59:46 +0000706
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000707 self.assert_(data.count("\0") == tarfile.RECORDSIZE,
Neal Norwitz8a519392006-08-21 17:59:46 +0000708 "incorrect zero padding")
709
Lars Gustäbelb4a5bc92010-04-29 15:35:30 +0000710 def test_file_mode(self):
711 # Test for issue #8464: Create files with correct
712 # permissions.
713 if sys.platform == "win32" or not hasattr(os, "umask"):
714 return
715
716 if os.path.exists(tmpname):
717 os.remove(tmpname)
718
719 original_umask = os.umask(0022)
720 try:
721 tar = tarfile.open(tmpname, self.mode)
722 tar.close()
723 mode = os.stat(tmpname).st_mode & 0777
724 self.assertEqual(mode, 0644, "wrong file permissions")
725 finally:
726 os.umask(original_umask)
727
Neal Norwitz8a519392006-08-21 17:59:46 +0000728
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000729class GNUWriteTest(unittest.TestCase):
730 # This testcase checks for correct creation of GNU Longname
731 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000732
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000733 def _length(self, s):
734 blocks, remainder = divmod(len(s) + 1, 512)
735 if remainder:
736 blocks += 1
737 return blocks * 512
738
739 def _calc_size(self, name, link=None):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000740 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000741 count = 512
742
743 if len(name) > tarfile.LENGTH_NAME:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000744 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000745 count += 512
746 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000747 if link is not None and len(link) > tarfile.LENGTH_LINK:
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000748 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000749 count += 512
750 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000751 return count
752
753 def _test(self, name, link=None):
754 tarinfo = tarfile.TarInfo(name)
755 if link:
756 tarinfo.linkname = link
757 tarinfo.type = tarfile.LNKTYPE
758
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000759 tar = tarfile.open(tmpname, "w")
760 tar.format = tarfile.GNU_FORMAT
Georg Brandl87fa5592006-12-06 22:21:18 +0000761 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000762
763 v1 = self._calc_size(name, link)
Georg Brandl87fa5592006-12-06 22:21:18 +0000764 v2 = tar.offset
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000765 self.assert_(v1 == v2, "GNU longname/longlink creation failed")
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000766
Georg Brandl87fa5592006-12-06 22:21:18 +0000767 tar.close()
768
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000769 tar = tarfile.open(tmpname)
Georg Brandl87fa5592006-12-06 22:21:18 +0000770 member = tar.next()
771 self.failIf(member is None, "unable to read longname member")
772 self.assert_(tarinfo.name == member.name and \
773 tarinfo.linkname == member.linkname, \
774 "unable to read longname member")
775
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000776 def test_longname_1023(self):
777 self._test(("longnam/" * 127) + "longnam")
778
779 def test_longname_1024(self):
780 self._test(("longnam/" * 127) + "longname")
781
782 def test_longname_1025(self):
783 self._test(("longnam/" * 127) + "longname_")
784
785 def test_longlink_1023(self):
786 self._test("name", ("longlnk/" * 127) + "longlnk")
787
788 def test_longlink_1024(self):
789 self._test("name", ("longlnk/" * 127) + "longlink")
790
791 def test_longlink_1025(self):
792 self._test("name", ("longlnk/" * 127) + "longlink_")
793
794 def test_longnamelink_1023(self):
795 self._test(("longnam/" * 127) + "longnam",
796 ("longlnk/" * 127) + "longlnk")
797
798 def test_longnamelink_1024(self):
799 self._test(("longnam/" * 127) + "longname",
800 ("longlnk/" * 127) + "longlink")
801
802 def test_longnamelink_1025(self):
803 self._test(("longnam/" * 127) + "longname_",
804 ("longlnk/" * 127) + "longlink_")
805
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000806
807class HardlinkTest(unittest.TestCase):
808 # Test the creation of LNKTYPE (hardlink) members in an archive.
Georg Brandl38c6a222006-05-10 16:26:03 +0000809
810 def setUp(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000811 self.foo = os.path.join(TEMPDIR, "foo")
812 self.bar = os.path.join(TEMPDIR, "bar")
Georg Brandl38c6a222006-05-10 16:26:03 +0000813
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000814 fobj = open(self.foo, "wb")
815 fobj.write("foo")
816 fobj.close()
Georg Brandl38c6a222006-05-10 16:26:03 +0000817
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000818 os.link(self.foo, self.bar)
Georg Brandl38c6a222006-05-10 16:26:03 +0000819
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000820 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000821 self.tar.add(self.foo)
822
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000823 def tearDown(self):
Hirokazu Yamamoto56d380d2008-09-21 11:44:23 +0000824 self.tar.close()
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000825 os.remove(self.foo)
826 os.remove(self.bar)
827
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000828 def test_add_twice(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000829 # The same name will be added as a REGTYPE every
830 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000831 tarinfo = self.tar.gettarinfo(self.foo)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000832 self.assert_(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000833 "add file as regular failed")
834
835 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000836 tarinfo = self.tar.gettarinfo(self.bar)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000837 self.assert_(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000838 "add file as hardlink failed")
839
840 def test_dereference_hardlink(self):
841 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000842 tarinfo = self.tar.gettarinfo(self.bar)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000843 self.assert_(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000844 "dereferencing hardlink failed")
845
Neal Norwitza4f651a2004-07-20 22:07:44 +0000846
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000847class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000848
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000849 def _test(self, name, link=None):
850 # See GNUWriteTest.
851 tarinfo = tarfile.TarInfo(name)
852 if link:
853 tarinfo.linkname = link
854 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +0000855
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000856 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
857 tar.addfile(tarinfo)
858 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +0000859
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000860 tar = tarfile.open(tmpname)
861 if link:
862 l = tar.getmembers()[0].linkname
863 self.assert_(link == l, "PAX longlink creation failed")
864 else:
865 n = tar.getmembers()[0].name
866 self.assert_(name == n, "PAX longname creation failed")
867
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000868 def test_pax_global_header(self):
869 pax_headers = {
870 u"foo": u"bar",
871 u"uid": u"0",
872 u"mtime": u"1.23",
873 u"test": u"äöü",
874 u"äöü": u"test"}
875
876 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, \
877 pax_headers=pax_headers)
878 tar.addfile(tarfile.TarInfo("test"))
879 tar.close()
880
881 # Test if the global header was written correctly.
882 tar = tarfile.open(tmpname, encoding="iso8859-1")
883 self.assertEqual(tar.pax_headers, pax_headers)
884 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
885
886 # Test if all the fields are unicode.
887 for key, val in tar.pax_headers.iteritems():
888 self.assert_(type(key) is unicode)
889 self.assert_(type(val) is unicode)
890 if key in tarfile.PAX_NUMBER_FIELDS:
891 try:
892 tarfile.PAX_NUMBER_FIELDS[key](val)
893 except (TypeError, ValueError):
894 self.fail("unable to convert pax header field")
895
896 def test_pax_extended_header(self):
897 # The fields from the pax header have priority over the
898 # TarInfo.
899 pax_headers = {u"path": u"foo", u"uid": u"123"}
900
901 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
902 t = tarfile.TarInfo()
903 t.name = u"äöü" # non-ASCII
904 t.uid = 8**8 # too large
905 t.pax_headers = pax_headers
906 tar.addfile(t)
907 tar.close()
908
909 tar = tarfile.open(tmpname, encoding="iso8859-1")
910 t = tar.getmembers()[0]
911 self.assertEqual(t.pax_headers, pax_headers)
912 self.assertEqual(t.name, "foo")
913 self.assertEqual(t.uid, 123)
914
915
916class UstarUnicodeTest(unittest.TestCase):
917 # All *UnicodeTests FIXME
918
919 format = tarfile.USTAR_FORMAT
920
921 def test_iso8859_1_filename(self):
922 self._test_unicode_filename("iso8859-1")
923
924 def test_utf7_filename(self):
925 self._test_unicode_filename("utf7")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000926
927 def test_utf8_filename(self):
928 self._test_unicode_filename("utf8")
929
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000930 def _test_unicode_filename(self, encoding):
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000931 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
932 name = u"äöü"
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000933 tar.addfile(tarfile.TarInfo(name))
934 tar.close()
935
936 tar = tarfile.open(tmpname, encoding=encoding)
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000937 self.assert_(type(tar.getnames()[0]) is not unicode)
938 self.assertEqual(tar.getmembers()[0].name, name.encode(encoding))
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000939 tar.close()
940
941 def test_unicode_filename_error(self):
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000942 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
943 tarinfo = tarfile.TarInfo()
944
945 tarinfo.name = "äöü"
946 if self.format == tarfile.PAX_FORMAT:
947 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
948 else:
949 tar.addfile(tarinfo)
950
951 tarinfo.name = u"äöü"
952 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
953
954 tarinfo.name = "foo"
955 tarinfo.uname = u"äöü"
956 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
957
958 def test_unicode_argument(self):
959 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
960 for t in tar:
961 self.assert_(type(t.name) is str)
962 self.assert_(type(t.linkname) is str)
963 self.assert_(type(t.uname) is str)
964 self.assert_(type(t.gname) is str)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000965 tar.close()
966
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000967 def test_uname_unicode(self):
968 for name in (u"äöü", "äöü"):
969 t = tarfile.TarInfo("foo")
970 t.uname = name
971 t.gname = name
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000972
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000973 fobj = StringIO.StringIO()
974 tar = tarfile.open("foo.tar", mode="w", fileobj=fobj, format=self.format, encoding="iso8859-1")
975 tar.addfile(t)
976 tar.close()
977 fobj.seek(0)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000978
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000979 tar = tarfile.open("foo.tar", fileobj=fobj, encoding="iso8859-1")
980 t = tar.getmember("foo")
981 self.assertEqual(t.uname, "äöü")
982 self.assertEqual(t.gname, "äöü")
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000983
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000984
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000985class GNUUnicodeTest(UstarUnicodeTest):
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000986
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000987 format = tarfile.GNU_FORMAT
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000988
Lars Gustäbela0fcb932007-05-27 19:49:30 +0000989
990class PaxUnicodeTest(UstarUnicodeTest):
991
992 format = tarfile.PAX_FORMAT
993
994 def _create_unicode_name(self, name):
995 tar = tarfile.open(tmpname, "w", format=self.format)
996 t = tarfile.TarInfo()
997 t.pax_headers["path"] = name
998 tar.addfile(t)
Lars Gustäbelc64e4022007-03-13 10:47:19 +0000999 tar.close()
1000
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001001 def test_error_handlers(self):
1002 # Test if the unicode error handlers work correctly for characters
1003 # that cannot be expressed in a given encoding.
1004 self._create_unicode_name(u"äöü")
Georg Brandlded1c4d2006-12-20 11:55:16 +00001005
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001006 for handler, name in (("utf-8", u"äöü".encode("utf8")),
1007 ("replace", "???"), ("ignore", "")):
1008 tar = tarfile.open(tmpname, format=self.format, encoding="ascii",
1009 errors=handler)
1010 self.assertEqual(tar.getnames()[0], name)
Georg Brandlded1c4d2006-12-20 11:55:16 +00001011
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001012 self.assertRaises(UnicodeError, tarfile.open, tmpname,
1013 encoding="ascii", errors="strict")
1014
1015 def test_error_handler_utf8(self):
1016 # Create a pathname that has one component representable using
1017 # iso8859-1 and the other only in iso8859-15.
1018 self._create_unicode_name(u"äöü/¤")
1019
1020 tar = tarfile.open(tmpname, format=self.format, encoding="iso8859-1",
1021 errors="utf-8")
1022 self.assertEqual(tar.getnames()[0], "äöü/" + u"¤".encode("utf8"))
Georg Brandlded1c4d2006-12-20 11:55:16 +00001023
Georg Brandlded1c4d2006-12-20 11:55:16 +00001024
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001025class AppendTest(unittest.TestCase):
1026 # Test append mode (cp. patch #1652681).
Tim Peters8ceefc52004-10-25 03:19:41 +00001027
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001028 def setUp(self):
1029 self.tarname = tmpname
1030 if os.path.exists(self.tarname):
1031 os.remove(self.tarname)
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001032
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001033 def _add_testfile(self, fileobj=None):
1034 tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
1035 tar.addfile(tarfile.TarInfo("bar"))
1036 tar.close()
Lars Gustäbela7ba6fc2006-12-27 10:30:46 +00001037
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001038 def _create_testtar(self, mode="w:"):
Lars Gustäbela36cde42007-03-13 15:47:07 +00001039 src = tarfile.open(tarname, encoding="iso8859-1")
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001040 t = src.getmember("ustar/regtype")
1041 t.name = "foo"
1042 f = src.extractfile(t)
1043 tar = tarfile.open(self.tarname, mode)
1044 tar.addfile(t, f)
1045 tar.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001046
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001047 def _test(self, names=["bar"], fileobj=None):
1048 tar = tarfile.open(self.tarname, fileobj=fileobj)
1049 self.assertEqual(tar.getnames(), names)
1050
1051 def test_non_existing(self):
1052 self._add_testfile()
1053 self._test()
1054
1055 def test_empty(self):
1056 open(self.tarname, "w").close()
1057 self._add_testfile()
1058 self._test()
1059
1060 def test_empty_fileobj(self):
1061 fobj = StringIO.StringIO()
1062 self._add_testfile(fobj)
1063 fobj.seek(0)
1064 self._test(fileobj=fobj)
1065
1066 def test_fileobj(self):
1067 self._create_testtar()
1068 data = open(self.tarname).read()
1069 fobj = StringIO.StringIO(data)
1070 self._add_testfile(fobj)
1071 fobj.seek(0)
1072 self._test(names=["foo", "bar"], fileobj=fobj)
1073
1074 def test_existing(self):
1075 self._create_testtar()
1076 self._add_testfile()
1077 self._test(names=["foo", "bar"])
1078
1079 def test_append_gz(self):
1080 if gzip is None:
1081 return
1082 self._create_testtar("w:gz")
1083 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1084
1085 def test_append_bz2(self):
1086 if bz2 is None:
1087 return
1088 self._create_testtar("w:bz2")
1089 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1090
1091
1092class LimitsTest(unittest.TestCase):
1093
1094 def test_ustar_limits(self):
1095 # 100 char name
1096 tarinfo = tarfile.TarInfo("0123456789" * 10)
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001097 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001098
1099 # 101 char name that cannot be stored
1100 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001101 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001102
1103 # 256 char name with a slash at pos 156
1104 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001105 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001106
1107 # 256 char name that cannot be stored
1108 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001109 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001110
1111 # 512 char name
1112 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001113 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001114
1115 # 512 char linkname
1116 tarinfo = tarfile.TarInfo("longlink")
1117 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001118 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001119
1120 # uid > 8 digits
1121 tarinfo = tarfile.TarInfo("name")
1122 tarinfo.uid = 010000000
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001123 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001124
1125 def test_gnu_limits(self):
1126 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001127 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001128
1129 tarinfo = tarfile.TarInfo("longlink")
1130 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001131 tarinfo.tobuf(tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001132
1133 # uid >= 256 ** 7
1134 tarinfo = tarfile.TarInfo("name")
1135 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001136 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001137
1138 def test_pax_limits(self):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001139 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001140 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001141
1142 tarinfo = tarfile.TarInfo("longlink")
1143 tarinfo.linkname = "123/" * 126 + "longname"
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001144 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001145
1146 tarinfo = tarfile.TarInfo("name")
1147 tarinfo.uid = 04000000000000000000L
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001148 tarinfo.tobuf(tarfile.PAX_FORMAT)
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001149
1150
1151class GzipMiscReadTest(MiscReadTest):
1152 tarname = gzipname
1153 mode = "r:gz"
1154class GzipUstarReadTest(UstarReadTest):
1155 tarname = gzipname
1156 mode = "r:gz"
1157class GzipStreamReadTest(StreamReadTest):
1158 tarname = gzipname
1159 mode = "r|gz"
1160class GzipWriteTest(WriteTest):
1161 mode = "w:gz"
1162class GzipStreamWriteTest(StreamWriteTest):
1163 mode = "w|gz"
1164
1165
1166class Bz2MiscReadTest(MiscReadTest):
1167 tarname = bz2name
1168 mode = "r:bz2"
1169class Bz2UstarReadTest(UstarReadTest):
1170 tarname = bz2name
1171 mode = "r:bz2"
1172class Bz2StreamReadTest(StreamReadTest):
1173 tarname = bz2name
1174 mode = "r|bz2"
1175class Bz2WriteTest(WriteTest):
1176 mode = "w:bz2"
1177class Bz2StreamWriteTest(StreamWriteTest):
1178 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001179
Lars Gustäbel9e2a09a2009-03-22 20:22:29 +00001180class Bz2PartialReadTest(unittest.TestCase):
1181 # Issue5068: The _BZ2Proxy.read() method loops forever
1182 # on an empty or partial bzipped file.
1183
1184 def _test_partial_input(self, mode):
1185 class MyStringIO(StringIO.StringIO):
1186 hit_eof = False
1187 def read(self, n):
1188 if self.hit_eof:
1189 raise AssertionError("infinite loop detected in tarfile.open()")
1190 self.hit_eof = self.pos == self.len
1191 return StringIO.StringIO.read(self, n)
1192
1193 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1194 for x in range(len(data) + 1):
1195 tarfile.open(fileobj=MyStringIO(data[:x]), mode=mode)
1196
1197 def test_partial_input(self):
1198 self._test_partial_input("r")
1199
1200 def test_partial_input_bz2(self):
1201 self._test_partial_input("r:bz2")
1202
1203
Neal Norwitz996acf12003-02-17 14:51:41 +00001204def test_main():
Antoine Pitrou80e44f82009-11-11 20:57:55 +00001205 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001206
Walter Dörwald21d3a322003-05-01 17:45:56 +00001207 tests = [
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001208 UstarReadTest,
1209 MiscReadTest,
1210 StreamReadTest,
1211 DetectReadTest,
1212 MemberReadTest,
1213 GNUReadTest,
1214 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001215 WriteTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001216 StreamWriteTest,
1217 GNUWriteTest,
1218 PaxWriteTest,
Lars Gustäbela0fcb932007-05-27 19:49:30 +00001219 UstarUnicodeTest,
1220 GNUUnicodeTest,
1221 PaxUnicodeTest,
Lars Gustäbel3f8aca12007-02-06 18:38:13 +00001222 AppendTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001223 LimitsTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001224 ]
1225
Neal Norwitza4f651a2004-07-20 22:07:44 +00001226 if hasattr(os, "link"):
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001227 tests.append(HardlinkTest)
1228
1229 fobj = open(tarname, "rb")
1230 data = fobj.read()
1231 fobj.close()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001232
Walter Dörwald21d3a322003-05-01 17:45:56 +00001233 if gzip:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001234 # Create testtar.tar.gz and add gzip-specific tests.
1235 tar = gzip.open(gzipname, "wb")
1236 tar.write(data)
1237 tar.close()
1238
1239 tests += [
1240 GzipMiscReadTest,
1241 GzipUstarReadTest,
1242 GzipStreamReadTest,
1243 GzipWriteTest,
1244 GzipStreamWriteTest,
1245 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001246
1247 if bz2:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001248 # Create testtar.tar.bz2 and add bz2-specific tests.
1249 tar = bz2.BZ2File(bz2name, "wb")
1250 tar.write(data)
1251 tar.close()
1252
1253 tests += [
1254 Bz2MiscReadTest,
1255 Bz2UstarReadTest,
1256 Bz2StreamReadTest,
1257 Bz2WriteTest,
1258 Bz2StreamWriteTest,
Lars Gustäbel9e2a09a2009-03-22 20:22:29 +00001259 Bz2PartialReadTest,
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001260 ]
1261
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001262 try:
Walter Dörwald21d3a322003-05-01 17:45:56 +00001263 test_support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001264 finally:
Lars Gustäbelc64e4022007-03-13 10:47:19 +00001265 if os.path.exists(TEMPDIR):
1266 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001267
Neal Norwitz996acf12003-02-17 14:51:41 +00001268if __name__ == "__main__":
1269 test_main()