blob: a904e32fdf486bdd00a6d036b243cafd0d807d2c [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 Pitrouab58b5f2010-09-23 19:39:35 +000028TEMPDIR = os.path.abspath(support.TESTFN) + "-tardir"
Antoine Pitrou941ee882009-11-11 20:59:38 +000029tarname = 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)
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000055 try:
56 data = fobj.read()
57 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
58 "regular file extraction failed")
59 finally:
60 fobj.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000061
Guido van Rossumd8faa362007-04-27 19:54:29 +000062 def test_fileobj_readlines(self):
63 self.tar.extract("ustar/regtype", TEMPDIR)
64 tarinfo = self.tar.getmember("ustar/regtype")
Antoine Pitrou95f55602010-09-23 18:36:46 +000065 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
66 lines1 = fobj1.readlines()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000067
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000068 fobj = self.tar.extractfile(tarinfo)
69 try:
70 fobj2 = io.TextIOWrapper(fobj)
71 lines2 = fobj2.readlines()
72 self.assertTrue(lines1 == lines2,
73 "fileobj.readlines() failed")
74 self.assertTrue(len(lines2) == 114,
75 "fileobj.readlines() failed")
76 self.assertTrue(lines2[83] ==
77 "I will gladly admit that Python is not the fastest running scripting language.\n",
78 "fileobj.readlines() failed")
79 finally:
80 fobj.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000081
Guido van Rossumd8faa362007-04-27 19:54:29 +000082 def test_fileobj_iter(self):
83 self.tar.extract("ustar/regtype", TEMPDIR)
84 tarinfo = self.tar.getmember("ustar/regtype")
Victor Stinner4e86d5b2011-05-04 13:55:36 +020085 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
Antoine Pitrou95f55602010-09-23 18:36:46 +000086 lines1 = fobj1.readlines()
Guido van Rossumd8faa362007-04-27 19:54:29 +000087 fobj2 = self.tar.extractfile(tarinfo)
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000088 try:
89 lines2 = list(io.TextIOWrapper(fobj2))
90 self.assertTrue(lines1 == lines2,
91 "fileobj.__iter__() failed")
92 finally:
93 fobj2.close()
Martin v. Löwisdf241532005-03-03 08:17:42 +000094
Guido van Rossumd8faa362007-04-27 19:54:29 +000095 def test_fileobj_seek(self):
96 self.tar.extract("ustar/regtype", TEMPDIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +000097 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
98 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +000099
Guido van Rossumd8faa362007-04-27 19:54:29 +0000100 tarinfo = self.tar.getmember("ustar/regtype")
101 fobj = self.tar.extractfile(tarinfo)
102
103 text = fobj.read()
104 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000105 self.assertEqual(0, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000106 "seek() to file's start failed")
107 fobj.seek(2048, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000108 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000109 "seek() to absolute position failed")
110 fobj.seek(-1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000111 self.assertEqual(1024, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 "seek() to negative relative position failed")
113 fobj.seek(1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000114 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000115 "seek() to positive relative position failed")
116 s = fobj.read(10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000117 self.assertTrue(s == data[2048:2058],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118 "read() after seek failed")
119 fobj.seek(0, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000120 self.assertEqual(tarinfo.size, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000121 "seek() to file's end failed")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000122 self.assertTrue(fobj.read() == b"",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123 "read() at file's end did not return empty string")
124 fobj.seek(-tarinfo.size, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000125 self.assertEqual(0, fobj.tell(),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000126 "relative seek() to file's end failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000127 fobj.seek(512)
128 s1 = fobj.readlines()
129 fobj.seek(512)
130 s2 = fobj.readlines()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000131 self.assertTrue(s1 == s2,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000132 "readlines() after seek failed")
133 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000134 self.assertEqual(len(fobj.readline()), fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000135 "tell() after readline() failed")
136 fobj.seek(512)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000137 self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000138 "tell() after seek() and readline() failed")
139 fobj.seek(0)
140 line = fobj.readline()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000141 self.assertEqual(fobj.read(), data[len(line):],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000142 "read() after readline() failed")
143 fobj.close()
144
Lars Gustäbel1b512722010-06-03 12:45:16 +0000145 # Test if symbolic and hard links are resolved by extractfile(). The
146 # test link members each point to a regular member whose data is
147 # supposed to be exported.
148 def _test_fileobj_link(self, lnktype, regtype):
149 a = self.tar.extractfile(lnktype)
150 b = self.tar.extractfile(regtype)
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000151 try:
152 self.assertEqual(a.name, b.name)
153 finally:
154 a.close()
155 b.close()
Lars Gustäbel1b512722010-06-03 12:45:16 +0000156
157 def test_fileobj_link1(self):
158 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
159
160 def test_fileobj_link2(self):
161 self._test_fileobj_link("./ustar/linktest2/lnktype", "ustar/linktest1/regtype")
162
163 def test_fileobj_symlink1(self):
164 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
165
166 def test_fileobj_symlink2(self):
167 self._test_fileobj_link("./ustar/linktest2/symtype", "ustar/linktest1/regtype")
168
Guido van Rossumd8faa362007-04-27 19:54:29 +0000169
Lars Gustäbel9520a432009-11-22 18:48:49 +0000170class CommonReadTest(ReadTest):
171
172 def test_empty_tarfile(self):
173 # Test for issue6123: Allow opening empty archives.
174 # This test checks if tarfile.open() is able to open an empty tar
175 # archive successfully. Note that an empty tar archive is not the
176 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000177 with tarfile.open(tmpname, self.mode.replace("r", "w")):
178 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000179 try:
180 tar = tarfile.open(tmpname, self.mode)
181 tar.getnames()
182 except tarfile.ReadError:
183 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000184 else:
185 self.assertListEqual(tar.getmembers(), [])
186 finally:
187 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000188
189 def test_null_tarfile(self):
190 # Test for issue6123: Allow opening empty archives.
191 # This test guarantees that tarfile.open() does not treat an empty
192 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000193 with open(tmpname, "wb"):
194 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000195 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
196 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
197
198 def test_ignore_zeros(self):
199 # Test TarFile's ignore_zeros option.
200 if self.mode.endswith(":gz"):
201 _open = gzip.GzipFile
202 elif self.mode.endswith(":bz2"):
203 _open = bz2.BZ2File
204 else:
205 _open = open
206
207 for char in (b'\0', b'a'):
208 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
209 # are ignored correctly.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000210 with _open(tmpname, "wb") as fobj:
211 fobj.write(char * 1024)
212 fobj.write(tarfile.TarInfo("foo").tobuf())
Lars Gustäbel9520a432009-11-22 18:48:49 +0000213
214 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000215 try:
216 self.assertListEqual(tar.getnames(), ["foo"],
Lars Gustäbel9520a432009-11-22 18:48:49 +0000217 "ignore_zeros=True should have skipped the %r-blocks" % char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000218 finally:
219 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000220
221
222class MiscReadTest(CommonReadTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223
Thomas Woutersed03b412007-08-28 21:37:11 +0000224 def test_no_name_argument(self):
Lars Gustäbelbb44b732011-12-06 13:44:10 +0100225 if self.mode.endswith("bz2"):
226 # BZ2File has no name attribute.
227 return
Antoine Pitrou95f55602010-09-23 18:36:46 +0000228 with open(self.tarname, "rb") as fobj:
229 tar = tarfile.open(fileobj=fobj, mode=self.mode)
230 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
Thomas Woutersed03b412007-08-28 21:37:11 +0000232 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000233 with open(self.tarname, "rb") as fobj:
234 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000235 fobj = io.BytesIO(data)
236 self.assertRaises(AttributeError, getattr, fobj, "name")
237 tar = tarfile.open(fileobj=fobj, mode=self.mode)
238 self.assertEqual(tar.name, None)
239
240 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000241 with open(self.tarname, "rb") as fobj:
242 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000243 fobj = io.BytesIO(data)
244 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000245 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
246 self.assertEqual(tar.name, None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000247
Christian Heimesd8654cf2007-12-02 15:22:16 +0000248 def test_fileobj_with_offset(self):
249 # Skip the first member and store values from the second member
250 # of the testtar.
251 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000252 try:
253 tar.next()
254 t = tar.next()
255 name = t.name
256 offset = t.offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000257 f = tar.extractfile(t)
258 data = f.read()
259 f.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000260 finally:
261 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000262
263 # Open the testtar and seek to the offset of the second member.
264 if self.mode.endswith(":gz"):
265 _open = gzip.GzipFile
266 elif self.mode.endswith(":bz2"):
267 _open = bz2.BZ2File
268 else:
269 _open = open
270 fobj = _open(self.tarname, "rb")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000271 try:
272 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000273
Antoine Pitrou95f55602010-09-23 18:36:46 +0000274 # Test if the tarfile starts with the second member.
275 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
276 t = tar.next()
277 self.assertEqual(t.name, name)
278 # Read to the end of fileobj and test if seeking back to the
279 # beginning works.
280 tar.getmembers()
281 self.assertEqual(tar.extractfile(t).read(), data,
282 "seek back did not work")
283 tar.close()
284 finally:
285 fobj.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000286
Guido van Rossumd8faa362007-04-27 19:54:29 +0000287 def test_fail_comp(self):
288 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
289 if self.mode == "r:":
290 return
291 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000292 with open(tarname, "rb") as fobj:
293 self.assertRaises(tarfile.ReadError, tarfile.open,
294 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000295
296 def test_v7_dirtype(self):
297 # Test old style dirtype member (bug #1336623):
298 # Old V7 tars create directory members using an AREGTYPE
299 # header with a "/" appended to the filename field.
300 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000301 self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000302 "v7 dirtype failed")
303
Christian Heimes126d29a2008-02-11 22:57:17 +0000304 def test_xstar_type(self):
305 # The xstar format stores extra atime and ctime fields inside the
306 # space reserved for the prefix field. The prefix field must be
307 # ignored in this case, otherwise it will mess up the name.
308 try:
309 self.tar.getmember("misc/regtype-xstar")
310 except KeyError:
311 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
312
Guido van Rossumd8faa362007-04-27 19:54:29 +0000313 def test_check_members(self):
314 for tarinfo in self.tar:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000315 self.assertTrue(int(tarinfo.mtime) == 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000316 "wrong mtime for %s" % tarinfo.name)
317 if not tarinfo.name.startswith("ustar/"):
318 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000319 self.assertTrue(tarinfo.uname == "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000320 "wrong uname for %s" % tarinfo.name)
321
322 def test_find_members(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000323 self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000324 "could not find all members")
325
Brian Curtin74e45612010-07-09 15:58:59 +0000326 @unittest.skipUnless(hasattr(os, "link"),
327 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000328 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000329 def test_extract_hardlink(self):
330 # Test hardlink extraction (e.g. bug #857297).
331 tar = tarfile.open(tarname, errorlevel=1, encoding="iso8859-1")
332
Neal Norwitzf3396542005-10-28 05:52:22 +0000333 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000334 tar.extract("ustar/regtype", TEMPDIR)
335 try:
336 tar.extract("ustar/lnktype", TEMPDIR)
337 except EnvironmentError as e:
338 if e.errno == errno.ENOENT:
339 self.fail("hardlink not extracted properly")
Neal Norwitzf3396542005-10-28 05:52:22 +0000340
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000341 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
342 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000343 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000344
Antoine Pitrou95f55602010-09-23 18:36:46 +0000345 try:
346 tar.extract("ustar/symtype", TEMPDIR)
347 except EnvironmentError as e:
348 if e.errno == errno.ENOENT:
349 self.fail("symlink not extracted properly")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000350
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000351 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
352 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000353 self.assertEqual(md5sum(data), md5_regtype)
354 finally:
355 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000356
Christian Heimesfaf2f632008-01-06 16:59:19 +0000357 def test_extractall(self):
358 # Test if extractall() correctly restores directory permissions
359 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000360 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000361 DIR = os.path.join(TEMPDIR, "extractall")
362 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000363 try:
364 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000365 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000366 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000367 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000368 if sys.platform != "win32":
369 # Win32 has no support for fine grained permissions.
370 self.assertEqual(tarinfo.mode & 0o777, os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000371 def format_mtime(mtime):
372 if isinstance(mtime, float):
373 return "{} ({})".format(mtime, mtime.hex())
374 else:
375 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000376 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000377 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
378 format_mtime(tarinfo.mtime),
379 format_mtime(file_mtime),
380 path)
381 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000382 finally:
383 tar.close()
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000384 shutil.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000385
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000386 def test_extract_directory(self):
387 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000388 DIR = os.path.join(TEMPDIR, "extractdir")
389 os.mkdir(DIR)
390 try:
391 with tarfile.open(tarname, encoding="iso8859-1") as tar:
392 tarinfo = tar.getmember(dirtype)
393 tar.extract(tarinfo, path=DIR)
394 extracted = os.path.join(DIR, dirtype)
395 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
396 if sys.platform != "win32":
397 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
398 finally:
399 shutil.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000400
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000401 def test_init_close_fobj(self):
402 # Issue #7341: Close the internal file object in the TarFile
403 # constructor in case of an error. For the test we rely on
404 # the fact that opening an empty file raises a ReadError.
405 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000406 with open(empty, "wb") as fobj:
407 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000408
409 try:
410 tar = object.__new__(tarfile.TarFile)
411 try:
412 tar.__init__(empty)
413 except tarfile.ReadError:
414 self.assertTrue(tar.fileobj.closed)
415 else:
416 self.fail("ReadError not raised")
417 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000418 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000419
Guido van Rossumd8faa362007-04-27 19:54:29 +0000420
Lars Gustäbel9520a432009-11-22 18:48:49 +0000421class StreamReadTest(CommonReadTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000422
423 mode="r|"
424
Lars Gustäbeldd071042011-02-23 11:42:22 +0000425 def test_read_through(self):
426 # Issue #11224: A poorly designed _FileInFile.read() method
427 # caused seeking errors with stream tar files.
428 for tarinfo in self.tar:
429 if not tarinfo.isreg():
430 continue
431 fobj = self.tar.extractfile(tarinfo)
432 while True:
433 try:
434 buf = fobj.read(512)
435 except tarfile.StreamError:
436 self.fail("simple read-through using TarFile.extractfile() failed")
437 if not buf:
438 break
439 fobj.close()
440
Guido van Rossumd8faa362007-04-27 19:54:29 +0000441 def test_fileobj_regular_file(self):
442 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
443 fobj = self.tar.extractfile(tarinfo)
444 data = fobj.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000445 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000446 "regular file extraction failed")
447
448 def test_provoke_stream_error(self):
449 tarinfos = self.tar.getmembers()
450 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000451 self.assertRaises(tarfile.StreamError, f.read)
452
Guido van Rossumd8faa362007-04-27 19:54:29 +0000453 def test_compare_members(self):
454 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000455 try:
456 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000457
Antoine Pitrou95f55602010-09-23 18:36:46 +0000458 while True:
459 t1 = tar1.next()
460 t2 = tar2.next()
461 if t1 is None:
462 break
463 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000464
Antoine Pitrou95f55602010-09-23 18:36:46 +0000465 if t2.islnk() or t2.issym():
466 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
467 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000468
Antoine Pitrou95f55602010-09-23 18:36:46 +0000469 v1 = tar1.extractfile(t1)
470 v2 = tar2.extractfile(t2)
471 if v1 is None:
472 continue
473 self.assertTrue(v2 is not None, "stream.extractfile() failed")
474 self.assertEqual(v1.read(), v2.read(), "stream extraction failed")
475 finally:
476 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000477
Thomas Wouters89f507f2006-12-13 04:49:30 +0000478
Guido van Rossumd8faa362007-04-27 19:54:29 +0000479class DetectReadTest(unittest.TestCase):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000480
Guido van Rossumd8faa362007-04-27 19:54:29 +0000481 def _testfunc_file(self, name, mode):
482 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000483 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000484 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000485 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000486 else:
487 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000488
Guido van Rossumd8faa362007-04-27 19:54:29 +0000489 def _testfunc_fileobj(self, name, mode):
490 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000491 with open(name, "rb") as f:
492 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000493 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000494 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000495 else:
496 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497
498 def _test_modes(self, testfunc):
499 testfunc(tarname, "r")
500 testfunc(tarname, "r:")
501 testfunc(tarname, "r:*")
502 testfunc(tarname, "r|")
503 testfunc(tarname, "r|*")
504
505 if gzip:
506 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
507 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
508 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
509 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
510
511 testfunc(gzipname, "r")
512 testfunc(gzipname, "r:*")
513 testfunc(gzipname, "r:gz")
514 testfunc(gzipname, "r|*")
515 testfunc(gzipname, "r|gz")
516
517 if bz2:
518 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
519 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
520 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
521 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
522
523 testfunc(bz2name, "r")
524 testfunc(bz2name, "r:*")
525 testfunc(bz2name, "r:bz2")
526 testfunc(bz2name, "r|*")
527 testfunc(bz2name, "r|bz2")
528
529 def test_detect_file(self):
530 self._test_modes(self._testfunc_file)
531
532 def test_detect_fileobj(self):
533 self._test_modes(self._testfunc_fileobj)
534
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100535 def test_detect_stream_bz2(self):
536 # Originally, tarfile's stream detection looked for the string
537 # "BZh91" at the start of the file. This is incorrect because
538 # the '9' represents the blocksize (900kB). If the file was
539 # compressed using another blocksize autodetection fails.
540 if not bz2:
541 return
542
543 with open(tarname, "rb") as fobj:
544 data = fobj.read()
545
546 # Compress with blocksize 100kB, the file starts with "BZh11".
547 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
548 fobj.write(data)
549
550 self._testfunc_file(tmpname, "r|*")
551
Guido van Rossumd8faa362007-04-27 19:54:29 +0000552
553class MemberReadTest(ReadTest):
554
555 def _test_member(self, tarinfo, chksum=None, **kwargs):
556 if chksum is not None:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000557 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000558 "wrong md5sum for %s" % tarinfo.name)
559
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000560 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561 kwargs["uid"] = 1000
562 kwargs["gid"] = 100
563 if "old-v7" not in tarinfo.name:
564 # V7 tar can't handle alphabetic owners.
565 kwargs["uname"] = "tarfile"
566 kwargs["gname"] = "tarfile"
567 for k, v in kwargs.items():
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000568 self.assertTrue(getattr(tarinfo, k) == v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000569 "wrong value in %s field of %s" % (k, tarinfo.name))
570
571 def test_find_regtype(self):
572 tarinfo = self.tar.getmember("ustar/regtype")
573 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
574
575 def test_find_conttype(self):
576 tarinfo = self.tar.getmember("ustar/conttype")
577 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
578
579 def test_find_dirtype(self):
580 tarinfo = self.tar.getmember("ustar/dirtype")
581 self._test_member(tarinfo, size=0)
582
583 def test_find_dirtype_with_size(self):
584 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
585 self._test_member(tarinfo, size=255)
586
587 def test_find_lnktype(self):
588 tarinfo = self.tar.getmember("ustar/lnktype")
589 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
590
591 def test_find_symtype(self):
592 tarinfo = self.tar.getmember("ustar/symtype")
593 self._test_member(tarinfo, size=0, linkname="regtype")
594
595 def test_find_blktype(self):
596 tarinfo = self.tar.getmember("ustar/blktype")
597 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
598
599 def test_find_chrtype(self):
600 tarinfo = self.tar.getmember("ustar/chrtype")
601 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
602
603 def test_find_fifotype(self):
604 tarinfo = self.tar.getmember("ustar/fifotype")
605 self._test_member(tarinfo, size=0)
606
607 def test_find_sparse(self):
608 tarinfo = self.tar.getmember("ustar/sparse")
609 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
610
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000611 def test_find_gnusparse(self):
612 tarinfo = self.tar.getmember("gnu/sparse")
613 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
614
615 def test_find_gnusparse_00(self):
616 tarinfo = self.tar.getmember("gnu/sparse-0.0")
617 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
618
619 def test_find_gnusparse_01(self):
620 tarinfo = self.tar.getmember("gnu/sparse-0.1")
621 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
622
623 def test_find_gnusparse_10(self):
624 tarinfo = self.tar.getmember("gnu/sparse-1.0")
625 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
626
Guido van Rossumd8faa362007-04-27 19:54:29 +0000627 def test_find_umlauts(self):
Guido van Rossuma0557702007-08-07 23:19:53 +0000628 tarinfo = self.tar.getmember("ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000629 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
630
631 def test_find_ustar_longname(self):
632 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000633 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000634
635 def test_find_regtype_oldv7(self):
636 tarinfo = self.tar.getmember("misc/regtype-old-v7")
637 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
638
639 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000640 self.tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Guido van Rossuma0557702007-08-07 23:19:53 +0000642 tarinfo = self.tar.getmember("pax/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000643 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
644
645
646class LongnameTest(ReadTest):
647
648 def test_read_longname(self):
649 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000650 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000651 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000652 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000653 except KeyError:
654 self.fail("longname not found")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000655 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000656
657 def test_read_longlink(self):
658 longname = self.subdir + "/" + "123/" * 125 + "longname"
659 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
660 try:
661 tarinfo = self.tar.getmember(longlink)
662 except KeyError:
663 self.fail("longlink not found")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000664 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000665
666 def test_truncated_longname(self):
667 longname = self.subdir + "/" + "123/" * 125 + "longname"
668 tarinfo = self.tar.getmember(longname)
669 offset = tarinfo.offset
670 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000671 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000672 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
673
Guido van Rossume7ba4952007-06-06 23:52:48 +0000674 def test_header_offset(self):
675 # Test if the start offset of the TarInfo object includes
676 # the preceding extended header.
677 longname = self.subdir + "/" + "123/" * 125 + "longname"
678 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000679 with open(tarname, "rb") as fobj:
680 fobj.seek(offset)
681 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512), "iso8859-1", "strict")
682 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000683
Guido van Rossumd8faa362007-04-27 19:54:29 +0000684
685class GNUReadTest(LongnameTest):
686
687 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000688 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000689
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000690 # Since 3.2 tarfile is supposed to accurately restore sparse members and
691 # produce files with holes. This is what we actually want to test here.
692 # Unfortunately, not all platforms/filesystems support sparse files, and
693 # even on platforms that do it is non-trivial to make reliable assertions
694 # about holes in files. Therefore, we first do one basic test which works
695 # an all platforms, and after that a test that will work only on
696 # platforms/filesystems that prove to support sparse files.
697 def _test_sparse_file(self, name):
698 self.tar.extract(name, TEMPDIR)
699 filename = os.path.join(TEMPDIR, name)
700 with open(filename, "rb") as fobj:
701 data = fobj.read()
702 self.assertEqual(md5sum(data), md5_sparse,
703 "wrong md5sum for %s" % name)
704
705 if self._fs_supports_holes():
706 s = os.stat(filename)
707 self.assertTrue(s.st_blocks * 512 < s.st_size)
708
709 def test_sparse_file_old(self):
710 self._test_sparse_file("gnu/sparse")
711
712 def test_sparse_file_00(self):
713 self._test_sparse_file("gnu/sparse-0.0")
714
715 def test_sparse_file_01(self):
716 self._test_sparse_file("gnu/sparse-0.1")
717
718 def test_sparse_file_10(self):
719 self._test_sparse_file("gnu/sparse-1.0")
720
721 @staticmethod
722 def _fs_supports_holes():
723 # Return True if the platform knows the st_blocks stat attribute and
724 # uses st_blocks units of 512 bytes, and if the filesystem is able to
725 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200726 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000727 # Linux evidentially has 512 byte st_blocks units.
728 name = os.path.join(TEMPDIR, "sparse-test")
729 with open(name, "wb") as fobj:
730 fobj.seek(4096)
731 fobj.truncate()
732 s = os.stat(name)
733 os.remove(name)
734 return s.st_blocks == 0
735 else:
736 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737
738
Guido van Rossume7ba4952007-06-06 23:52:48 +0000739class PaxReadTest(LongnameTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000740
741 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000742 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000743
Guido van Rossume7ba4952007-06-06 23:52:48 +0000744 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000745 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000746 try:
747 tarinfo = tar.getmember("pax/regtype1")
748 self.assertEqual(tarinfo.uname, "foo")
749 self.assertEqual(tarinfo.gname, "bar")
750 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000751
Antoine Pitrou95f55602010-09-23 18:36:46 +0000752 tarinfo = tar.getmember("pax/regtype2")
753 self.assertEqual(tarinfo.uname, "")
754 self.assertEqual(tarinfo.gname, "bar")
755 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756
Antoine Pitrou95f55602010-09-23 18:36:46 +0000757 tarinfo = tar.getmember("pax/regtype3")
758 self.assertEqual(tarinfo.uname, "tarfile")
759 self.assertEqual(tarinfo.gname, "tarfile")
760 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
761 finally:
762 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000763
764 def test_pax_number_fields(self):
765 # All following number fields are read from the pax header.
766 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000767 try:
768 tarinfo = tar.getmember("pax/regtype4")
769 self.assertEqual(tarinfo.size, 7011)
770 self.assertEqual(tarinfo.uid, 123)
771 self.assertEqual(tarinfo.gid, 123)
772 self.assertEqual(tarinfo.mtime, 1041808783.0)
773 self.assertEqual(type(tarinfo.mtime), float)
774 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
775 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
776 finally:
777 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000778
779
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000780class WriteTestBase(unittest.TestCase):
781 # Put all write tests in here that are supposed to be tested
782 # in all possible mode combinations.
783
784 def test_fileobj_no_close(self):
785 fobj = io.BytesIO()
786 tar = tarfile.open(fileobj=fobj, mode=self.mode)
787 tar.addfile(tarfile.TarInfo("foo"))
788 tar.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000789 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000790
791
792class WriteTest(WriteTestBase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000793
794 mode = "w:"
795
796 def test_100_char_name(self):
797 # The name field in a tar header stores strings of at most 100 chars.
798 # If a string is shorter than 100 chars it has to be padded with '\0',
799 # which implies that a string of exactly 100 chars is stored without
800 # a trailing '\0'.
801 name = "0123456789" * 10
802 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000803 try:
804 t = tarfile.TarInfo(name)
805 tar.addfile(t)
806 finally:
807 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000808
Guido van Rossumd8faa362007-04-27 19:54:29 +0000809 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000810 try:
811 self.assertTrue(tar.getnames()[0] == name,
812 "failed to store 100 char filename")
813 finally:
814 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000815
Guido van Rossumd8faa362007-04-27 19:54:29 +0000816 def test_tar_size(self):
817 # Test for bug #1013882.
818 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000819 try:
820 path = os.path.join(TEMPDIR, "file")
821 with open(path, "wb") as fobj:
822 fobj.write(b"aaa")
823 tar.add(path)
824 finally:
825 tar.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000826 self.assertTrue(os.path.getsize(tmpname) > 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000827 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000828
Guido van Rossumd8faa362007-04-27 19:54:29 +0000829 # The test_*_size tests test for bug #1167128.
830 def test_file_size(self):
831 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000832 try:
833 path = os.path.join(TEMPDIR, "file")
834 with open(path, "wb"):
835 pass
836 tarinfo = tar.gettarinfo(path)
837 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000838
Antoine Pitrou95f55602010-09-23 18:36:46 +0000839 with open(path, "wb") as fobj:
840 fobj.write(b"aaa")
841 tarinfo = tar.gettarinfo(path)
842 self.assertEqual(tarinfo.size, 3)
843 finally:
844 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000845
846 def test_directory_size(self):
847 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000848 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000849 try:
850 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000851 try:
852 tarinfo = tar.gettarinfo(path)
853 self.assertEqual(tarinfo.size, 0)
854 finally:
855 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000856 finally:
857 os.rmdir(path)
858
859 def test_link_size(self):
860 if hasattr(os, "link"):
861 link = os.path.join(TEMPDIR, "link")
862 target = os.path.join(TEMPDIR, "link_target")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000863 with open(target, "wb") as fobj:
864 fobj.write(b"aaa")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000865 os.link(target, link)
866 try:
867 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000868 try:
869 # Record the link target in the inodes list.
870 tar.gettarinfo(target)
871 tarinfo = tar.gettarinfo(link)
872 self.assertEqual(tarinfo.size, 0)
873 finally:
874 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000875 finally:
876 os.remove(target)
877 os.remove(link)
878
Brian Curtin3b4499c2010-12-28 14:31:47 +0000879 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000880 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +0000881 path = os.path.join(TEMPDIR, "symlink")
882 os.symlink("link_target", path)
883 try:
884 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000885 try:
886 tarinfo = tar.gettarinfo(path)
887 self.assertEqual(tarinfo.size, 0)
888 finally:
889 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +0000890 finally:
891 os.remove(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000892
893 def test_add_self(self):
894 # Test for #1257255.
895 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000896 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000897 try:
898 self.assertTrue(tar.name == dstname, "archive name must be absolute")
899 tar.add(dstname)
900 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000901
Antoine Pitrou95f55602010-09-23 18:36:46 +0000902 cwd = os.getcwd()
903 os.chdir(TEMPDIR)
904 tar.add(dstname)
905 os.chdir(cwd)
906 self.assertTrue(tar.getnames() == [], "added the archive to itself")
907 finally:
908 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000909
Guido van Rossum486364b2007-06-30 05:01:58 +0000910 def test_exclude(self):
911 tempdir = os.path.join(TEMPDIR, "exclude")
912 os.mkdir(tempdir)
913 try:
914 for name in ("foo", "bar", "baz"):
915 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +0200916 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +0000917
Benjamin Peterson886af962010-03-21 23:13:07 +0000918 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +0000919
920 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000921 try:
922 with support.check_warnings(("use the filter argument",
923 DeprecationWarning)):
924 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
925 finally:
926 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000927
928 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000929 try:
930 self.assertEqual(len(tar.getmembers()), 1)
931 self.assertEqual(tar.getnames()[0], "empty_dir")
932 finally:
933 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000934 finally:
935 shutil.rmtree(tempdir)
936
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000937 def test_filter(self):
938 tempdir = os.path.join(TEMPDIR, "filter")
939 os.mkdir(tempdir)
940 try:
941 for name in ("foo", "bar", "baz"):
942 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +0200943 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000944
945 def filter(tarinfo):
946 if os.path.basename(tarinfo.name) == "bar":
947 return
948 tarinfo.uid = 123
949 tarinfo.uname = "foo"
950 return tarinfo
951
952 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000953 try:
954 tar.add(tempdir, arcname="empty_dir", filter=filter)
955 finally:
956 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000957
Raymond Hettingera63a3122011-01-26 20:34:14 +0000958 # Verify that filter is a keyword-only argument
959 with self.assertRaises(TypeError):
960 tar.add(tempdir, "empty_dir", True, None, filter)
961
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000962 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000963 try:
964 for tarinfo in tar:
965 self.assertEqual(tarinfo.uid, 123)
966 self.assertEqual(tarinfo.uname, "foo")
967 self.assertEqual(len(tar.getmembers()), 3)
968 finally:
969 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000970 finally:
971 shutil.rmtree(tempdir)
972
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000973 # Guarantee that stored pathnames are not modified. Don't
974 # remove ./ or ../ or double slashes. Still make absolute
975 # pathnames relative.
976 # For details see bug #6054.
977 def _test_pathname(self, path, cmp_path=None, dir=False):
978 # Create a tarfile with an empty member named path
979 # and compare the stored name with the original.
980 foo = os.path.join(TEMPDIR, "foo")
981 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +0200982 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000983 else:
984 os.mkdir(foo)
985
986 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000987 try:
988 tar.add(foo, arcname=path)
989 finally:
990 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000991
992 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000993 try:
994 t = tar.next()
995 finally:
996 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000997
998 if not dir:
999 os.remove(foo)
1000 else:
1001 os.rmdir(foo)
1002
1003 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1004
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001005
1006 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001007 def test_extractall_symlinks(self):
1008 # Test if extractall works properly when tarfile contains symlinks
1009 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1010 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1011 os.mkdir(tempdir)
1012 try:
1013 source_file = os.path.join(tempdir,'source')
1014 target_file = os.path.join(tempdir,'symlink')
1015 with open(source_file,'w') as f:
1016 f.write('something\n')
1017 os.symlink(source_file, target_file)
1018 tar = tarfile.open(temparchive,'w')
1019 tar.add(source_file)
1020 tar.add(target_file)
1021 tar.close()
1022 # Let's extract it to the location which contains the symlink
1023 tar = tarfile.open(temparchive,'r')
1024 # this should not raise OSError: [Errno 17] File exists
1025 try:
1026 tar.extractall(path=tempdir)
1027 except OSError:
1028 self.fail("extractall failed with symlinked files")
1029 finally:
1030 tar.close()
1031 finally:
1032 os.unlink(temparchive)
1033 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001034
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001035 def test_pathnames(self):
1036 self._test_pathname("foo")
1037 self._test_pathname(os.path.join("foo", ".", "bar"))
1038 self._test_pathname(os.path.join("foo", "..", "bar"))
1039 self._test_pathname(os.path.join(".", "foo"))
1040 self._test_pathname(os.path.join(".", "foo", "."))
1041 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1042 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1043 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1044 self._test_pathname(os.path.join("..", "foo"))
1045 self._test_pathname(os.path.join("..", "foo", ".."))
1046 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1047 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1048
1049 self._test_pathname("foo" + os.sep + os.sep + "bar")
1050 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1051
1052 def test_abs_pathnames(self):
1053 if sys.platform == "win32":
1054 self._test_pathname("C:\\foo", "foo")
1055 else:
1056 self._test_pathname("/foo", "foo")
1057 self._test_pathname("///foo", "foo")
1058
1059 def test_cwd(self):
1060 # Test adding the current working directory.
1061 cwd = os.getcwd()
1062 os.chdir(TEMPDIR)
1063 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001064 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001065 try:
1066 tar.add(".")
1067 finally:
1068 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001069
1070 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001071 try:
1072 for t in tar:
Ezio Melottib3aedd42010-11-20 19:04:17 +00001073 self.assertTrue(t.name == "." or t.name.startswith("./"))
Antoine Pitrou95f55602010-09-23 18:36:46 +00001074 finally:
1075 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001076 finally:
1077 os.chdir(cwd)
1078
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001079
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001080class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001081
Guido van Rossumd8faa362007-04-27 19:54:29 +00001082 mode = "w|"
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001083
Guido van Rossumd8faa362007-04-27 19:54:29 +00001084 def test_stream_padding(self):
1085 # Test for bug #1543303.
1086 tar = tarfile.open(tmpname, self.mode)
1087 tar.close()
1088
1089 if self.mode.endswith("gz"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001090 with gzip.GzipFile(tmpname) as fobj:
1091 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001092 elif self.mode.endswith("bz2"):
1093 dec = bz2.BZ2Decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001094 with open(tmpname, "rb") as fobj:
1095 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001096 data = dec.decompress(data)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001097 self.assertTrue(len(dec.unused_data) == 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001098 "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001099 else:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001100 with open(tmpname, "rb") as fobj:
1101 data = fobj.read()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001102
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001103 self.assertTrue(data.count(b"\0") == tarfile.RECORDSIZE,
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001104 "incorrect zero padding")
1105
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001106 def test_file_mode(self):
1107 # Test for issue #8464: Create files with correct
1108 # permissions.
1109 if sys.platform == "win32" or not hasattr(os, "umask"):
1110 return
1111
1112 if os.path.exists(tmpname):
1113 os.remove(tmpname)
1114
1115 original_umask = os.umask(0o022)
1116 try:
1117 tar = tarfile.open(tmpname, self.mode)
1118 tar.close()
1119 mode = os.stat(tmpname).st_mode & 0o777
1120 self.assertEqual(mode, 0o644, "wrong file permissions")
1121 finally:
1122 os.umask(original_umask)
1123
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001124
Guido van Rossumd8faa362007-04-27 19:54:29 +00001125class GNUWriteTest(unittest.TestCase):
1126 # This testcase checks for correct creation of GNU Longname
1127 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001128
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001129 def _length(self, s):
1130 blocks, remainder = divmod(len(s) + 1, 512)
1131 if remainder:
1132 blocks += 1
1133 return blocks * 512
1134
1135 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001136 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001137 count = 512
1138
1139 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001140 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001141 count += 512
1142 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001143 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001144 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001145 count += 512
1146 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001147 return count
1148
1149 def _test(self, name, link=None):
1150 tarinfo = tarfile.TarInfo(name)
1151 if link:
1152 tarinfo.linkname = link
1153 tarinfo.type = tarfile.LNKTYPE
1154
Guido van Rossumd8faa362007-04-27 19:54:29 +00001155 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001156 try:
1157 tar.format = tarfile.GNU_FORMAT
1158 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001159
Antoine Pitrou95f55602010-09-23 18:36:46 +00001160 v1 = self._calc_size(name, link)
1161 v2 = tar.offset
1162 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
1163 finally:
1164 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001165
Guido van Rossumd8faa362007-04-27 19:54:29 +00001166 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001167 try:
1168 member = tar.next()
1169 self.assertIsNotNone(member,
1170 "unable to read longname member")
1171 self.assertEqual(tarinfo.name, member.name,
1172 "unable to read longname member")
1173 self.assertEqual(tarinfo.linkname, member.linkname,
1174 "unable to read longname member")
1175 finally:
1176 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001177
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001178 def test_longname_1023(self):
1179 self._test(("longnam/" * 127) + "longnam")
1180
1181 def test_longname_1024(self):
1182 self._test(("longnam/" * 127) + "longname")
1183
1184 def test_longname_1025(self):
1185 self._test(("longnam/" * 127) + "longname_")
1186
1187 def test_longlink_1023(self):
1188 self._test("name", ("longlnk/" * 127) + "longlnk")
1189
1190 def test_longlink_1024(self):
1191 self._test("name", ("longlnk/" * 127) + "longlink")
1192
1193 def test_longlink_1025(self):
1194 self._test("name", ("longlnk/" * 127) + "longlink_")
1195
1196 def test_longnamelink_1023(self):
1197 self._test(("longnam/" * 127) + "longnam",
1198 ("longlnk/" * 127) + "longlnk")
1199
1200 def test_longnamelink_1024(self):
1201 self._test(("longnam/" * 127) + "longname",
1202 ("longlnk/" * 127) + "longlink")
1203
1204 def test_longnamelink_1025(self):
1205 self._test(("longnam/" * 127) + "longname_",
1206 ("longlnk/" * 127) + "longlink_")
1207
Guido van Rossumd8faa362007-04-27 19:54:29 +00001208
1209class HardlinkTest(unittest.TestCase):
1210 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001211
1212 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001213 self.foo = os.path.join(TEMPDIR, "foo")
1214 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001215
Antoine Pitrou95f55602010-09-23 18:36:46 +00001216 with open(self.foo, "wb") as fobj:
1217 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001218
Guido van Rossumd8faa362007-04-27 19:54:29 +00001219 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220
Guido van Rossumd8faa362007-04-27 19:54:29 +00001221 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001222 self.tar.add(self.foo)
1223
Guido van Rossumd8faa362007-04-27 19:54:29 +00001224 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001225 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001226 support.unlink(self.foo)
1227 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001228
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001229 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001230 # The same name will be added as a REGTYPE every
1231 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001232 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001233 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001234 "add file as regular failed")
1235
1236 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001237 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001238 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001239 "add file as hardlink failed")
1240
1241 def test_dereference_hardlink(self):
1242 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001243 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001244 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001245 "dereferencing hardlink failed")
1246
Neal Norwitza4f651a2004-07-20 22:07:44 +00001247
Guido van Rossumd8faa362007-04-27 19:54:29 +00001248class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001249
Guido van Rossumd8faa362007-04-27 19:54:29 +00001250 def _test(self, name, link=None):
1251 # See GNUWriteTest.
1252 tarinfo = tarfile.TarInfo(name)
1253 if link:
1254 tarinfo.linkname = link
1255 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001256
Guido van Rossumd8faa362007-04-27 19:54:29 +00001257 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001258 try:
1259 tar.addfile(tarinfo)
1260 finally:
1261 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001262
Guido van Rossumd8faa362007-04-27 19:54:29 +00001263 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001264 try:
1265 if link:
1266 l = tar.getmembers()[0].linkname
1267 self.assertTrue(link == l, "PAX longlink creation failed")
1268 else:
1269 n = tar.getmembers()[0].name
1270 self.assertTrue(name == n, "PAX longname creation failed")
1271 finally:
1272 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001273
Guido van Rossume7ba4952007-06-06 23:52:48 +00001274 def test_pax_global_header(self):
1275 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001276 "foo": "bar",
1277 "uid": "0",
1278 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001279 "test": "\xe4\xf6\xfc",
1280 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001281
Benjamin Peterson886af962010-03-21 23:13:07 +00001282 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001283 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001284 try:
1285 tar.addfile(tarfile.TarInfo("test"))
1286 finally:
1287 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001288
1289 # Test if the global header was written correctly.
1290 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001291 try:
1292 self.assertEqual(tar.pax_headers, pax_headers)
1293 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1294 # Test if all the fields are strings.
1295 for key, val in tar.pax_headers.items():
1296 self.assertTrue(type(key) is not bytes)
1297 self.assertTrue(type(val) is not bytes)
1298 if key in tarfile.PAX_NUMBER_FIELDS:
1299 try:
1300 tarfile.PAX_NUMBER_FIELDS[key](val)
1301 except (TypeError, ValueError):
1302 self.fail("unable to convert pax header field")
1303 finally:
1304 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001305
1306 def test_pax_extended_header(self):
1307 # The fields from the pax header have priority over the
1308 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001309 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001310
1311 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001312 try:
1313 t = tarfile.TarInfo()
1314 t.name = "\xe4\xf6\xfc" # non-ASCII
1315 t.uid = 8**8 # too large
1316 t.pax_headers = pax_headers
1317 tar.addfile(t)
1318 finally:
1319 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001320
1321 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001322 try:
1323 t = tar.getmembers()[0]
1324 self.assertEqual(t.pax_headers, pax_headers)
1325 self.assertEqual(t.name, "foo")
1326 self.assertEqual(t.uid, 123)
1327 finally:
1328 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001329
1330
1331class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001332
1333 format = tarfile.USTAR_FORMAT
1334
1335 def test_iso8859_1_filename(self):
1336 self._test_unicode_filename("iso8859-1")
1337
1338 def test_utf7_filename(self):
1339 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001340
1341 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001342 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001343
Guido van Rossumd8faa362007-04-27 19:54:29 +00001344 def _test_unicode_filename(self, encoding):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001345 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001346 try:
1347 name = "\xe4\xf6\xfc"
1348 tar.addfile(tarfile.TarInfo(name))
1349 finally:
1350 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001351
1352 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001353 try:
1354 self.assertEqual(tar.getmembers()[0].name, name)
1355 finally:
1356 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001357
1358 def test_unicode_filename_error(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001359 if self.format == tarfile.PAX_FORMAT:
1360 # PAX_FORMAT ignores encoding in write mode.
1361 return
1362
Guido van Rossume7ba4952007-06-06 23:52:48 +00001363 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001364 try:
1365 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001366
Antoine Pitrou95f55602010-09-23 18:36:46 +00001367 tarinfo.name = "\xe4\xf6\xfc"
1368 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001369
Antoine Pitrou95f55602010-09-23 18:36:46 +00001370 tarinfo.name = "foo"
1371 tarinfo.uname = "\xe4\xf6\xfc"
1372 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1373 finally:
1374 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001375
1376 def test_unicode_argument(self):
1377 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001378 try:
1379 for t in tar:
1380 self.assertTrue(type(t.name) is str)
1381 self.assertTrue(type(t.linkname) is str)
1382 self.assertTrue(type(t.uname) is str)
1383 self.assertTrue(type(t.gname) is str)
1384 finally:
1385 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001386
Guido van Rossume7ba4952007-06-06 23:52:48 +00001387 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001388 t = tarfile.TarInfo("foo")
1389 t.uname = "\xe4\xf6\xfc"
1390 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001391
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001392 tar = tarfile.open(tmpname, mode="w", format=self.format, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001393 try:
1394 tar.addfile(t)
1395 finally:
1396 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001397
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001398 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001399 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001400 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001401 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1402 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1403
1404 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001405 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001406 tar = tarfile.open(tmpname, encoding="ascii")
1407 t = tar.getmember("foo")
1408 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1409 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1410 finally:
1411 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001412
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001413
Guido van Rossume7ba4952007-06-06 23:52:48 +00001414class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001415
Guido van Rossume7ba4952007-06-06 23:52:48 +00001416 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001417
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001418 def test_bad_pax_header(self):
1419 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1420 # without a hdrcharset=BINARY header.
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001421 for encoding, name in (("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001422 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
1423 with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar:
1424 try:
1425 t = tar.getmember(name)
1426 except KeyError:
1427 self.fail("unable to read bad GNU tar pax header")
1428
Guido van Rossumd8faa362007-04-27 19:54:29 +00001429
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001430class PAXUnicodeTest(UstarUnicodeTest):
1431
1432 format = tarfile.PAX_FORMAT
1433
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001434 def test_binary_header(self):
1435 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001436 for encoding, name in (("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001437 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
1438 with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar:
1439 try:
1440 t = tar.getmember(name)
1441 except KeyError:
1442 self.fail("unable to read POSIX.1-2008 binary header")
1443
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001444
Guido van Rossumd8faa362007-04-27 19:54:29 +00001445class AppendTest(unittest.TestCase):
1446 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001447
Guido van Rossumd8faa362007-04-27 19:54:29 +00001448 def setUp(self):
1449 self.tarname = tmpname
1450 if os.path.exists(self.tarname):
1451 os.remove(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001452
Guido van Rossumd8faa362007-04-27 19:54:29 +00001453 def _add_testfile(self, fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001454 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1455 tar.addfile(tarfile.TarInfo("bar"))
Tim Peters8ceefc52004-10-25 03:19:41 +00001456
Guido van Rossumd8faa362007-04-27 19:54:29 +00001457 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001458 with tarfile.open(tarname, encoding="iso8859-1") as src:
1459 t = src.getmember("ustar/regtype")
1460 t.name = "foo"
1461 f = src.extractfile(t)
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001462 try:
1463 with tarfile.open(self.tarname, mode) as tar:
1464 tar.addfile(t, f)
1465 finally:
1466 f.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001467
Guido van Rossumd8faa362007-04-27 19:54:29 +00001468 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001469 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1470 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001471
1472 def test_non_existing(self):
1473 self._add_testfile()
1474 self._test()
1475
1476 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001477 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001478 self._add_testfile()
1479 self._test()
1480
1481 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001482 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001483 self._add_testfile(fobj)
1484 fobj.seek(0)
1485 self._test(fileobj=fobj)
1486
1487 def test_fileobj(self):
1488 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001489 with open(self.tarname, "rb") as fobj:
1490 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001491 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001492 self._add_testfile(fobj)
1493 fobj.seek(0)
1494 self._test(names=["foo", "bar"], fileobj=fobj)
1495
1496 def test_existing(self):
1497 self._create_testtar()
1498 self._add_testfile()
1499 self._test(names=["foo", "bar"])
1500
1501 def test_append_gz(self):
1502 if gzip is None:
1503 return
1504 self._create_testtar("w:gz")
1505 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1506
1507 def test_append_bz2(self):
1508 if bz2 is None:
1509 return
1510 self._create_testtar("w:bz2")
1511 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1512
Lars Gustäbel9520a432009-11-22 18:48:49 +00001513 # Append mode is supposed to fail if the tarfile to append to
1514 # does not end with a zero block.
1515 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001516 with open(self.tarname, "wb") as fobj:
1517 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001518 self.assertRaises(tarfile.ReadError, self._add_testfile)
1519
1520 def test_null(self):
1521 self._test_error(b"")
1522
1523 def test_incomplete(self):
1524 self._test_error(b"\0" * 13)
1525
1526 def test_premature_eof(self):
1527 data = tarfile.TarInfo("foo").tobuf()
1528 self._test_error(data)
1529
1530 def test_trailing_garbage(self):
1531 data = tarfile.TarInfo("foo").tobuf()
1532 self._test_error(data + b"\0" * 13)
1533
1534 def test_invalid(self):
1535 self._test_error(b"a" * 512)
1536
Guido van Rossumd8faa362007-04-27 19:54:29 +00001537
1538class LimitsTest(unittest.TestCase):
1539
1540 def test_ustar_limits(self):
1541 # 100 char name
1542 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001543 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001544
1545 # 101 char name that cannot be stored
1546 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001547 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001548
1549 # 256 char name with a slash at pos 156
1550 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001551 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001552
1553 # 256 char name that cannot be stored
1554 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001555 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001556
1557 # 512 char name
1558 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001559 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001560
1561 # 512 char linkname
1562 tarinfo = tarfile.TarInfo("longlink")
1563 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001564 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001565
1566 # uid > 8 digits
1567 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001568 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001569 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001570
1571 def test_gnu_limits(self):
1572 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001573 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001574
1575 tarinfo = tarfile.TarInfo("longlink")
1576 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001577 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001578
1579 # uid >= 256 ** 7
1580 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001581 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001582 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001583
1584 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001585 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001586 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001587
1588 tarinfo = tarfile.TarInfo("longlink")
1589 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001590 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001591
1592 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001593 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001594 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001595
1596
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001597class MiscTest(unittest.TestCase):
1598
1599 def test_char_fields(self):
1600 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"), b"foo\0\0\0\0\0")
1601 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"), b"foo")
1602 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"), "foo")
1603 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"), "foo")
1604
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001605 def test_read_number_fields(self):
1606 # Issue 13158: Test if GNU tar specific base-256 number fields
1607 # are decoded correctly.
1608 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1609 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
1610 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"), 0o10000000)
1611 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"), 0xffffffff)
1612 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"), -1)
1613 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"), -100)
1614 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"), -0x100000000000000)
1615
1616 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001617 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001618 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
1619 self.assertEqual(tarfile.itn(0o10000000), b"\x80\x00\x00\x00\x00\x20\x00\x00")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001620 self.assertEqual(tarfile.itn(0xffffffff), b"\x80\x00\x00\x00\xff\xff\xff\xff")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001621 self.assertEqual(tarfile.itn(-1), b"\xff\xff\xff\xff\xff\xff\xff\xff")
1622 self.assertEqual(tarfile.itn(-100), b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1623 self.assertEqual(tarfile.itn(-0x100000000000000), b"\xff\x00\x00\x00\x00\x00\x00\x00")
1624
1625 def test_number_field_limits(self):
1626 self.assertRaises(ValueError, tarfile.itn, -1, 8, tarfile.USTAR_FORMAT)
1627 self.assertRaises(ValueError, tarfile.itn, 0o10000000, 8, tarfile.USTAR_FORMAT)
1628 self.assertRaises(ValueError, tarfile.itn, -0x10000000001, 6, tarfile.GNU_FORMAT)
1629 self.assertRaises(ValueError, tarfile.itn, 0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001630
1631
Lars Gustäbel01385812010-03-03 12:08:54 +00001632class ContextManagerTest(unittest.TestCase):
1633
1634 def test_basic(self):
1635 with tarfile.open(tarname) as tar:
1636 self.assertFalse(tar.closed, "closed inside runtime context")
1637 self.assertTrue(tar.closed, "context manager failed")
1638
1639 def test_closed(self):
1640 # The __enter__() method is supposed to raise IOError
1641 # if the TarFile object is already closed.
1642 tar = tarfile.open(tarname)
1643 tar.close()
1644 with self.assertRaises(IOError):
1645 with tar:
1646 pass
1647
1648 def test_exception(self):
1649 # Test if the IOError exception is passed through properly.
1650 with self.assertRaises(Exception) as exc:
1651 with tarfile.open(tarname) as tar:
1652 raise IOError
1653 self.assertIsInstance(exc.exception, IOError,
1654 "wrong exception raised in context manager")
1655 self.assertTrue(tar.closed, "context manager failed")
1656
1657 def test_no_eof(self):
1658 # __exit__() must not write end-of-archive blocks if an
1659 # exception was raised.
1660 try:
1661 with tarfile.open(tmpname, "w") as tar:
1662 raise Exception
1663 except:
1664 pass
1665 self.assertEqual(os.path.getsize(tmpname), 0,
1666 "context manager wrote an end-of-archive block")
1667 self.assertTrue(tar.closed, "context manager failed")
1668
1669 def test_eof(self):
1670 # __exit__() must write end-of-archive blocks, i.e. call
1671 # TarFile.close() if there was no error.
1672 with tarfile.open(tmpname, "w"):
1673 pass
1674 self.assertNotEqual(os.path.getsize(tmpname), 0,
1675 "context manager wrote no end-of-archive block")
1676
1677 def test_fileobj(self):
1678 # Test that __exit__() did not close the external file
1679 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001680 with open(tmpname, "wb") as fobj:
1681 try:
1682 with tarfile.open(fileobj=fobj, mode="w") as tar:
1683 raise Exception
1684 except:
1685 pass
1686 self.assertFalse(fobj.closed, "external file object was closed")
1687 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00001688
1689
Lars Gustäbel1b512722010-06-03 12:45:16 +00001690class LinkEmulationTest(ReadTest):
1691
1692 # Test for issue #8741 regression. On platforms that do not support
1693 # symbolic or hard links tarfile tries to extract these types of members as
1694 # the regular files they point to.
1695 def _test_link_extraction(self, name):
1696 self.tar.extract(name, TEMPDIR)
1697 data = open(os.path.join(TEMPDIR, name), "rb").read()
1698 self.assertEqual(md5sum(data), md5_regtype)
1699
Brian Curtind40e6f72010-07-08 21:39:08 +00001700 # When 8879 gets fixed, this will need to change. Currently on Windows
1701 # we have os.path.islink but no os.link, so these tests fail without the
1702 # following skip until link is completed.
1703 @unittest.skipIf(hasattr(os.path, "islink"),
1704 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001705 def test_hardlink_extraction1(self):
1706 self._test_link_extraction("ustar/lnktype")
1707
Brian Curtind40e6f72010-07-08 21:39:08 +00001708 @unittest.skipIf(hasattr(os.path, "islink"),
1709 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001710 def test_hardlink_extraction2(self):
1711 self._test_link_extraction("./ustar/linktest2/lnktype")
1712
Brian Curtin74e45612010-07-09 15:58:59 +00001713 @unittest.skipIf(hasattr(os, "symlink"),
1714 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001715 def test_symlink_extraction1(self):
1716 self._test_link_extraction("ustar/symtype")
1717
Brian Curtin74e45612010-07-09 15:58:59 +00001718 @unittest.skipIf(hasattr(os, "symlink"),
1719 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001720 def test_symlink_extraction2(self):
1721 self._test_link_extraction("./ustar/linktest2/symtype")
1722
1723
Guido van Rossumd8faa362007-04-27 19:54:29 +00001724class GzipMiscReadTest(MiscReadTest):
1725 tarname = gzipname
1726 mode = "r:gz"
Georg Brandl3abb3722011-08-13 11:48:12 +02001727
1728 def test_non_existent_targz_file(self):
1729 # Test for issue11513: prevent non-existent gzipped tarfiles raising
1730 # multiple exceptions.
1731 with self.assertRaisesRegex(IOError, "xxx") as ex:
1732 tarfile.open("xxx", self.mode)
1733 self.assertEqual(ex.exception.errno, errno.ENOENT)
1734
Guido van Rossumd8faa362007-04-27 19:54:29 +00001735class GzipUstarReadTest(UstarReadTest):
1736 tarname = gzipname
1737 mode = "r:gz"
1738class GzipStreamReadTest(StreamReadTest):
1739 tarname = gzipname
1740 mode = "r|gz"
1741class GzipWriteTest(WriteTest):
1742 mode = "w:gz"
1743class GzipStreamWriteTest(StreamWriteTest):
1744 mode = "w|gz"
1745
1746
1747class Bz2MiscReadTest(MiscReadTest):
1748 tarname = bz2name
1749 mode = "r:bz2"
1750class Bz2UstarReadTest(UstarReadTest):
1751 tarname = bz2name
1752 mode = "r:bz2"
1753class Bz2StreamReadTest(StreamReadTest):
1754 tarname = bz2name
1755 mode = "r|bz2"
1756class Bz2WriteTest(WriteTest):
1757 mode = "w:bz2"
1758class Bz2StreamWriteTest(StreamWriteTest):
1759 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001760
Lars Gustäbel42e00912009-03-22 20:34:29 +00001761class Bz2PartialReadTest(unittest.TestCase):
1762 # Issue5068: The _BZ2Proxy.read() method loops forever
1763 # on an empty or partial bzipped file.
1764
1765 def _test_partial_input(self, mode):
1766 class MyBytesIO(io.BytesIO):
1767 hit_eof = False
1768 def read(self, n):
1769 if self.hit_eof:
1770 raise AssertionError("infinite loop detected in tarfile.open()")
1771 self.hit_eof = self.tell() == len(self.getvalue())
1772 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001773 def seek(self, *args):
1774 self.hit_eof = False
1775 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00001776
1777 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1778 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001779 try:
1780 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
1781 except tarfile.ReadError:
1782 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00001783
1784 def test_partial_input(self):
1785 self._test_partial_input("r")
1786
1787 def test_partial_input_bz2(self):
1788 self._test_partial_input("r:bz2")
1789
1790
Neal Norwitz996acf12003-02-17 14:51:41 +00001791def test_main():
Antoine Pitrou95f55602010-09-23 18:36:46 +00001792 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00001793 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001794
Walter Dörwald21d3a322003-05-01 17:45:56 +00001795 tests = [
Guido van Rossumd8faa362007-04-27 19:54:29 +00001796 UstarReadTest,
1797 MiscReadTest,
1798 StreamReadTest,
1799 DetectReadTest,
1800 MemberReadTest,
1801 GNUReadTest,
1802 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001803 WriteTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001804 StreamWriteTest,
1805 GNUWriteTest,
1806 PaxWriteTest,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001807 UstarUnicodeTest,
1808 GNUUnicodeTest,
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001809 PAXUnicodeTest,
Thomas Wouterscf297e42007-02-23 15:07:44 +00001810 AppendTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001811 LimitsTest,
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001812 MiscTest,
Lars Gustäbel01385812010-03-03 12:08:54 +00001813 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001814 ]
1815
Neal Norwitza4f651a2004-07-20 22:07:44 +00001816 if hasattr(os, "link"):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001817 tests.append(HardlinkTest)
Lars Gustäbel1b512722010-06-03 12:45:16 +00001818 else:
1819 tests.append(LinkEmulationTest)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001820
Antoine Pitrou95f55602010-09-23 18:36:46 +00001821 with open(tarname, "rb") as fobj:
1822 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001823
Walter Dörwald21d3a322003-05-01 17:45:56 +00001824 if gzip:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001825 # Create testtar.tar.gz and add gzip-specific tests.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001826 support.unlink(gzipname)
1827 with gzip.open(gzipname, "wb") as tar:
1828 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001829
1830 tests += [
1831 GzipMiscReadTest,
1832 GzipUstarReadTest,
1833 GzipStreamReadTest,
1834 GzipWriteTest,
1835 GzipStreamWriteTest,
1836 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001837
1838 if bz2:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001839 # Create testtar.tar.bz2 and add bz2-specific tests.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001840 support.unlink(bz2name)
Lars Gustäbeled1ac582011-12-06 12:56:38 +01001841 with bz2.BZ2File(bz2name, "wb") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001842 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001843
1844 tests += [
1845 Bz2MiscReadTest,
1846 Bz2UstarReadTest,
1847 Bz2StreamReadTest,
1848 Bz2WriteTest,
1849 Bz2StreamWriteTest,
Lars Gustäbel42e00912009-03-22 20:34:29 +00001850 Bz2PartialReadTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001851 ]
1852
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001853 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001854 support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001855 finally:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001856 if os.path.exists(TEMPDIR):
1857 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001858
Neal Norwitz996acf12003-02-17 14:51:41 +00001859if __name__ == "__main__":
1860 test_main()