blob: ff04ef835197e2017d40c400a53b4a6e06fc277e [file] [log] [blame]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001import sys
2import os
Lars Gustäbelb506dc32007-08-07 18:36:16 +00003import io
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00004import shutil
Guido van Rossum34d19282007-08-09 01:03:29 +00005import io
Guido van Rossuma8add0e2007-05-14 22:03:55 +00006from hashlib import md5
Guido van Rossumd8faa362007-04-27 19:54:29 +00007import errno
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00008
9import unittest
10import tarfile
11
Benjamin Petersonee8712c2008-05-20 21:35:26 +000012from test import 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
Guido van Rossumd8faa362007-04-27 19:54:29 +000025def md5sum(data):
Guido van Rossuma8add0e2007-05-14 22:03:55 +000026 return md5(data).hexdigest()
Guido van Rossumd8faa362007-04-27 19:54:29 +000027
Antoine Pitrou941ee882009-11-11 20:59:38 +000028TEMPDIR = os.path.abspath(support.TESTFN)
29tarname = support.findfile("testtar.tar")
Guido van Rossumd8faa362007-04-27 19:54:29 +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
Guido van Rossumd8faa362007-04-27 19:54:29 +000034md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
35md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000036
37
Guido van Rossumd8faa362007-04-27 19:54:29 +000038class ReadTest(unittest.TestCase):
39
40 tarname = tarname
41 mode = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000042
43 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +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
Guido van Rossumd8faa362007-04-27 19:54:29 +000050class UstarReadTest(ReadTest):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000051
Guido van Rossumd8faa362007-04-27 19:54:29 +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 Petersonc9c0f202009-06-30 23:06:06 +000056 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Guido van Rossumd8faa362007-04-27 19:54:29 +000057 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000058
Guido van Rossumd8faa362007-04-27 19:54:29 +000059 def test_fileobj_readlines(self):
60 self.tar.extract("ustar/regtype", TEMPDIR)
61 tarinfo = self.tar.getmember("ustar/regtype")
Lars Gustäbelb506dc32007-08-07 18:36:16 +000062 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "r")
63 fobj2 = io.TextIOWrapper(self.tar.extractfile(tarinfo))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000064
Guido van Rossumd8faa362007-04-27 19:54:29 +000065 lines1 = fobj1.readlines()
66 lines2 = fobj2.readlines()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000067 self.assertTrue(lines1 == lines2,
Guido van Rossumd8faa362007-04-27 19:54:29 +000068 "fileobj.readlines() failed")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000069 self.assertTrue(len(lines2) == 114,
Guido van Rossumd8faa362007-04-27 19:54:29 +000070 "fileobj.readlines() failed")
Benjamin Peterson886af962010-03-21 23:13:07 +000071 self.assertTrue(lines2[83] ==
Guido van Rossumd8faa362007-04-27 19:54:29 +000072 "I will gladly admit that Python is not the fastest running scripting language.\n",
73 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000074
Guido van Rossumd8faa362007-04-27 19:54:29 +000075 def test_fileobj_iter(self):
76 self.tar.extract("ustar/regtype", TEMPDIR)
77 tarinfo = self.tar.getmember("ustar/regtype")
78 fobj1 = open(os.path.join(TEMPDIR, "ustar/regtype"), "rU")
79 fobj2 = self.tar.extractfile(tarinfo)
80 lines1 = fobj1.readlines()
Lars Gustäbelb506dc32007-08-07 18:36:16 +000081 lines2 = list(io.TextIOWrapper(fobj2))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000082 self.assertTrue(lines1 == lines2,
Guido van Rossumd8faa362007-04-27 19:54:29 +000083 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +000084
Guido van Rossumd8faa362007-04-27 19:54:29 +000085 def test_fileobj_seek(self):
86 self.tar.extract("ustar/regtype", TEMPDIR)
87 fobj = open(os.path.join(TEMPDIR, "ustar/regtype"), "rb")
88 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +000089 fobj.close()
90
Guido van Rossumd8faa362007-04-27 19:54:29 +000091 tarinfo = self.tar.getmember("ustar/regtype")
92 fobj = self.tar.extractfile(tarinfo)
93
94 text = fobj.read()
95 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +000096 self.assertEqual(0, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +000097 "seek() to file's start failed")
98 fobj.seek(2048, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +000099 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000100 "seek() to absolute position failed")
101 fobj.seek(-1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000102 self.assertEqual(1024, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000103 "seek() to negative relative position failed")
104 fobj.seek(1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000105 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000106 "seek() to positive relative position failed")
107 s = fobj.read(10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000108 self.assertTrue(s == data[2048:2058],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000109 "read() after seek failed")
110 fobj.seek(0, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000111 self.assertEqual(tarinfo.size, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 "seek() to file's end failed")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000113 self.assertTrue(fobj.read() == b"",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000114 "read() at file's end did not return empty string")
115 fobj.seek(-tarinfo.size, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000116 self.assertEqual(0, fobj.tell(),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000117 "relative seek() to file's end failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118 fobj.seek(512)
119 s1 = fobj.readlines()
120 fobj.seek(512)
121 s2 = fobj.readlines()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000122 self.assertTrue(s1 == s2,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123 "readlines() after seek failed")
124 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000125 self.assertEqual(len(fobj.readline()), fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126 "tell() after readline() failed")
127 fobj.seek(512)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000128 self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000129 "tell() after seek() and readline() failed")
130 fobj.seek(0)
131 line = fobj.readline()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000132 self.assertEqual(fobj.read(), data[len(line):],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000133 "read() after readline() failed")
134 fobj.close()
135
136
Lars Gustäbel9520a432009-11-22 18:48:49 +0000137class CommonReadTest(ReadTest):
138
139 def test_empty_tarfile(self):
140 # Test for issue6123: Allow opening empty archives.
141 # This test checks if tarfile.open() is able to open an empty tar
142 # archive successfully. Note that an empty tar archive is not the
143 # same as an empty file!
144 tarfile.open(tmpname, self.mode.replace("r", "w")).close()
145 try:
146 tar = tarfile.open(tmpname, self.mode)
147 tar.getnames()
148 except tarfile.ReadError:
149 self.fail("tarfile.open() failed on empty archive")
150 self.assertListEqual(tar.getmembers(), [])
151
152 def test_null_tarfile(self):
153 # Test for issue6123: Allow opening empty archives.
154 # This test guarantees that tarfile.open() does not treat an empty
155 # file as an empty tar archive.
156 open(tmpname, "wb").close()
157 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
158 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
159
160 def test_ignore_zeros(self):
161 # Test TarFile's ignore_zeros option.
162 if self.mode.endswith(":gz"):
163 _open = gzip.GzipFile
164 elif self.mode.endswith(":bz2"):
165 _open = bz2.BZ2File
166 else:
167 _open = open
168
169 for char in (b'\0', b'a'):
170 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
171 # are ignored correctly.
172 fobj = _open(tmpname, "wb")
173 fobj.write(char * 1024)
174 fobj.write(tarfile.TarInfo("foo").tobuf())
175 fobj.close()
176
177 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
178 self.assertListEqual(tar.getnames(), ["foo"],
179 "ignore_zeros=True should have skipped the %r-blocks" % char)
180 tar.close()
181
182
183class MiscReadTest(CommonReadTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000184
Thomas Woutersed03b412007-08-28 21:37:11 +0000185 def test_no_name_argument(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000186 fobj = open(self.tarname, "rb")
187 tar = tarfile.open(fileobj=fobj, mode=self.mode)
188 self.assertEqual(tar.name, os.path.abspath(fobj.name))
189
Thomas Woutersed03b412007-08-28 21:37:11 +0000190 def test_no_name_attribute(self):
191 data = open(self.tarname, "rb").read()
192 fobj = io.BytesIO(data)
193 self.assertRaises(AttributeError, getattr, fobj, "name")
194 tar = tarfile.open(fileobj=fobj, mode=self.mode)
195 self.assertEqual(tar.name, None)
196
197 def test_empty_name_attribute(self):
198 data = open(self.tarname, "rb").read()
199 fobj = io.BytesIO(data)
200 fobj.name = ""
201 tar = tarfile.open(fileobj=fobj, mode=self.mode)
202 self.assertEqual(tar.name, None)
203
Christian Heimesd8654cf2007-12-02 15:22:16 +0000204 def test_fileobj_with_offset(self):
205 # Skip the first member and store values from the second member
206 # of the testtar.
207 tar = tarfile.open(self.tarname, mode=self.mode)
208 tar.next()
209 t = tar.next()
210 name = t.name
211 offset = t.offset
212 data = tar.extractfile(t).read()
213 tar.close()
214
215 # Open the testtar and seek to the offset of the second member.
216 if self.mode.endswith(":gz"):
217 _open = gzip.GzipFile
218 elif self.mode.endswith(":bz2"):
219 _open = bz2.BZ2File
220 else:
221 _open = open
222 fobj = _open(self.tarname, "rb")
223 fobj.seek(offset)
224
225 # Test if the tarfile starts with the second member.
226 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
227 t = tar.next()
228 self.assertEqual(t.name, name)
229 # Read to the end of fileobj and test if seeking back to the
230 # beginning works.
231 tar.getmembers()
232 self.assertEqual(tar.extractfile(t).read(), data,
233 "seek back did not work")
234 tar.close()
235
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236 def test_fail_comp(self):
237 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
238 if self.mode == "r:":
239 return
240 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
241 fobj = open(tarname, "rb")
242 self.assertRaises(tarfile.ReadError, tarfile.open, fileobj=fobj, mode=self.mode)
243
244 def test_v7_dirtype(self):
245 # Test old style dirtype member (bug #1336623):
246 # Old V7 tars create directory members using an AREGTYPE
247 # header with a "/" appended to the filename field.
248 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000249 self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250 "v7 dirtype failed")
251
Christian Heimes126d29a2008-02-11 22:57:17 +0000252 def test_xstar_type(self):
253 # The xstar format stores extra atime and ctime fields inside the
254 # space reserved for the prefix field. The prefix field must be
255 # ignored in this case, otherwise it will mess up the name.
256 try:
257 self.tar.getmember("misc/regtype-xstar")
258 except KeyError:
259 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
260
Guido van Rossumd8faa362007-04-27 19:54:29 +0000261 def test_check_members(self):
262 for tarinfo in self.tar:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000263 self.assertTrue(int(tarinfo.mtime) == 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000264 "wrong mtime for %s" % tarinfo.name)
265 if not tarinfo.name.startswith("ustar/"):
266 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000267 self.assertTrue(tarinfo.uname == "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000268 "wrong uname for %s" % tarinfo.name)
269
270 def test_find_members(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000271 self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000272 "could not find all members")
273
274 def test_extract_hardlink(self):
275 # Test hardlink extraction (e.g. bug #857297).
276 tar = tarfile.open(tarname, errorlevel=1, encoding="iso8859-1")
277
278 tar.extract("ustar/regtype", TEMPDIR)
Neal Norwitzf3396542005-10-28 05:52:22 +0000279 try:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000280 tar.extract("ustar/lnktype", TEMPDIR)
281 except EnvironmentError as e:
282 if e.errno == errno.ENOENT:
283 self.fail("hardlink not extracted properly")
Neal Norwitzf3396542005-10-28 05:52:22 +0000284
Guido van Rossumd8faa362007-04-27 19:54:29 +0000285 data = open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb").read()
286 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000287
Guido van Rossumd8faa362007-04-27 19:54:29 +0000288 try:
289 tar.extract("ustar/symtype", TEMPDIR)
290 except EnvironmentError as e:
291 if e.errno == errno.ENOENT:
292 self.fail("symlink not extracted properly")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000293
Guido van Rossumd8faa362007-04-27 19:54:29 +0000294 data = open(os.path.join(TEMPDIR, "ustar/symtype"), "rb").read()
295 self.assertEqual(md5sum(data), md5_regtype)
296
Christian Heimesfaf2f632008-01-06 16:59:19 +0000297 def test_extractall(self):
298 # Test if extractall() correctly restores directory permissions
299 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000300 tar = tarfile.open(tarname, encoding="iso8859-1")
301 directories = [t for t in tar if t.isdir()]
302 tar.extractall(TEMPDIR, directories)
303 for tarinfo in directories:
304 path = os.path.join(TEMPDIR, tarinfo.name)
Lars Gustäbel43fcf3a2008-12-12 14:58:38 +0000305 if sys.platform != "win32":
306 # Win32 has no support for fine grained permissions.
307 self.assertEqual(tarinfo.mode & 0o777, os.stat(path).st_mode & 0o777)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000308 self.assertEqual(tarinfo.mtime, os.path.getmtime(path))
309 tar.close()
310
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000311 def test_init_close_fobj(self):
312 # Issue #7341: Close the internal file object in the TarFile
313 # constructor in case of an error. For the test we rely on
314 # the fact that opening an empty file raises a ReadError.
315 empty = os.path.join(TEMPDIR, "empty")
316 open(empty, "wb").write(b"")
317
318 try:
319 tar = object.__new__(tarfile.TarFile)
320 try:
321 tar.__init__(empty)
322 except tarfile.ReadError:
323 self.assertTrue(tar.fileobj.closed)
324 else:
325 self.fail("ReadError not raised")
326 finally:
327 os.remove(empty)
328
Guido van Rossumd8faa362007-04-27 19:54:29 +0000329
Lars Gustäbel9520a432009-11-22 18:48:49 +0000330class StreamReadTest(CommonReadTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000331
332 mode="r|"
333
334 def test_fileobj_regular_file(self):
335 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
336 fobj = self.tar.extractfile(tarinfo)
337 data = fobj.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000338 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000339 "regular file extraction failed")
340
341 def test_provoke_stream_error(self):
342 tarinfos = self.tar.getmembers()
343 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000344 self.assertRaises(tarfile.StreamError, f.read)
345
Guido van Rossumd8faa362007-04-27 19:54:29 +0000346 def test_compare_members(self):
347 tar1 = tarfile.open(tarname, encoding="iso8859-1")
348 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000349
Guido van Rossumd8faa362007-04-27 19:54:29 +0000350 while True:
351 t1 = tar1.next()
352 t2 = tar2.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000353 if t1 is None:
354 break
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000355 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000356
357 if t2.islnk() or t2.issym():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000358 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000359 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000360
361 v1 = tar1.extractfile(t1)
362 v2 = tar2.extractfile(t2)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000363 if v1 is None:
364 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000365 self.assertTrue(v2 is not None, "stream.extractfile() failed")
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000366 self.assertEqual(v1.read(), v2.read(), "stream extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000367
Guido van Rossumd8faa362007-04-27 19:54:29 +0000368 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000369
Thomas Wouters89f507f2006-12-13 04:49:30 +0000370
Guido van Rossumd8faa362007-04-27 19:54:29 +0000371class DetectReadTest(unittest.TestCase):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000372
Guido van Rossumd8faa362007-04-27 19:54:29 +0000373 def _testfunc_file(self, name, mode):
374 try:
375 tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000376 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000377 self.fail()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000378
Guido van Rossumd8faa362007-04-27 19:54:29 +0000379 def _testfunc_fileobj(self, name, mode):
380 try:
381 tarfile.open(name, mode, fileobj=open(name, "rb"))
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000382 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000383 self.fail()
384
385 def _test_modes(self, testfunc):
386 testfunc(tarname, "r")
387 testfunc(tarname, "r:")
388 testfunc(tarname, "r:*")
389 testfunc(tarname, "r|")
390 testfunc(tarname, "r|*")
391
392 if gzip:
393 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
394 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
395 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
396 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
397
398 testfunc(gzipname, "r")
399 testfunc(gzipname, "r:*")
400 testfunc(gzipname, "r:gz")
401 testfunc(gzipname, "r|*")
402 testfunc(gzipname, "r|gz")
403
404 if bz2:
405 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
406 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
407 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
408 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
409
410 testfunc(bz2name, "r")
411 testfunc(bz2name, "r:*")
412 testfunc(bz2name, "r:bz2")
413 testfunc(bz2name, "r|*")
414 testfunc(bz2name, "r|bz2")
415
416 def test_detect_file(self):
417 self._test_modes(self._testfunc_file)
418
419 def test_detect_fileobj(self):
420 self._test_modes(self._testfunc_fileobj)
421
422
423class MemberReadTest(ReadTest):
424
425 def _test_member(self, tarinfo, chksum=None, **kwargs):
426 if chksum is not None:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000427 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428 "wrong md5sum for %s" % tarinfo.name)
429
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000430 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000431 kwargs["uid"] = 1000
432 kwargs["gid"] = 100
433 if "old-v7" not in tarinfo.name:
434 # V7 tar can't handle alphabetic owners.
435 kwargs["uname"] = "tarfile"
436 kwargs["gname"] = "tarfile"
437 for k, v in kwargs.items():
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000438 self.assertTrue(getattr(tarinfo, k) == v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000439 "wrong value in %s field of %s" % (k, tarinfo.name))
440
441 def test_find_regtype(self):
442 tarinfo = self.tar.getmember("ustar/regtype")
443 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
444
445 def test_find_conttype(self):
446 tarinfo = self.tar.getmember("ustar/conttype")
447 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
448
449 def test_find_dirtype(self):
450 tarinfo = self.tar.getmember("ustar/dirtype")
451 self._test_member(tarinfo, size=0)
452
453 def test_find_dirtype_with_size(self):
454 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
455 self._test_member(tarinfo, size=255)
456
457 def test_find_lnktype(self):
458 tarinfo = self.tar.getmember("ustar/lnktype")
459 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
460
461 def test_find_symtype(self):
462 tarinfo = self.tar.getmember("ustar/symtype")
463 self._test_member(tarinfo, size=0, linkname="regtype")
464
465 def test_find_blktype(self):
466 tarinfo = self.tar.getmember("ustar/blktype")
467 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
468
469 def test_find_chrtype(self):
470 tarinfo = self.tar.getmember("ustar/chrtype")
471 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
472
473 def test_find_fifotype(self):
474 tarinfo = self.tar.getmember("ustar/fifotype")
475 self._test_member(tarinfo, size=0)
476
477 def test_find_sparse(self):
478 tarinfo = self.tar.getmember("ustar/sparse")
479 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
480
481 def test_find_umlauts(self):
Guido van Rossuma0557702007-08-07 23:19:53 +0000482 tarinfo = self.tar.getmember("ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000483 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
484
485 def test_find_ustar_longname(self):
486 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000487 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000488
489 def test_find_regtype_oldv7(self):
490 tarinfo = self.tar.getmember("misc/regtype-old-v7")
491 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
492
493 def test_find_pax_umlauts(self):
494 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Guido van Rossuma0557702007-08-07 23:19:53 +0000495 tarinfo = self.tar.getmember("pax/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000496 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
497
498
499class LongnameTest(ReadTest):
500
501 def test_read_longname(self):
502 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000503 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000504 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000505 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000506 except KeyError:
507 self.fail("longname not found")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000508 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000509
510 def test_read_longlink(self):
511 longname = self.subdir + "/" + "123/" * 125 + "longname"
512 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
513 try:
514 tarinfo = self.tar.getmember(longlink)
515 except KeyError:
516 self.fail("longlink not found")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000517 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518
519 def test_truncated_longname(self):
520 longname = self.subdir + "/" + "123/" * 125 + "longname"
521 tarinfo = self.tar.getmember(longname)
522 offset = tarinfo.offset
523 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000524 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000525 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
526
Guido van Rossume7ba4952007-06-06 23:52:48 +0000527 def test_header_offset(self):
528 # Test if the start offset of the TarInfo object includes
529 # the preceding extended header.
530 longname = self.subdir + "/" + "123/" * 125 + "longname"
531 offset = self.tar.getmember(longname).offset
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000532 fobj = open(tarname, "rb")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000533 fobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000534 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512), "iso8859-1", "strict")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000535 self.assertEqual(tarinfo.type, self.longnametype)
536
Guido van Rossumd8faa362007-04-27 19:54:29 +0000537
538class GNUReadTest(LongnameTest):
539
540 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000541 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000542
543 def test_sparse_file(self):
544 tarinfo1 = self.tar.getmember("ustar/sparse")
545 fobj1 = self.tar.extractfile(tarinfo1)
546 tarinfo2 = self.tar.getmember("gnu/sparse")
547 fobj2 = self.tar.extractfile(tarinfo2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000548 self.assertEqual(fobj1.read(), fobj2.read(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000549 "sparse file extraction failed")
550
551
Guido van Rossume7ba4952007-06-06 23:52:48 +0000552class PaxReadTest(LongnameTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000553
554 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000555 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000556
Guido van Rossume7ba4952007-06-06 23:52:48 +0000557 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000558 tar = tarfile.open(tarname, encoding="iso8859-1")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000559
Guido van Rossumd8faa362007-04-27 19:54:29 +0000560 tarinfo = tar.getmember("pax/regtype1")
561 self.assertEqual(tarinfo.uname, "foo")
562 self.assertEqual(tarinfo.gname, "bar")
Guido van Rossuma0557702007-08-07 23:19:53 +0000563 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000564
565 tarinfo = tar.getmember("pax/regtype2")
566 self.assertEqual(tarinfo.uname, "")
567 self.assertEqual(tarinfo.gname, "bar")
Guido van Rossuma0557702007-08-07 23:19:53 +0000568 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000569
570 tarinfo = tar.getmember("pax/regtype3")
571 self.assertEqual(tarinfo.uname, "tarfile")
572 self.assertEqual(tarinfo.gname, "tarfile")
Guido van Rossuma0557702007-08-07 23:19:53 +0000573 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000574
575 def test_pax_number_fields(self):
576 # All following number fields are read from the pax header.
577 tar = tarfile.open(tarname, encoding="iso8859-1")
578 tarinfo = tar.getmember("pax/regtype4")
579 self.assertEqual(tarinfo.size, 7011)
580 self.assertEqual(tarinfo.uid, 123)
581 self.assertEqual(tarinfo.gid, 123)
582 self.assertEqual(tarinfo.mtime, 1041808783.0)
583 self.assertEqual(type(tarinfo.mtime), float)
584 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
585 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000586
587
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000588class WriteTestBase(unittest.TestCase):
589 # Put all write tests in here that are supposed to be tested
590 # in all possible mode combinations.
591
592 def test_fileobj_no_close(self):
593 fobj = io.BytesIO()
594 tar = tarfile.open(fileobj=fobj, mode=self.mode)
595 tar.addfile(tarfile.TarInfo("foo"))
596 tar.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000597 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000598
599
600class WriteTest(WriteTestBase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000601
602 mode = "w:"
603
604 def test_100_char_name(self):
605 # The name field in a tar header stores strings of at most 100 chars.
606 # If a string is shorter than 100 chars it has to be padded with '\0',
607 # which implies that a string of exactly 100 chars is stored without
608 # a trailing '\0'.
609 name = "0123456789" * 10
610 tar = tarfile.open(tmpname, self.mode)
611 t = tarfile.TarInfo(name)
612 tar.addfile(t)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000613 tar.close()
614
Guido van Rossumd8faa362007-04-27 19:54:29 +0000615 tar = tarfile.open(tmpname)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000616 self.assertTrue(tar.getnames()[0] == name,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000617 "failed to store 100 char filename")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000618 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000619
Guido van Rossumd8faa362007-04-27 19:54:29 +0000620 def test_tar_size(self):
621 # Test for bug #1013882.
622 tar = tarfile.open(tmpname, self.mode)
623 path = os.path.join(TEMPDIR, "file")
624 fobj = open(path, "wb")
Lars Gustäbela280ca752007-08-28 07:34:33 +0000625 fobj.write(b"aaa")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000626 fobj.close()
627 tar.add(path)
628 tar.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000629 self.assertTrue(os.path.getsize(tmpname) > 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000630 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000631
Guido van Rossumd8faa362007-04-27 19:54:29 +0000632 # The test_*_size tests test for bug #1167128.
633 def test_file_size(self):
634 tar = tarfile.open(tmpname, self.mode)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000635
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636 path = os.path.join(TEMPDIR, "file")
637 fobj = open(path, "wb")
638 fobj.close()
639 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000640 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641
642 fobj = open(path, "wb")
Lars Gustäbela280ca752007-08-28 07:34:33 +0000643 fobj.write(b"aaa")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 fobj.close()
645 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000646 self.assertEqual(tarinfo.size, 3)
647
Guido van Rossumd8faa362007-04-27 19:54:29 +0000648 tar.close()
649
650 def test_directory_size(self):
651 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000652 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000653 try:
654 tar = tarfile.open(tmpname, self.mode)
655 tarinfo = tar.gettarinfo(path)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000656 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000657 finally:
658 os.rmdir(path)
659
660 def test_link_size(self):
661 if hasattr(os, "link"):
662 link = os.path.join(TEMPDIR, "link")
663 target = os.path.join(TEMPDIR, "link_target")
664 open(target, "wb").close()
665 os.link(target, link)
666 try:
667 tar = tarfile.open(tmpname, self.mode)
668 tarinfo = tar.gettarinfo(link)
669 self.assertEqual(tarinfo.size, 0)
670 finally:
671 os.remove(target)
672 os.remove(link)
673
674 def test_symlink_size(self):
675 if hasattr(os, "symlink"):
676 path = os.path.join(TEMPDIR, "symlink")
677 os.symlink("link_target", path)
678 try:
679 tar = tarfile.open(tmpname, self.mode)
680 tarinfo = tar.gettarinfo(path)
681 self.assertEqual(tarinfo.size, 0)
682 finally:
683 os.remove(path)
684
685 def test_add_self(self):
686 # Test for #1257255.
687 dstname = os.path.abspath(tmpname)
688
689 tar = tarfile.open(tmpname, self.mode)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000690 self.assertTrue(tar.name == dstname, "archive name must be absolute")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691
692 tar.add(dstname)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000693 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000694
695 cwd = os.getcwd()
696 os.chdir(TEMPDIR)
697 tar.add(dstname)
698 os.chdir(cwd)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000699 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000700
Guido van Rossum486364b2007-06-30 05:01:58 +0000701 def test_exclude(self):
702 tempdir = os.path.join(TEMPDIR, "exclude")
703 os.mkdir(tempdir)
704 try:
705 for name in ("foo", "bar", "baz"):
706 name = os.path.join(tempdir, name)
707 open(name, "wb").close()
708
Benjamin Peterson886af962010-03-21 23:13:07 +0000709 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +0000710
711 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Benjamin Peterson886af962010-03-21 23:13:07 +0000712 with support.check_warnings(("use the filter argument",
713 DeprecationWarning)):
714 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
Guido van Rossum486364b2007-06-30 05:01:58 +0000715 tar.close()
716
717 tar = tarfile.open(tmpname, "r")
718 self.assertEqual(len(tar.getmembers()), 1)
719 self.assertEqual(tar.getnames()[0], "empty_dir")
720 finally:
721 shutil.rmtree(tempdir)
722
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000723 def test_filter(self):
724 tempdir = os.path.join(TEMPDIR, "filter")
725 os.mkdir(tempdir)
726 try:
727 for name in ("foo", "bar", "baz"):
728 name = os.path.join(tempdir, name)
729 open(name, "wb").close()
730
731 def filter(tarinfo):
732 if os.path.basename(tarinfo.name) == "bar":
733 return
734 tarinfo.uid = 123
735 tarinfo.uname = "foo"
736 return tarinfo
737
738 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
739 tar.add(tempdir, arcname="empty_dir", filter=filter)
740 tar.close()
741
742 tar = tarfile.open(tmpname, "r")
743 for tarinfo in tar:
744 self.assertEqual(tarinfo.uid, 123)
745 self.assertEqual(tarinfo.uname, "foo")
746 self.assertEqual(len(tar.getmembers()), 3)
747 tar.close()
748 finally:
749 shutil.rmtree(tempdir)
750
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000751 # Guarantee that stored pathnames are not modified. Don't
752 # remove ./ or ../ or double slashes. Still make absolute
753 # pathnames relative.
754 # For details see bug #6054.
755 def _test_pathname(self, path, cmp_path=None, dir=False):
756 # Create a tarfile with an empty member named path
757 # and compare the stored name with the original.
758 foo = os.path.join(TEMPDIR, "foo")
759 if not dir:
760 open(foo, "w").close()
761 else:
762 os.mkdir(foo)
763
764 tar = tarfile.open(tmpname, self.mode)
765 tar.add(foo, arcname=path)
766 tar.close()
767
768 tar = tarfile.open(tmpname, "r")
769 t = tar.next()
770 tar.close()
771
772 if not dir:
773 os.remove(foo)
774 else:
775 os.rmdir(foo)
776
777 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
778
779 def test_pathnames(self):
780 self._test_pathname("foo")
781 self._test_pathname(os.path.join("foo", ".", "bar"))
782 self._test_pathname(os.path.join("foo", "..", "bar"))
783 self._test_pathname(os.path.join(".", "foo"))
784 self._test_pathname(os.path.join(".", "foo", "."))
785 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
786 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
787 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
788 self._test_pathname(os.path.join("..", "foo"))
789 self._test_pathname(os.path.join("..", "foo", ".."))
790 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
791 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
792
793 self._test_pathname("foo" + os.sep + os.sep + "bar")
794 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
795
796 def test_abs_pathnames(self):
797 if sys.platform == "win32":
798 self._test_pathname("C:\\foo", "foo")
799 else:
800 self._test_pathname("/foo", "foo")
801 self._test_pathname("///foo", "foo")
802
803 def test_cwd(self):
804 # Test adding the current working directory.
805 cwd = os.getcwd()
806 os.chdir(TEMPDIR)
807 try:
808 open("foo", "w").close()
809
810 tar = tarfile.open(tmpname, self.mode)
811 tar.add(".")
812 tar.close()
813
814 tar = tarfile.open(tmpname, "r")
815 for t in tar:
816 self.assert_(t.name == "." or t.name.startswith("./"))
817 tar.close()
818 finally:
819 os.chdir(cwd)
820
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000821
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000822class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000823
Guido van Rossumd8faa362007-04-27 19:54:29 +0000824 mode = "w|"
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000825
Guido van Rossumd8faa362007-04-27 19:54:29 +0000826 def test_stream_padding(self):
827 # Test for bug #1543303.
828 tar = tarfile.open(tmpname, self.mode)
829 tar.close()
830
831 if self.mode.endswith("gz"):
832 fobj = gzip.GzipFile(tmpname)
833 data = fobj.read()
834 fobj.close()
835 elif self.mode.endswith("bz2"):
836 dec = bz2.BZ2Decompressor()
837 data = open(tmpname, "rb").read()
838 data = dec.decompress(data)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000839 self.assertTrue(len(dec.unused_data) == 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000840 "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000841 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000842 fobj = open(tmpname, "rb")
843 data = fobj.read()
844 fobj.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000845
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000846 self.assertTrue(data.count(b"\0") == tarfile.RECORDSIZE,
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000847 "incorrect zero padding")
848
849
Guido van Rossumd8faa362007-04-27 19:54:29 +0000850class GNUWriteTest(unittest.TestCase):
851 # This testcase checks for correct creation of GNU Longname
852 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000853
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000854 def _length(self, s):
855 blocks, remainder = divmod(len(s) + 1, 512)
856 if remainder:
857 blocks += 1
858 return blocks * 512
859
860 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000861 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000862 count = 512
863
864 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000865 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000866 count += 512
867 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000868 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000869 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000870 count += 512
871 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000872 return count
873
874 def _test(self, name, link=None):
875 tarinfo = tarfile.TarInfo(name)
876 if link:
877 tarinfo.linkname = link
878 tarinfo.type = tarfile.LNKTYPE
879
Guido van Rossumd8faa362007-04-27 19:54:29 +0000880 tar = tarfile.open(tmpname, "w")
881 tar.format = tarfile.GNU_FORMAT
Thomas Wouters89f507f2006-12-13 04:49:30 +0000882 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000883
884 v1 = self._calc_size(name, link)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000885 v2 = tar.offset
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000886 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000887
Thomas Wouters89f507f2006-12-13 04:49:30 +0000888 tar.close()
889
Guido van Rossumd8faa362007-04-27 19:54:29 +0000890 tar = tarfile.open(tmpname)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000891 member = tar.next()
Benjamin Peterson886af962010-03-21 23:13:07 +0000892 self.assertIsNotNone(member,
893 "unable to read longname member")
894 self.assertEqual(tarinfo.name, member.name,
895 "unable to read longname member")
896 self.assertEqual(tarinfo.linkname, member.linkname,
897 "unable to read longname member")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000898
Neal Norwitz0662f8a2004-07-20 21:54:18 +0000899 def test_longname_1023(self):
900 self._test(("longnam/" * 127) + "longnam")
901
902 def test_longname_1024(self):
903 self._test(("longnam/" * 127) + "longname")
904
905 def test_longname_1025(self):
906 self._test(("longnam/" * 127) + "longname_")
907
908 def test_longlink_1023(self):
909 self._test("name", ("longlnk/" * 127) + "longlnk")
910
911 def test_longlink_1024(self):
912 self._test("name", ("longlnk/" * 127) + "longlink")
913
914 def test_longlink_1025(self):
915 self._test("name", ("longlnk/" * 127) + "longlink_")
916
917 def test_longnamelink_1023(self):
918 self._test(("longnam/" * 127) + "longnam",
919 ("longlnk/" * 127) + "longlnk")
920
921 def test_longnamelink_1024(self):
922 self._test(("longnam/" * 127) + "longname",
923 ("longlnk/" * 127) + "longlink")
924
925 def test_longnamelink_1025(self):
926 self._test(("longnam/" * 127) + "longname_",
927 ("longlnk/" * 127) + "longlink_")
928
Guido van Rossumd8faa362007-04-27 19:54:29 +0000929
930class HardlinkTest(unittest.TestCase):
931 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000932
933 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000934 self.foo = os.path.join(TEMPDIR, "foo")
935 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000936
Guido van Rossumd8faa362007-04-27 19:54:29 +0000937 fobj = open(self.foo, "wb")
Lars Gustäbela280ca752007-08-28 07:34:33 +0000938 fobj.write(b"foo")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000939 fobj.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000940
Guido van Rossumd8faa362007-04-27 19:54:29 +0000941 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000942
Guido van Rossumd8faa362007-04-27 19:54:29 +0000943 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000944 self.tar.add(self.foo)
945
Guido van Rossumd8faa362007-04-27 19:54:29 +0000946 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +0000947 self.tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000948 os.remove(self.foo)
949 os.remove(self.bar)
950
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000951 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000952 # The same name will be added as a REGTYPE every
953 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000954 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000955 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000956 "add file as regular failed")
957
958 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000959 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000960 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000961 "add file as hardlink failed")
962
963 def test_dereference_hardlink(self):
964 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000965 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000966 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +0000967 "dereferencing hardlink failed")
968
Neal Norwitza4f651a2004-07-20 22:07:44 +0000969
Guido van Rossumd8faa362007-04-27 19:54:29 +0000970class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000971
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972 def _test(self, name, link=None):
973 # See GNUWriteTest.
974 tarinfo = tarfile.TarInfo(name)
975 if link:
976 tarinfo.linkname = link
977 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +0000978
Guido van Rossumd8faa362007-04-27 19:54:29 +0000979 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
980 tar.addfile(tarinfo)
981 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +0000982
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983 tar = tarfile.open(tmpname)
984 if link:
985 l = tar.getmembers()[0].linkname
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000986 self.assertTrue(link == l, "PAX longlink creation failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000987 else:
988 n = tar.getmembers()[0].name
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000989 self.assertTrue(name == n, "PAX longname creation failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000990
Guido van Rossume7ba4952007-06-06 23:52:48 +0000991 def test_pax_global_header(self):
992 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +0000993 "foo": "bar",
994 "uid": "0",
995 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +0000996 "test": "\xe4\xf6\xfc",
997 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +0000998
Benjamin Peterson886af962010-03-21 23:13:07 +0000999 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001000 pax_headers=pax_headers)
1001 tar.addfile(tarfile.TarInfo("test"))
1002 tar.close()
1003
1004 # Test if the global header was written correctly.
1005 tar = tarfile.open(tmpname, encoding="iso8859-1")
1006 self.assertEqual(tar.pax_headers, pax_headers)
1007 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1008
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001009 # Test if all the fields are strings.
Guido van Rossume7ba4952007-06-06 23:52:48 +00001010 for key, val in tar.pax_headers.items():
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001011 self.assertTrue(type(key) is not bytes)
1012 self.assertTrue(type(val) is not bytes)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001013 if key in tarfile.PAX_NUMBER_FIELDS:
1014 try:
1015 tarfile.PAX_NUMBER_FIELDS[key](val)
1016 except (TypeError, ValueError):
1017 self.fail("unable to convert pax header field")
1018
1019 def test_pax_extended_header(self):
1020 # The fields from the pax header have priority over the
1021 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001022 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001023
1024 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
1025 t = tarfile.TarInfo()
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001026 t.name = "\xe4\xf6\xfc" # non-ASCII
1027 t.uid = 8**8 # too large
Guido van Rossume7ba4952007-06-06 23:52:48 +00001028 t.pax_headers = pax_headers
1029 tar.addfile(t)
1030 tar.close()
1031
1032 tar = tarfile.open(tmpname, encoding="iso8859-1")
1033 t = tar.getmembers()[0]
1034 self.assertEqual(t.pax_headers, pax_headers)
1035 self.assertEqual(t.name, "foo")
1036 self.assertEqual(t.uid, 123)
1037
1038
1039class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001040
1041 format = tarfile.USTAR_FORMAT
1042
1043 def test_iso8859_1_filename(self):
1044 self._test_unicode_filename("iso8859-1")
1045
1046 def test_utf7_filename(self):
1047 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001048
1049 def test_utf8_filename(self):
1050 self._test_unicode_filename("utf8")
1051
Guido van Rossumd8faa362007-04-27 19:54:29 +00001052 def _test_unicode_filename(self, encoding):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001053 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
Guido van Rossuma0557702007-08-07 23:19:53 +00001054 name = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001055 tar.addfile(tarfile.TarInfo(name))
1056 tar.close()
1057
1058 tar = tarfile.open(tmpname, encoding=encoding)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001059 self.assertEqual(tar.getmembers()[0].name, name)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001060 tar.close()
1061
1062 def test_unicode_filename_error(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001063 if self.format == tarfile.PAX_FORMAT:
1064 # PAX_FORMAT ignores encoding in write mode.
1065 return
1066
Guido van Rossume7ba4952007-06-06 23:52:48 +00001067 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
1068 tarinfo = tarfile.TarInfo()
1069
Guido van Rossuma0557702007-08-07 23:19:53 +00001070 tarinfo.name = "\xe4\xf6\xfc"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001071 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1072
1073 tarinfo.name = "foo"
Guido van Rossuma0557702007-08-07 23:19:53 +00001074 tarinfo.uname = "\xe4\xf6\xfc"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001075 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1076
1077 def test_unicode_argument(self):
1078 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
1079 for t in tar:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001080 self.assertTrue(type(t.name) is str)
1081 self.assertTrue(type(t.linkname) is str)
1082 self.assertTrue(type(t.uname) is str)
1083 self.assertTrue(type(t.gname) is str)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001084 tar.close()
1085
Guido van Rossume7ba4952007-06-06 23:52:48 +00001086 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001087 t = tarfile.TarInfo("foo")
1088 t.uname = "\xe4\xf6\xfc"
1089 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001090
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001091 tar = tarfile.open(tmpname, mode="w", format=self.format, encoding="iso8859-1")
1092 tar.addfile(t)
1093 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001094
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001095 tar = tarfile.open(tmpname, encoding="iso8859-1")
1096 t = tar.getmember("foo")
1097 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1098 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1099
1100 if self.format != tarfile.PAX_FORMAT:
1101 tar = tarfile.open(tmpname, encoding="ascii")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001102 t = tar.getmember("foo")
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001103 self.assertEqual(t.uname, "\ufffd\ufffd\ufffd")
1104 self.assertEqual(t.gname, "\ufffd\ufffd\ufffd")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001105
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001106
Guido van Rossume7ba4952007-06-06 23:52:48 +00001107class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001108
Guido van Rossume7ba4952007-06-06 23:52:48 +00001109 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001110
Guido van Rossumd8faa362007-04-27 19:54:29 +00001111
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001112class PAXUnicodeTest(UstarUnicodeTest):
1113
1114 format = tarfile.PAX_FORMAT
1115
1116
Guido van Rossumd8faa362007-04-27 19:54:29 +00001117class AppendTest(unittest.TestCase):
1118 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001119
Guido van Rossumd8faa362007-04-27 19:54:29 +00001120 def setUp(self):
1121 self.tarname = tmpname
1122 if os.path.exists(self.tarname):
1123 os.remove(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001124
Guido van Rossumd8faa362007-04-27 19:54:29 +00001125 def _add_testfile(self, fileobj=None):
1126 tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
1127 tar.addfile(tarfile.TarInfo("bar"))
1128 tar.close()
Tim Peters8ceefc52004-10-25 03:19:41 +00001129
Guido van Rossumd8faa362007-04-27 19:54:29 +00001130 def _create_testtar(self, mode="w:"):
1131 src = tarfile.open(tarname, encoding="iso8859-1")
1132 t = src.getmember("ustar/regtype")
1133 t.name = "foo"
1134 f = src.extractfile(t)
1135 tar = tarfile.open(self.tarname, mode)
1136 tar.addfile(t, f)
1137 tar.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001138
Guido van Rossumd8faa362007-04-27 19:54:29 +00001139 def _test(self, names=["bar"], fileobj=None):
1140 tar = tarfile.open(self.tarname, fileobj=fileobj)
1141 self.assertEqual(tar.getnames(), names)
1142
1143 def test_non_existing(self):
1144 self._add_testfile()
1145 self._test()
1146
1147 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001148 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001149 self._add_testfile()
1150 self._test()
1151
1152 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001153 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001154 self._add_testfile(fobj)
1155 fobj.seek(0)
1156 self._test(fileobj=fobj)
1157
1158 def test_fileobj(self):
1159 self._create_testtar()
Guido van Rossum34d19282007-08-09 01:03:29 +00001160 data = open(self.tarname, "rb").read()
1161 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001162 self._add_testfile(fobj)
1163 fobj.seek(0)
1164 self._test(names=["foo", "bar"], fileobj=fobj)
1165
1166 def test_existing(self):
1167 self._create_testtar()
1168 self._add_testfile()
1169 self._test(names=["foo", "bar"])
1170
1171 def test_append_gz(self):
1172 if gzip is None:
1173 return
1174 self._create_testtar("w:gz")
1175 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1176
1177 def test_append_bz2(self):
1178 if bz2 is None:
1179 return
1180 self._create_testtar("w:bz2")
1181 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1182
Lars Gustäbel9520a432009-11-22 18:48:49 +00001183 # Append mode is supposed to fail if the tarfile to append to
1184 # does not end with a zero block.
1185 def _test_error(self, data):
1186 open(self.tarname, "wb").write(data)
1187 self.assertRaises(tarfile.ReadError, self._add_testfile)
1188
1189 def test_null(self):
1190 self._test_error(b"")
1191
1192 def test_incomplete(self):
1193 self._test_error(b"\0" * 13)
1194
1195 def test_premature_eof(self):
1196 data = tarfile.TarInfo("foo").tobuf()
1197 self._test_error(data)
1198
1199 def test_trailing_garbage(self):
1200 data = tarfile.TarInfo("foo").tobuf()
1201 self._test_error(data + b"\0" * 13)
1202
1203 def test_invalid(self):
1204 self._test_error(b"a" * 512)
1205
Guido van Rossumd8faa362007-04-27 19:54:29 +00001206
1207class LimitsTest(unittest.TestCase):
1208
1209 def test_ustar_limits(self):
1210 # 100 char name
1211 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001212 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001213
1214 # 101 char name that cannot be stored
1215 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001216 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001217
1218 # 256 char name with a slash at pos 156
1219 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001220 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001221
1222 # 256 char name that cannot be stored
1223 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001224 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001225
1226 # 512 char name
1227 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001228 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001229
1230 # 512 char linkname
1231 tarinfo = tarfile.TarInfo("longlink")
1232 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001233 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001234
1235 # uid > 8 digits
1236 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001237 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001238 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001239
1240 def test_gnu_limits(self):
1241 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001242 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001243
1244 tarinfo = tarfile.TarInfo("longlink")
1245 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001246 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001247
1248 # uid >= 256 ** 7
1249 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001250 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001251 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001252
1253 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001254 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001255 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001256
1257 tarinfo = tarfile.TarInfo("longlink")
1258 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001259 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001260
1261 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001262 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001263 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001264
1265
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001266class MiscTest(unittest.TestCase):
1267
1268 def test_char_fields(self):
1269 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"), b"foo\0\0\0\0\0")
1270 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"), b"foo")
1271 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"), "foo")
1272 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"), "foo")
1273
1274 def test_number_fields(self):
1275 self.assertEqual(tarfile.itn(1), b"0000001\x00")
1276 self.assertEqual(tarfile.itn(0xffffffff), b"\x80\x00\x00\x00\xff\xff\xff\xff")
1277
1278
Lars Gustäbel01385812010-03-03 12:08:54 +00001279class ContextManagerTest(unittest.TestCase):
1280
1281 def test_basic(self):
1282 with tarfile.open(tarname) as tar:
1283 self.assertFalse(tar.closed, "closed inside runtime context")
1284 self.assertTrue(tar.closed, "context manager failed")
1285
1286 def test_closed(self):
1287 # The __enter__() method is supposed to raise IOError
1288 # if the TarFile object is already closed.
1289 tar = tarfile.open(tarname)
1290 tar.close()
1291 with self.assertRaises(IOError):
1292 with tar:
1293 pass
1294
1295 def test_exception(self):
1296 # Test if the IOError exception is passed through properly.
1297 with self.assertRaises(Exception) as exc:
1298 with tarfile.open(tarname) as tar:
1299 raise IOError
1300 self.assertIsInstance(exc.exception, IOError,
1301 "wrong exception raised in context manager")
1302 self.assertTrue(tar.closed, "context manager failed")
1303
1304 def test_no_eof(self):
1305 # __exit__() must not write end-of-archive blocks if an
1306 # exception was raised.
1307 try:
1308 with tarfile.open(tmpname, "w") as tar:
1309 raise Exception
1310 except:
1311 pass
1312 self.assertEqual(os.path.getsize(tmpname), 0,
1313 "context manager wrote an end-of-archive block")
1314 self.assertTrue(tar.closed, "context manager failed")
1315
1316 def test_eof(self):
1317 # __exit__() must write end-of-archive blocks, i.e. call
1318 # TarFile.close() if there was no error.
1319 with tarfile.open(tmpname, "w"):
1320 pass
1321 self.assertNotEqual(os.path.getsize(tmpname), 0,
1322 "context manager wrote no end-of-archive block")
1323
1324 def test_fileobj(self):
1325 # Test that __exit__() did not close the external file
1326 # object.
1327 fobj = open(tmpname, "wb")
1328 try:
1329 with tarfile.open(fileobj=fobj, mode="w") as tar:
1330 raise Exception
1331 except:
1332 pass
1333 self.assertFalse(fobj.closed, "external file object was closed")
1334 self.assertTrue(tar.closed, "context manager failed")
1335 fobj.close()
1336
1337
Guido van Rossumd8faa362007-04-27 19:54:29 +00001338class GzipMiscReadTest(MiscReadTest):
1339 tarname = gzipname
1340 mode = "r:gz"
1341class GzipUstarReadTest(UstarReadTest):
1342 tarname = gzipname
1343 mode = "r:gz"
1344class GzipStreamReadTest(StreamReadTest):
1345 tarname = gzipname
1346 mode = "r|gz"
1347class GzipWriteTest(WriteTest):
1348 mode = "w:gz"
1349class GzipStreamWriteTest(StreamWriteTest):
1350 mode = "w|gz"
1351
1352
1353class Bz2MiscReadTest(MiscReadTest):
1354 tarname = bz2name
1355 mode = "r:bz2"
1356class Bz2UstarReadTest(UstarReadTest):
1357 tarname = bz2name
1358 mode = "r:bz2"
1359class Bz2StreamReadTest(StreamReadTest):
1360 tarname = bz2name
1361 mode = "r|bz2"
1362class Bz2WriteTest(WriteTest):
1363 mode = "w:bz2"
1364class Bz2StreamWriteTest(StreamWriteTest):
1365 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001366
Lars Gustäbel42e00912009-03-22 20:34:29 +00001367class Bz2PartialReadTest(unittest.TestCase):
1368 # Issue5068: The _BZ2Proxy.read() method loops forever
1369 # on an empty or partial bzipped file.
1370
1371 def _test_partial_input(self, mode):
1372 class MyBytesIO(io.BytesIO):
1373 hit_eof = False
1374 def read(self, n):
1375 if self.hit_eof:
1376 raise AssertionError("infinite loop detected in tarfile.open()")
1377 self.hit_eof = self.tell() == len(self.getvalue())
1378 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001379 def seek(self, *args):
1380 self.hit_eof = False
1381 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00001382
1383 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1384 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001385 try:
1386 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
1387 except tarfile.ReadError:
1388 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00001389
1390 def test_partial_input(self):
1391 self._test_partial_input("r")
1392
1393 def test_partial_input_bz2(self):
1394 self._test_partial_input("r:bz2")
1395
1396
Neal Norwitz996acf12003-02-17 14:51:41 +00001397def test_main():
Antoine Pitrou941ee882009-11-11 20:59:38 +00001398 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001399
Walter Dörwald21d3a322003-05-01 17:45:56 +00001400 tests = [
Guido van Rossumd8faa362007-04-27 19:54:29 +00001401 UstarReadTest,
1402 MiscReadTest,
1403 StreamReadTest,
1404 DetectReadTest,
1405 MemberReadTest,
1406 GNUReadTest,
1407 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001408 WriteTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001409 StreamWriteTest,
1410 GNUWriteTest,
1411 PaxWriteTest,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001412 UstarUnicodeTest,
1413 GNUUnicodeTest,
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001414 PAXUnicodeTest,
Thomas Wouterscf297e42007-02-23 15:07:44 +00001415 AppendTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001416 LimitsTest,
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001417 MiscTest,
Lars Gustäbel01385812010-03-03 12:08:54 +00001418 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001419 ]
1420
Neal Norwitza4f651a2004-07-20 22:07:44 +00001421 if hasattr(os, "link"):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001422 tests.append(HardlinkTest)
1423
1424 fobj = open(tarname, "rb")
1425 data = fobj.read()
1426 fobj.close()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001427
Walter Dörwald21d3a322003-05-01 17:45:56 +00001428 if gzip:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001429 # Create testtar.tar.gz and add gzip-specific tests.
1430 tar = gzip.open(gzipname, "wb")
1431 tar.write(data)
1432 tar.close()
1433
1434 tests += [
1435 GzipMiscReadTest,
1436 GzipUstarReadTest,
1437 GzipStreamReadTest,
1438 GzipWriteTest,
1439 GzipStreamWriteTest,
1440 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001441
1442 if bz2:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001443 # Create testtar.tar.bz2 and add bz2-specific tests.
1444 tar = bz2.BZ2File(bz2name, "wb")
1445 tar.write(data)
1446 tar.close()
1447
1448 tests += [
1449 Bz2MiscReadTest,
1450 Bz2UstarReadTest,
1451 Bz2StreamReadTest,
1452 Bz2WriteTest,
1453 Bz2StreamWriteTest,
Lars Gustäbel42e00912009-03-22 20:34:29 +00001454 Bz2PartialReadTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001455 ]
1456
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001457 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001458 support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001459 finally:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001460 if os.path.exists(TEMPDIR):
1461 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001462
Neal Norwitz996acf12003-02-17 14:51:41 +00001463if __name__ == "__main__":
1464 test_main()