blob: a53181e56c298ea895b9a3e5a31ef21f56c36da6 [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")
Antoine Pitrou95f55602010-09-23 18:36:46 +000085 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rU") as fobj1:
86 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
Lars Gustäbel1ef9eda2012-04-24 21:04:40 +0200169 def test_issue14160(self):
170 self._test_fileobj_link("symtype2", "ustar/regtype")
171
Guido van Rossumd8faa362007-04-27 19:54:29 +0000172
Lars Gustäbel9520a432009-11-22 18:48:49 +0000173class CommonReadTest(ReadTest):
174
175 def test_empty_tarfile(self):
176 # Test for issue6123: Allow opening empty archives.
177 # This test checks if tarfile.open() is able to open an empty tar
178 # archive successfully. Note that an empty tar archive is not the
179 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000180 with tarfile.open(tmpname, self.mode.replace("r", "w")):
181 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000182 try:
183 tar = tarfile.open(tmpname, self.mode)
184 tar.getnames()
185 except tarfile.ReadError:
186 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000187 else:
188 self.assertListEqual(tar.getmembers(), [])
189 finally:
190 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000191
192 def test_null_tarfile(self):
193 # Test for issue6123: Allow opening empty archives.
194 # This test guarantees that tarfile.open() does not treat an empty
195 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000196 with open(tmpname, "wb"):
197 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000198 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
199 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
200
201 def test_ignore_zeros(self):
202 # Test TarFile's ignore_zeros option.
203 if self.mode.endswith(":gz"):
204 _open = gzip.GzipFile
205 elif self.mode.endswith(":bz2"):
206 _open = bz2.BZ2File
207 else:
208 _open = open
209
210 for char in (b'\0', b'a'):
211 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
212 # are ignored correctly.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000213 with _open(tmpname, "wb") as fobj:
214 fobj.write(char * 1024)
215 fobj.write(tarfile.TarInfo("foo").tobuf())
Lars Gustäbel9520a432009-11-22 18:48:49 +0000216
217 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000218 try:
219 self.assertListEqual(tar.getnames(), ["foo"],
Lars Gustäbel9520a432009-11-22 18:48:49 +0000220 "ignore_zeros=True should have skipped the %r-blocks" % char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000221 finally:
222 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000223
224
225class MiscReadTest(CommonReadTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
Thomas Woutersed03b412007-08-28 21:37:11 +0000227 def test_no_name_argument(self):
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).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200331 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000332 tar.extract("ustar/regtype", TEMPDIR)
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200333 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000334
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200335 tar.extract("ustar/lnktype", TEMPDIR)
336 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000337 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
338 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000339 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000340
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200341 tar.extract("ustar/symtype", TEMPDIR)
342 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000343 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
344 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000345 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000346
Christian Heimesfaf2f632008-01-06 16:59:19 +0000347 def test_extractall(self):
348 # Test if extractall() correctly restores directory permissions
349 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000350 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000351 DIR = os.path.join(TEMPDIR, "extractall")
352 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000353 try:
354 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000355 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000356 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000357 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000358 if sys.platform != "win32":
359 # Win32 has no support for fine grained permissions.
360 self.assertEqual(tarinfo.mode & 0o777, os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000361 def format_mtime(mtime):
362 if isinstance(mtime, float):
363 return "{} ({})".format(mtime, mtime.hex())
364 else:
365 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000366 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000367 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
368 format_mtime(tarinfo.mtime),
369 format_mtime(file_mtime),
370 path)
371 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000372 finally:
373 tar.close()
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000374 shutil.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000375
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000376 def test_extract_directory(self):
377 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000378 DIR = os.path.join(TEMPDIR, "extractdir")
379 os.mkdir(DIR)
380 try:
381 with tarfile.open(tarname, encoding="iso8859-1") as tar:
382 tarinfo = tar.getmember(dirtype)
383 tar.extract(tarinfo, path=DIR)
384 extracted = os.path.join(DIR, dirtype)
385 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
386 if sys.platform != "win32":
387 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
388 finally:
389 shutil.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000390
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000391 def test_init_close_fobj(self):
392 # Issue #7341: Close the internal file object in the TarFile
393 # constructor in case of an error. For the test we rely on
394 # the fact that opening an empty file raises a ReadError.
395 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000396 with open(empty, "wb") as fobj:
397 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000398
399 try:
400 tar = object.__new__(tarfile.TarFile)
401 try:
402 tar.__init__(empty)
403 except tarfile.ReadError:
404 self.assertTrue(tar.fileobj.closed)
405 else:
406 self.fail("ReadError not raised")
407 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000408 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000409
Guido van Rossumd8faa362007-04-27 19:54:29 +0000410
Lars Gustäbel9520a432009-11-22 18:48:49 +0000411class StreamReadTest(CommonReadTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000412
413 mode="r|"
414
Lars Gustäbel9f6cbe02011-02-23 11:52:31 +0000415 def test_read_through(self):
416 # Issue #11224: A poorly designed _FileInFile.read() method
417 # caused seeking errors with stream tar files.
418 for tarinfo in self.tar:
419 if not tarinfo.isreg():
420 continue
421 fobj = self.tar.extractfile(tarinfo)
422 while True:
423 try:
424 buf = fobj.read(512)
425 except tarfile.StreamError:
426 self.fail("simple read-through using TarFile.extractfile() failed")
427 if not buf:
428 break
429 fobj.close()
430
Guido van Rossumd8faa362007-04-27 19:54:29 +0000431 def test_fileobj_regular_file(self):
432 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
433 fobj = self.tar.extractfile(tarinfo)
434 data = fobj.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000435 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000436 "regular file extraction failed")
437
438 def test_provoke_stream_error(self):
439 tarinfos = self.tar.getmembers()
440 f = self.tar.extractfile(tarinfos[0]) # read the first member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000441 self.assertRaises(tarfile.StreamError, f.read)
442
Guido van Rossumd8faa362007-04-27 19:54:29 +0000443 def test_compare_members(self):
444 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000445 try:
446 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000447
Antoine Pitrou95f55602010-09-23 18:36:46 +0000448 while True:
449 t1 = tar1.next()
450 t2 = tar2.next()
451 if t1 is None:
452 break
453 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000454
Antoine Pitrou95f55602010-09-23 18:36:46 +0000455 if t2.islnk() or t2.issym():
456 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
457 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000458
Antoine Pitrou95f55602010-09-23 18:36:46 +0000459 v1 = tar1.extractfile(t1)
460 v2 = tar2.extractfile(t2)
461 if v1 is None:
462 continue
463 self.assertTrue(v2 is not None, "stream.extractfile() failed")
464 self.assertEqual(v1.read(), v2.read(), "stream extraction failed")
465 finally:
466 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000467
Thomas Wouters89f507f2006-12-13 04:49:30 +0000468
Guido van Rossumd8faa362007-04-27 19:54:29 +0000469class DetectReadTest(unittest.TestCase):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000470
Guido van Rossumd8faa362007-04-27 19:54:29 +0000471 def _testfunc_file(self, name, mode):
472 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000473 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000474 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000475 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000476 else:
477 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000478
Guido van Rossumd8faa362007-04-27 19:54:29 +0000479 def _testfunc_fileobj(self, name, mode):
480 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000481 with open(name, "rb") as f:
482 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000483 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000484 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000485 else:
486 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487
488 def _test_modes(self, testfunc):
489 testfunc(tarname, "r")
490 testfunc(tarname, "r:")
491 testfunc(tarname, "r:*")
492 testfunc(tarname, "r|")
493 testfunc(tarname, "r|*")
494
495 if gzip:
496 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
497 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
498 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
499 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
500
501 testfunc(gzipname, "r")
502 testfunc(gzipname, "r:*")
503 testfunc(gzipname, "r:gz")
504 testfunc(gzipname, "r|*")
505 testfunc(gzipname, "r|gz")
506
507 if bz2:
508 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
509 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
510 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
511 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
512
513 testfunc(bz2name, "r")
514 testfunc(bz2name, "r:*")
515 testfunc(bz2name, "r:bz2")
516 testfunc(bz2name, "r|*")
517 testfunc(bz2name, "r|bz2")
518
519 def test_detect_file(self):
520 self._test_modes(self._testfunc_file)
521
522 def test_detect_fileobj(self):
523 self._test_modes(self._testfunc_fileobj)
524
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100525 def test_detect_stream_bz2(self):
526 # Originally, tarfile's stream detection looked for the string
527 # "BZh91" at the start of the file. This is incorrect because
528 # the '9' represents the blocksize (900kB). If the file was
529 # compressed using another blocksize autodetection fails.
530 if not bz2:
531 return
532
533 with open(tarname, "rb") as fobj:
534 data = fobj.read()
535
536 # Compress with blocksize 100kB, the file starts with "BZh11".
537 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
538 fobj.write(data)
539
540 self._testfunc_file(tmpname, "r|*")
541
Guido van Rossumd8faa362007-04-27 19:54:29 +0000542
543class MemberReadTest(ReadTest):
544
545 def _test_member(self, tarinfo, chksum=None, **kwargs):
546 if chksum is not None:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000547 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000548 "wrong md5sum for %s" % tarinfo.name)
549
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000550 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000551 kwargs["uid"] = 1000
552 kwargs["gid"] = 100
553 if "old-v7" not in tarinfo.name:
554 # V7 tar can't handle alphabetic owners.
555 kwargs["uname"] = "tarfile"
556 kwargs["gname"] = "tarfile"
557 for k, v in kwargs.items():
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000558 self.assertTrue(getattr(tarinfo, k) == v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000559 "wrong value in %s field of %s" % (k, tarinfo.name))
560
561 def test_find_regtype(self):
562 tarinfo = self.tar.getmember("ustar/regtype")
563 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
564
565 def test_find_conttype(self):
566 tarinfo = self.tar.getmember("ustar/conttype")
567 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
568
569 def test_find_dirtype(self):
570 tarinfo = self.tar.getmember("ustar/dirtype")
571 self._test_member(tarinfo, size=0)
572
573 def test_find_dirtype_with_size(self):
574 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
575 self._test_member(tarinfo, size=255)
576
577 def test_find_lnktype(self):
578 tarinfo = self.tar.getmember("ustar/lnktype")
579 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
580
581 def test_find_symtype(self):
582 tarinfo = self.tar.getmember("ustar/symtype")
583 self._test_member(tarinfo, size=0, linkname="regtype")
584
585 def test_find_blktype(self):
586 tarinfo = self.tar.getmember("ustar/blktype")
587 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
588
589 def test_find_chrtype(self):
590 tarinfo = self.tar.getmember("ustar/chrtype")
591 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
592
593 def test_find_fifotype(self):
594 tarinfo = self.tar.getmember("ustar/fifotype")
595 self._test_member(tarinfo, size=0)
596
597 def test_find_sparse(self):
598 tarinfo = self.tar.getmember("ustar/sparse")
599 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
600
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000601 def test_find_gnusparse(self):
602 tarinfo = self.tar.getmember("gnu/sparse")
603 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
604
605 def test_find_gnusparse_00(self):
606 tarinfo = self.tar.getmember("gnu/sparse-0.0")
607 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
608
609 def test_find_gnusparse_01(self):
610 tarinfo = self.tar.getmember("gnu/sparse-0.1")
611 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
612
613 def test_find_gnusparse_10(self):
614 tarinfo = self.tar.getmember("gnu/sparse-1.0")
615 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
616
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617 def test_find_umlauts(self):
Guido van Rossuma0557702007-08-07 23:19:53 +0000618 tarinfo = self.tar.getmember("ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000619 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
620
621 def test_find_ustar_longname(self):
622 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000623 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000624
625 def test_find_regtype_oldv7(self):
626 tarinfo = self.tar.getmember("misc/regtype-old-v7")
627 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
628
629 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000630 self.tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000631 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Guido van Rossuma0557702007-08-07 23:19:53 +0000632 tarinfo = self.tar.getmember("pax/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
634
635
636class LongnameTest(ReadTest):
637
638 def test_read_longname(self):
639 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000640 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000642 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000643 except KeyError:
644 self.fail("longname not found")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000645 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000646
647 def test_read_longlink(self):
648 longname = self.subdir + "/" + "123/" * 125 + "longname"
649 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
650 try:
651 tarinfo = self.tar.getmember(longlink)
652 except KeyError:
653 self.fail("longlink not found")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000654 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000655
656 def test_truncated_longname(self):
657 longname = self.subdir + "/" + "123/" * 125 + "longname"
658 tarinfo = self.tar.getmember(longname)
659 offset = tarinfo.offset
660 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000661 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000662 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
663
Guido van Rossume7ba4952007-06-06 23:52:48 +0000664 def test_header_offset(self):
665 # Test if the start offset of the TarInfo object includes
666 # the preceding extended header.
667 longname = self.subdir + "/" + "123/" * 125 + "longname"
668 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000669 with open(tarname, "rb") as fobj:
670 fobj.seek(offset)
671 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512), "iso8859-1", "strict")
672 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000673
Guido van Rossumd8faa362007-04-27 19:54:29 +0000674
675class GNUReadTest(LongnameTest):
676
677 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000678 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000679
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000680 # Since 3.2 tarfile is supposed to accurately restore sparse members and
681 # produce files with holes. This is what we actually want to test here.
682 # Unfortunately, not all platforms/filesystems support sparse files, and
683 # even on platforms that do it is non-trivial to make reliable assertions
684 # about holes in files. Therefore, we first do one basic test which works
685 # an all platforms, and after that a test that will work only on
686 # platforms/filesystems that prove to support sparse files.
687 def _test_sparse_file(self, name):
688 self.tar.extract(name, TEMPDIR)
689 filename = os.path.join(TEMPDIR, name)
690 with open(filename, "rb") as fobj:
691 data = fobj.read()
692 self.assertEqual(md5sum(data), md5_sparse,
693 "wrong md5sum for %s" % name)
694
695 if self._fs_supports_holes():
696 s = os.stat(filename)
697 self.assertTrue(s.st_blocks * 512 < s.st_size)
698
699 def test_sparse_file_old(self):
700 self._test_sparse_file("gnu/sparse")
701
702 def test_sparse_file_00(self):
703 self._test_sparse_file("gnu/sparse-0.0")
704
705 def test_sparse_file_01(self):
706 self._test_sparse_file("gnu/sparse-0.1")
707
708 def test_sparse_file_10(self):
709 self._test_sparse_file("gnu/sparse-1.0")
710
711 @staticmethod
712 def _fs_supports_holes():
713 # Return True if the platform knows the st_blocks stat attribute and
714 # uses st_blocks units of 512 bytes, and if the filesystem is able to
715 # store holes in files.
716 if sys.platform == "linux2":
717 # Linux evidentially has 512 byte st_blocks units.
718 name = os.path.join(TEMPDIR, "sparse-test")
719 with open(name, "wb") as fobj:
720 fobj.seek(4096)
721 fobj.truncate()
722 s = os.stat(name)
723 os.remove(name)
724 return s.st_blocks == 0
725 else:
726 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000727
728
Guido van Rossume7ba4952007-06-06 23:52:48 +0000729class PaxReadTest(LongnameTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000730
731 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000732 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000733
Guido van Rossume7ba4952007-06-06 23:52:48 +0000734 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000735 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000736 try:
737 tarinfo = tar.getmember("pax/regtype1")
738 self.assertEqual(tarinfo.uname, "foo")
739 self.assertEqual(tarinfo.gname, "bar")
740 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000741
Antoine Pitrou95f55602010-09-23 18:36:46 +0000742 tarinfo = tar.getmember("pax/regtype2")
743 self.assertEqual(tarinfo.uname, "")
744 self.assertEqual(tarinfo.gname, "bar")
745 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000746
Antoine Pitrou95f55602010-09-23 18:36:46 +0000747 tarinfo = tar.getmember("pax/regtype3")
748 self.assertEqual(tarinfo.uname, "tarfile")
749 self.assertEqual(tarinfo.gname, "tarfile")
750 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
751 finally:
752 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000753
754 def test_pax_number_fields(self):
755 # All following number fields are read from the pax header.
756 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000757 try:
758 tarinfo = tar.getmember("pax/regtype4")
759 self.assertEqual(tarinfo.size, 7011)
760 self.assertEqual(tarinfo.uid, 123)
761 self.assertEqual(tarinfo.gid, 123)
762 self.assertEqual(tarinfo.mtime, 1041808783.0)
763 self.assertEqual(type(tarinfo.mtime), float)
764 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
765 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
766 finally:
767 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000768
769
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000770class WriteTestBase(unittest.TestCase):
771 # Put all write tests in here that are supposed to be tested
772 # in all possible mode combinations.
773
774 def test_fileobj_no_close(self):
775 fobj = io.BytesIO()
776 tar = tarfile.open(fileobj=fobj, mode=self.mode)
777 tar.addfile(tarfile.TarInfo("foo"))
778 tar.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000779 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000780
781
782class WriteTest(WriteTestBase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000783
784 mode = "w:"
785
786 def test_100_char_name(self):
787 # The name field in a tar header stores strings of at most 100 chars.
788 # If a string is shorter than 100 chars it has to be padded with '\0',
789 # which implies that a string of exactly 100 chars is stored without
790 # a trailing '\0'.
791 name = "0123456789" * 10
792 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000793 try:
794 t = tarfile.TarInfo(name)
795 tar.addfile(t)
796 finally:
797 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000798
Guido van Rossumd8faa362007-04-27 19:54:29 +0000799 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000800 try:
801 self.assertTrue(tar.getnames()[0] == name,
802 "failed to store 100 char filename")
803 finally:
804 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000805
Guido van Rossumd8faa362007-04-27 19:54:29 +0000806 def test_tar_size(self):
807 # Test for bug #1013882.
808 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000809 try:
810 path = os.path.join(TEMPDIR, "file")
811 with open(path, "wb") as fobj:
812 fobj.write(b"aaa")
813 tar.add(path)
814 finally:
815 tar.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000816 self.assertTrue(os.path.getsize(tmpname) > 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000817 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000818
Guido van Rossumd8faa362007-04-27 19:54:29 +0000819 # The test_*_size tests test for bug #1167128.
820 def test_file_size(self):
821 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000822 try:
823 path = os.path.join(TEMPDIR, "file")
824 with open(path, "wb"):
825 pass
826 tarinfo = tar.gettarinfo(path)
827 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000828
Antoine Pitrou95f55602010-09-23 18:36:46 +0000829 with open(path, "wb") as fobj:
830 fobj.write(b"aaa")
831 tarinfo = tar.gettarinfo(path)
832 self.assertEqual(tarinfo.size, 3)
833 finally:
834 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000835
836 def test_directory_size(self):
837 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000838 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000839 try:
840 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000841 try:
842 tarinfo = tar.gettarinfo(path)
843 self.assertEqual(tarinfo.size, 0)
844 finally:
845 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000846 finally:
847 os.rmdir(path)
848
849 def test_link_size(self):
850 if hasattr(os, "link"):
851 link = os.path.join(TEMPDIR, "link")
852 target = os.path.join(TEMPDIR, "link_target")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000853 with open(target, "wb") as fobj:
854 fobj.write(b"aaa")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000855 os.link(target, link)
856 try:
857 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000858 try:
859 # Record the link target in the inodes list.
860 tar.gettarinfo(target)
861 tarinfo = tar.gettarinfo(link)
862 self.assertEqual(tarinfo.size, 0)
863 finally:
864 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000865 finally:
866 os.remove(target)
867 os.remove(link)
868
Brian Curtin3b4499c2010-12-28 14:31:47 +0000869 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000870 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +0000871 path = os.path.join(TEMPDIR, "symlink")
872 os.symlink("link_target", path)
873 try:
874 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000875 try:
876 tarinfo = tar.gettarinfo(path)
877 self.assertEqual(tarinfo.size, 0)
878 finally:
879 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +0000880 finally:
881 os.remove(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000882
883 def test_add_self(self):
884 # Test for #1257255.
885 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000886 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000887 try:
888 self.assertTrue(tar.name == dstname, "archive name must be absolute")
889 tar.add(dstname)
890 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000891
Antoine Pitrou95f55602010-09-23 18:36:46 +0000892 cwd = os.getcwd()
893 os.chdir(TEMPDIR)
894 tar.add(dstname)
895 os.chdir(cwd)
896 self.assertTrue(tar.getnames() == [], "added the archive to itself")
897 finally:
898 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000899
Guido van Rossum486364b2007-06-30 05:01:58 +0000900 def test_exclude(self):
901 tempdir = os.path.join(TEMPDIR, "exclude")
902 os.mkdir(tempdir)
903 try:
904 for name in ("foo", "bar", "baz"):
905 name = os.path.join(tempdir, name)
906 open(name, "wb").close()
907
Benjamin Peterson886af962010-03-21 23:13:07 +0000908 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +0000909
910 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000911 try:
912 with support.check_warnings(("use the filter argument",
913 DeprecationWarning)):
914 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
915 finally:
916 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000917
918 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000919 try:
920 self.assertEqual(len(tar.getmembers()), 1)
921 self.assertEqual(tar.getnames()[0], "empty_dir")
922 finally:
923 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000924 finally:
925 shutil.rmtree(tempdir)
926
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000927 def test_filter(self):
928 tempdir = os.path.join(TEMPDIR, "filter")
929 os.mkdir(tempdir)
930 try:
931 for name in ("foo", "bar", "baz"):
932 name = os.path.join(tempdir, name)
933 open(name, "wb").close()
934
935 def filter(tarinfo):
936 if os.path.basename(tarinfo.name) == "bar":
937 return
938 tarinfo.uid = 123
939 tarinfo.uname = "foo"
940 return tarinfo
941
942 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000943 try:
944 tar.add(tempdir, arcname="empty_dir", filter=filter)
945 finally:
946 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000947
Raymond Hettingera63a3122011-01-26 20:34:14 +0000948 # Verify that filter is a keyword-only argument
949 with self.assertRaises(TypeError):
950 tar.add(tempdir, "empty_dir", True, None, filter)
951
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000952 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000953 try:
954 for tarinfo in tar:
955 self.assertEqual(tarinfo.uid, 123)
956 self.assertEqual(tarinfo.uname, "foo")
957 self.assertEqual(len(tar.getmembers()), 3)
958 finally:
959 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000960 finally:
961 shutil.rmtree(tempdir)
962
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000963 # Guarantee that stored pathnames are not modified. Don't
964 # remove ./ or ../ or double slashes. Still make absolute
965 # pathnames relative.
966 # For details see bug #6054.
967 def _test_pathname(self, path, cmp_path=None, dir=False):
968 # Create a tarfile with an empty member named path
969 # and compare the stored name with the original.
970 foo = os.path.join(TEMPDIR, "foo")
971 if not dir:
972 open(foo, "w").close()
973 else:
974 os.mkdir(foo)
975
976 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000977 try:
978 tar.add(foo, arcname=path)
979 finally:
980 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000981
982 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000983 try:
984 t = tar.next()
985 finally:
986 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000987
988 if not dir:
989 os.remove(foo)
990 else:
991 os.rmdir(foo)
992
993 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
994
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +0800995
996 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +0800997 def test_extractall_symlinks(self):
998 # Test if extractall works properly when tarfile contains symlinks
999 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1000 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1001 os.mkdir(tempdir)
1002 try:
1003 source_file = os.path.join(tempdir,'source')
1004 target_file = os.path.join(tempdir,'symlink')
1005 with open(source_file,'w') as f:
1006 f.write('something\n')
1007 os.symlink(source_file, target_file)
1008 tar = tarfile.open(temparchive,'w')
1009 tar.add(source_file)
1010 tar.add(target_file)
1011 tar.close()
1012 # Let's extract it to the location which contains the symlink
1013 tar = tarfile.open(temparchive,'r')
1014 # this should not raise OSError: [Errno 17] File exists
1015 try:
1016 tar.extractall(path=tempdir)
1017 except OSError:
1018 self.fail("extractall failed with symlinked files")
1019 finally:
1020 tar.close()
1021 finally:
1022 os.unlink(temparchive)
1023 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001024
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001025 def test_pathnames(self):
1026 self._test_pathname("foo")
1027 self._test_pathname(os.path.join("foo", ".", "bar"))
1028 self._test_pathname(os.path.join("foo", "..", "bar"))
1029 self._test_pathname(os.path.join(".", "foo"))
1030 self._test_pathname(os.path.join(".", "foo", "."))
1031 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1032 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1033 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1034 self._test_pathname(os.path.join("..", "foo"))
1035 self._test_pathname(os.path.join("..", "foo", ".."))
1036 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1037 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1038
1039 self._test_pathname("foo" + os.sep + os.sep + "bar")
1040 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1041
1042 def test_abs_pathnames(self):
1043 if sys.platform == "win32":
1044 self._test_pathname("C:\\foo", "foo")
1045 else:
1046 self._test_pathname("/foo", "foo")
1047 self._test_pathname("///foo", "foo")
1048
1049 def test_cwd(self):
1050 # Test adding the current working directory.
1051 cwd = os.getcwd()
1052 os.chdir(TEMPDIR)
1053 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001054 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001055 try:
1056 tar.add(".")
1057 finally:
1058 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001059
1060 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001061 try:
1062 for t in tar:
Ezio Melottib3aedd42010-11-20 19:04:17 +00001063 self.assertTrue(t.name == "." or t.name.startswith("./"))
Antoine Pitrou95f55602010-09-23 18:36:46 +00001064 finally:
1065 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001066 finally:
1067 os.chdir(cwd)
1068
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001069
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001070class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001071
Guido van Rossumd8faa362007-04-27 19:54:29 +00001072 mode = "w|"
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001073
Guido van Rossumd8faa362007-04-27 19:54:29 +00001074 def test_stream_padding(self):
1075 # Test for bug #1543303.
1076 tar = tarfile.open(tmpname, self.mode)
1077 tar.close()
1078
1079 if self.mode.endswith("gz"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001080 with gzip.GzipFile(tmpname) as fobj:
1081 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001082 elif self.mode.endswith("bz2"):
1083 dec = bz2.BZ2Decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001084 with open(tmpname, "rb") as fobj:
1085 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001086 data = dec.decompress(data)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001087 self.assertTrue(len(dec.unused_data) == 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001088 "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001089 else:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001090 with open(tmpname, "rb") as fobj:
1091 data = fobj.read()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001092
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001093 self.assertTrue(data.count(b"\0") == tarfile.RECORDSIZE,
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001094 "incorrect zero padding")
1095
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001096 def test_file_mode(self):
1097 # Test for issue #8464: Create files with correct
1098 # permissions.
1099 if sys.platform == "win32" or not hasattr(os, "umask"):
1100 return
1101
1102 if os.path.exists(tmpname):
1103 os.remove(tmpname)
1104
1105 original_umask = os.umask(0o022)
1106 try:
1107 tar = tarfile.open(tmpname, self.mode)
1108 tar.close()
1109 mode = os.stat(tmpname).st_mode & 0o777
1110 self.assertEqual(mode, 0o644, "wrong file permissions")
1111 finally:
1112 os.umask(original_umask)
1113
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001114
Guido van Rossumd8faa362007-04-27 19:54:29 +00001115class GNUWriteTest(unittest.TestCase):
1116 # This testcase checks for correct creation of GNU Longname
1117 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001118
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001119 def _length(self, s):
1120 blocks, remainder = divmod(len(s) + 1, 512)
1121 if remainder:
1122 blocks += 1
1123 return blocks * 512
1124
1125 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001126 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001127 count = 512
1128
1129 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001130 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001131 count += 512
1132 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001133 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001134 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001135 count += 512
1136 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001137 return count
1138
1139 def _test(self, name, link=None):
1140 tarinfo = tarfile.TarInfo(name)
1141 if link:
1142 tarinfo.linkname = link
1143 tarinfo.type = tarfile.LNKTYPE
1144
Guido van Rossumd8faa362007-04-27 19:54:29 +00001145 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001146 try:
1147 tar.format = tarfile.GNU_FORMAT
1148 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001149
Antoine Pitrou95f55602010-09-23 18:36:46 +00001150 v1 = self._calc_size(name, link)
1151 v2 = tar.offset
1152 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
1153 finally:
1154 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001155
Guido van Rossumd8faa362007-04-27 19:54:29 +00001156 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001157 try:
1158 member = tar.next()
1159 self.assertIsNotNone(member,
1160 "unable to read longname member")
1161 self.assertEqual(tarinfo.name, member.name,
1162 "unable to read longname member")
1163 self.assertEqual(tarinfo.linkname, member.linkname,
1164 "unable to read longname member")
1165 finally:
1166 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001167
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001168 def test_longname_1023(self):
1169 self._test(("longnam/" * 127) + "longnam")
1170
1171 def test_longname_1024(self):
1172 self._test(("longnam/" * 127) + "longname")
1173
1174 def test_longname_1025(self):
1175 self._test(("longnam/" * 127) + "longname_")
1176
1177 def test_longlink_1023(self):
1178 self._test("name", ("longlnk/" * 127) + "longlnk")
1179
1180 def test_longlink_1024(self):
1181 self._test("name", ("longlnk/" * 127) + "longlink")
1182
1183 def test_longlink_1025(self):
1184 self._test("name", ("longlnk/" * 127) + "longlink_")
1185
1186 def test_longnamelink_1023(self):
1187 self._test(("longnam/" * 127) + "longnam",
1188 ("longlnk/" * 127) + "longlnk")
1189
1190 def test_longnamelink_1024(self):
1191 self._test(("longnam/" * 127) + "longname",
1192 ("longlnk/" * 127) + "longlink")
1193
1194 def test_longnamelink_1025(self):
1195 self._test(("longnam/" * 127) + "longname_",
1196 ("longlnk/" * 127) + "longlink_")
1197
Guido van Rossumd8faa362007-04-27 19:54:29 +00001198
1199class HardlinkTest(unittest.TestCase):
1200 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001201
1202 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001203 self.foo = os.path.join(TEMPDIR, "foo")
1204 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001205
Antoine Pitrou95f55602010-09-23 18:36:46 +00001206 with open(self.foo, "wb") as fobj:
1207 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001208
Guido van Rossumd8faa362007-04-27 19:54:29 +00001209 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001210
Guido van Rossumd8faa362007-04-27 19:54:29 +00001211 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001212 self.tar.add(self.foo)
1213
Guido van Rossumd8faa362007-04-27 19:54:29 +00001214 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001215 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001216 support.unlink(self.foo)
1217 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001218
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001219 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001220 # The same name will be added as a REGTYPE every
1221 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001222 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001223 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001224 "add file as regular failed")
1225
1226 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001227 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001228 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001229 "add file as hardlink failed")
1230
1231 def test_dereference_hardlink(self):
1232 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001233 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001234 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001235 "dereferencing hardlink failed")
1236
Neal Norwitza4f651a2004-07-20 22:07:44 +00001237
Guido van Rossumd8faa362007-04-27 19:54:29 +00001238class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001239
Guido van Rossumd8faa362007-04-27 19:54:29 +00001240 def _test(self, name, link=None):
1241 # See GNUWriteTest.
1242 tarinfo = tarfile.TarInfo(name)
1243 if link:
1244 tarinfo.linkname = link
1245 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001246
Guido van Rossumd8faa362007-04-27 19:54:29 +00001247 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001248 try:
1249 tar.addfile(tarinfo)
1250 finally:
1251 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001252
Guido van Rossumd8faa362007-04-27 19:54:29 +00001253 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001254 try:
1255 if link:
1256 l = tar.getmembers()[0].linkname
1257 self.assertTrue(link == l, "PAX longlink creation failed")
1258 else:
1259 n = tar.getmembers()[0].name
1260 self.assertTrue(name == n, "PAX longname creation failed")
1261 finally:
1262 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001263
Guido van Rossume7ba4952007-06-06 23:52:48 +00001264 def test_pax_global_header(self):
1265 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001266 "foo": "bar",
1267 "uid": "0",
1268 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001269 "test": "\xe4\xf6\xfc",
1270 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001271
Benjamin Peterson886af962010-03-21 23:13:07 +00001272 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001273 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001274 try:
1275 tar.addfile(tarfile.TarInfo("test"))
1276 finally:
1277 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001278
1279 # Test if the global header was written correctly.
1280 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001281 try:
1282 self.assertEqual(tar.pax_headers, pax_headers)
1283 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1284 # Test if all the fields are strings.
1285 for key, val in tar.pax_headers.items():
1286 self.assertTrue(type(key) is not bytes)
1287 self.assertTrue(type(val) is not bytes)
1288 if key in tarfile.PAX_NUMBER_FIELDS:
1289 try:
1290 tarfile.PAX_NUMBER_FIELDS[key](val)
1291 except (TypeError, ValueError):
1292 self.fail("unable to convert pax header field")
1293 finally:
1294 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001295
1296 def test_pax_extended_header(self):
1297 # The fields from the pax header have priority over the
1298 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001299 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001300
1301 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001302 try:
1303 t = tarfile.TarInfo()
1304 t.name = "\xe4\xf6\xfc" # non-ASCII
1305 t.uid = 8**8 # too large
1306 t.pax_headers = pax_headers
1307 tar.addfile(t)
1308 finally:
1309 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001310
1311 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001312 try:
1313 t = tar.getmembers()[0]
1314 self.assertEqual(t.pax_headers, pax_headers)
1315 self.assertEqual(t.name, "foo")
1316 self.assertEqual(t.uid, 123)
1317 finally:
1318 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001319
1320
1321class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001322
1323 format = tarfile.USTAR_FORMAT
1324
1325 def test_iso8859_1_filename(self):
1326 self._test_unicode_filename("iso8859-1")
1327
1328 def test_utf7_filename(self):
1329 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001330
1331 def test_utf8_filename(self):
1332 self._test_unicode_filename("utf8")
1333
Guido van Rossumd8faa362007-04-27 19:54:29 +00001334 def _test_unicode_filename(self, encoding):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001335 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001336 try:
1337 name = "\xe4\xf6\xfc"
1338 tar.addfile(tarfile.TarInfo(name))
1339 finally:
1340 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001341
1342 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001343 try:
1344 self.assertEqual(tar.getmembers()[0].name, name)
1345 finally:
1346 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001347
1348 def test_unicode_filename_error(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001349 if self.format == tarfile.PAX_FORMAT:
1350 # PAX_FORMAT ignores encoding in write mode.
1351 return
1352
Guido van Rossume7ba4952007-06-06 23:52:48 +00001353 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001354 try:
1355 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001356
Antoine Pitrou95f55602010-09-23 18:36:46 +00001357 tarinfo.name = "\xe4\xf6\xfc"
1358 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001359
Antoine Pitrou95f55602010-09-23 18:36:46 +00001360 tarinfo.name = "foo"
1361 tarinfo.uname = "\xe4\xf6\xfc"
1362 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1363 finally:
1364 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001365
1366 def test_unicode_argument(self):
1367 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001368 try:
1369 for t in tar:
1370 self.assertTrue(type(t.name) is str)
1371 self.assertTrue(type(t.linkname) is str)
1372 self.assertTrue(type(t.uname) is str)
1373 self.assertTrue(type(t.gname) is str)
1374 finally:
1375 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001376
Guido van Rossume7ba4952007-06-06 23:52:48 +00001377 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001378 t = tarfile.TarInfo("foo")
1379 t.uname = "\xe4\xf6\xfc"
1380 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001381
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001382 tar = tarfile.open(tmpname, mode="w", format=self.format, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001383 try:
1384 tar.addfile(t)
1385 finally:
1386 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001387
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001388 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001389 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001390 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001391 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1392 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1393
1394 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001395 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001396 tar = tarfile.open(tmpname, encoding="ascii")
1397 t = tar.getmember("foo")
1398 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1399 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1400 finally:
1401 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001402
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001403
Guido van Rossume7ba4952007-06-06 23:52:48 +00001404class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001405
Guido van Rossume7ba4952007-06-06 23:52:48 +00001406 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001407
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001408 def test_bad_pax_header(self):
1409 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1410 # without a hdrcharset=BINARY header.
1411 for encoding, name in (("utf8", "pax/bad-pax-\udce4\udcf6\udcfc"),
1412 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
1413 with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar:
1414 try:
1415 t = tar.getmember(name)
1416 except KeyError:
1417 self.fail("unable to read bad GNU tar pax header")
1418
Guido van Rossumd8faa362007-04-27 19:54:29 +00001419
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001420class PAXUnicodeTest(UstarUnicodeTest):
1421
1422 format = tarfile.PAX_FORMAT
1423
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001424 def test_binary_header(self):
1425 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
1426 for encoding, name in (("utf8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
1427 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
1428 with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar:
1429 try:
1430 t = tar.getmember(name)
1431 except KeyError:
1432 self.fail("unable to read POSIX.1-2008 binary header")
1433
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001434
Guido van Rossumd8faa362007-04-27 19:54:29 +00001435class AppendTest(unittest.TestCase):
1436 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001437
Guido van Rossumd8faa362007-04-27 19:54:29 +00001438 def setUp(self):
1439 self.tarname = tmpname
1440 if os.path.exists(self.tarname):
1441 os.remove(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001442
Guido van Rossumd8faa362007-04-27 19:54:29 +00001443 def _add_testfile(self, fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001444 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1445 tar.addfile(tarfile.TarInfo("bar"))
Tim Peters8ceefc52004-10-25 03:19:41 +00001446
Guido van Rossumd8faa362007-04-27 19:54:29 +00001447 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001448 with tarfile.open(tarname, encoding="iso8859-1") as src:
1449 t = src.getmember("ustar/regtype")
1450 t.name = "foo"
1451 f = src.extractfile(t)
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001452 try:
1453 with tarfile.open(self.tarname, mode) as tar:
1454 tar.addfile(t, f)
1455 finally:
1456 f.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001457
Guido van Rossumd8faa362007-04-27 19:54:29 +00001458 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001459 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1460 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001461
1462 def test_non_existing(self):
1463 self._add_testfile()
1464 self._test()
1465
1466 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001467 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001468 self._add_testfile()
1469 self._test()
1470
1471 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001472 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001473 self._add_testfile(fobj)
1474 fobj.seek(0)
1475 self._test(fileobj=fobj)
1476
1477 def test_fileobj(self):
1478 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001479 with open(self.tarname, "rb") as fobj:
1480 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001481 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001482 self._add_testfile(fobj)
1483 fobj.seek(0)
1484 self._test(names=["foo", "bar"], fileobj=fobj)
1485
1486 def test_existing(self):
1487 self._create_testtar()
1488 self._add_testfile()
1489 self._test(names=["foo", "bar"])
1490
1491 def test_append_gz(self):
1492 if gzip is None:
1493 return
1494 self._create_testtar("w:gz")
1495 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1496
1497 def test_append_bz2(self):
1498 if bz2 is None:
1499 return
1500 self._create_testtar("w:bz2")
1501 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1502
Lars Gustäbel9520a432009-11-22 18:48:49 +00001503 # Append mode is supposed to fail if the tarfile to append to
1504 # does not end with a zero block.
1505 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001506 with open(self.tarname, "wb") as fobj:
1507 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001508 self.assertRaises(tarfile.ReadError, self._add_testfile)
1509
1510 def test_null(self):
1511 self._test_error(b"")
1512
1513 def test_incomplete(self):
1514 self._test_error(b"\0" * 13)
1515
1516 def test_premature_eof(self):
1517 data = tarfile.TarInfo("foo").tobuf()
1518 self._test_error(data)
1519
1520 def test_trailing_garbage(self):
1521 data = tarfile.TarInfo("foo").tobuf()
1522 self._test_error(data + b"\0" * 13)
1523
1524 def test_invalid(self):
1525 self._test_error(b"a" * 512)
1526
Guido van Rossumd8faa362007-04-27 19:54:29 +00001527
1528class LimitsTest(unittest.TestCase):
1529
1530 def test_ustar_limits(self):
1531 # 100 char name
1532 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001533 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001534
1535 # 101 char name that cannot be stored
1536 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001537 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001538
1539 # 256 char name with a slash at pos 156
1540 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001541 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001542
1543 # 256 char name that cannot be stored
1544 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001545 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001546
1547 # 512 char name
1548 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001549 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001550
1551 # 512 char linkname
1552 tarinfo = tarfile.TarInfo("longlink")
1553 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001554 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001555
1556 # uid > 8 digits
1557 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001558 tarinfo.uid = 0o10000000
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 def test_gnu_limits(self):
1562 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001563 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001564
1565 tarinfo = tarfile.TarInfo("longlink")
1566 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001567 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001568
1569 # uid >= 256 ** 7
1570 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001571 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001572 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001573
1574 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001575 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001576 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001577
1578 tarinfo = tarfile.TarInfo("longlink")
1579 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001580 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001581
1582 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001583 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001584 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001585
1586
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001587class MiscTest(unittest.TestCase):
1588
1589 def test_char_fields(self):
1590 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"), b"foo\0\0\0\0\0")
1591 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"), b"foo")
1592 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"), "foo")
1593 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"), "foo")
1594
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001595 def test_read_number_fields(self):
1596 # Issue 13158: Test if GNU tar specific base-256 number fields
1597 # are decoded correctly.
1598 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1599 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
1600 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"), 0o10000000)
1601 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"), 0xffffffff)
1602 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"), -1)
1603 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"), -100)
1604 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"), -0x100000000000000)
1605
1606 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001607 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001608 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
1609 self.assertEqual(tarfile.itn(0o10000000), b"\x80\x00\x00\x00\x00\x20\x00\x00")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001610 self.assertEqual(tarfile.itn(0xffffffff), b"\x80\x00\x00\x00\xff\xff\xff\xff")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001611 self.assertEqual(tarfile.itn(-1), b"\xff\xff\xff\xff\xff\xff\xff\xff")
1612 self.assertEqual(tarfile.itn(-100), b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1613 self.assertEqual(tarfile.itn(-0x100000000000000), b"\xff\x00\x00\x00\x00\x00\x00\x00")
1614
1615 def test_number_field_limits(self):
1616 self.assertRaises(ValueError, tarfile.itn, -1, 8, tarfile.USTAR_FORMAT)
1617 self.assertRaises(ValueError, tarfile.itn, 0o10000000, 8, tarfile.USTAR_FORMAT)
1618 self.assertRaises(ValueError, tarfile.itn, -0x10000000001, 6, tarfile.GNU_FORMAT)
1619 self.assertRaises(ValueError, tarfile.itn, 0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001620
1621
Lars Gustäbel01385812010-03-03 12:08:54 +00001622class ContextManagerTest(unittest.TestCase):
1623
1624 def test_basic(self):
1625 with tarfile.open(tarname) as tar:
1626 self.assertFalse(tar.closed, "closed inside runtime context")
1627 self.assertTrue(tar.closed, "context manager failed")
1628
1629 def test_closed(self):
1630 # The __enter__() method is supposed to raise IOError
1631 # if the TarFile object is already closed.
1632 tar = tarfile.open(tarname)
1633 tar.close()
1634 with self.assertRaises(IOError):
1635 with tar:
1636 pass
1637
1638 def test_exception(self):
1639 # Test if the IOError exception is passed through properly.
1640 with self.assertRaises(Exception) as exc:
1641 with tarfile.open(tarname) as tar:
1642 raise IOError
1643 self.assertIsInstance(exc.exception, IOError,
1644 "wrong exception raised in context manager")
1645 self.assertTrue(tar.closed, "context manager failed")
1646
1647 def test_no_eof(self):
1648 # __exit__() must not write end-of-archive blocks if an
1649 # exception was raised.
1650 try:
1651 with tarfile.open(tmpname, "w") as tar:
1652 raise Exception
1653 except:
1654 pass
1655 self.assertEqual(os.path.getsize(tmpname), 0,
1656 "context manager wrote an end-of-archive block")
1657 self.assertTrue(tar.closed, "context manager failed")
1658
1659 def test_eof(self):
1660 # __exit__() must write end-of-archive blocks, i.e. call
1661 # TarFile.close() if there was no error.
1662 with tarfile.open(tmpname, "w"):
1663 pass
1664 self.assertNotEqual(os.path.getsize(tmpname), 0,
1665 "context manager wrote no end-of-archive block")
1666
1667 def test_fileobj(self):
1668 # Test that __exit__() did not close the external file
1669 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001670 with open(tmpname, "wb") as fobj:
1671 try:
1672 with tarfile.open(fileobj=fobj, mode="w") as tar:
1673 raise Exception
1674 except:
1675 pass
1676 self.assertFalse(fobj.closed, "external file object was closed")
1677 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00001678
1679
Lars Gustäbel1b512722010-06-03 12:45:16 +00001680class LinkEmulationTest(ReadTest):
1681
1682 # Test for issue #8741 regression. On platforms that do not support
1683 # symbolic or hard links tarfile tries to extract these types of members as
1684 # the regular files they point to.
1685 def _test_link_extraction(self, name):
1686 self.tar.extract(name, TEMPDIR)
1687 data = open(os.path.join(TEMPDIR, name), "rb").read()
1688 self.assertEqual(md5sum(data), md5_regtype)
1689
Brian Curtind40e6f72010-07-08 21:39:08 +00001690 # When 8879 gets fixed, this will need to change. Currently on Windows
1691 # we have os.path.islink but no os.link, so these tests fail without the
1692 # following skip until link is completed.
1693 @unittest.skipIf(hasattr(os.path, "islink"),
1694 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001695 def test_hardlink_extraction1(self):
1696 self._test_link_extraction("ustar/lnktype")
1697
Brian Curtind40e6f72010-07-08 21:39:08 +00001698 @unittest.skipIf(hasattr(os.path, "islink"),
1699 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001700 def test_hardlink_extraction2(self):
1701 self._test_link_extraction("./ustar/linktest2/lnktype")
1702
Brian Curtin74e45612010-07-09 15:58:59 +00001703 @unittest.skipIf(hasattr(os, "symlink"),
1704 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001705 def test_symlink_extraction1(self):
1706 self._test_link_extraction("ustar/symtype")
1707
Brian Curtin74e45612010-07-09 15:58:59 +00001708 @unittest.skipIf(hasattr(os, "symlink"),
1709 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001710 def test_symlink_extraction2(self):
1711 self._test_link_extraction("./ustar/linktest2/symtype")
1712
1713
Guido van Rossumd8faa362007-04-27 19:54:29 +00001714class GzipMiscReadTest(MiscReadTest):
1715 tarname = gzipname
1716 mode = "r:gz"
Georg Brandl3abb3722011-08-13 11:48:12 +02001717
1718 def test_non_existent_targz_file(self):
1719 # Test for issue11513: prevent non-existent gzipped tarfiles raising
1720 # multiple exceptions.
1721 with self.assertRaisesRegex(IOError, "xxx") as ex:
1722 tarfile.open("xxx", self.mode)
1723 self.assertEqual(ex.exception.errno, errno.ENOENT)
1724
Guido van Rossumd8faa362007-04-27 19:54:29 +00001725class GzipUstarReadTest(UstarReadTest):
1726 tarname = gzipname
1727 mode = "r:gz"
1728class GzipStreamReadTest(StreamReadTest):
1729 tarname = gzipname
1730 mode = "r|gz"
1731class GzipWriteTest(WriteTest):
1732 mode = "w:gz"
1733class GzipStreamWriteTest(StreamWriteTest):
1734 mode = "w|gz"
1735
1736
1737class Bz2MiscReadTest(MiscReadTest):
1738 tarname = bz2name
1739 mode = "r:bz2"
1740class Bz2UstarReadTest(UstarReadTest):
1741 tarname = bz2name
1742 mode = "r:bz2"
1743class Bz2StreamReadTest(StreamReadTest):
1744 tarname = bz2name
1745 mode = "r|bz2"
1746class Bz2WriteTest(WriteTest):
1747 mode = "w:bz2"
1748class Bz2StreamWriteTest(StreamWriteTest):
1749 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001750
Lars Gustäbel42e00912009-03-22 20:34:29 +00001751class Bz2PartialReadTest(unittest.TestCase):
1752 # Issue5068: The _BZ2Proxy.read() method loops forever
1753 # on an empty or partial bzipped file.
1754
1755 def _test_partial_input(self, mode):
1756 class MyBytesIO(io.BytesIO):
1757 hit_eof = False
1758 def read(self, n):
1759 if self.hit_eof:
1760 raise AssertionError("infinite loop detected in tarfile.open()")
1761 self.hit_eof = self.tell() == len(self.getvalue())
1762 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001763 def seek(self, *args):
1764 self.hit_eof = False
1765 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00001766
1767 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1768 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001769 try:
1770 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
1771 except tarfile.ReadError:
1772 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00001773
1774 def test_partial_input(self):
1775 self._test_partial_input("r")
1776
1777 def test_partial_input_bz2(self):
1778 self._test_partial_input("r:bz2")
1779
1780
Neal Norwitz996acf12003-02-17 14:51:41 +00001781def test_main():
Antoine Pitrou95f55602010-09-23 18:36:46 +00001782 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00001783 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001784
Walter Dörwald21d3a322003-05-01 17:45:56 +00001785 tests = [
Guido van Rossumd8faa362007-04-27 19:54:29 +00001786 UstarReadTest,
1787 MiscReadTest,
1788 StreamReadTest,
1789 DetectReadTest,
1790 MemberReadTest,
1791 GNUReadTest,
1792 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001793 WriteTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001794 StreamWriteTest,
1795 GNUWriteTest,
1796 PaxWriteTest,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001797 UstarUnicodeTest,
1798 GNUUnicodeTest,
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001799 PAXUnicodeTest,
Thomas Wouterscf297e42007-02-23 15:07:44 +00001800 AppendTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001801 LimitsTest,
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001802 MiscTest,
Lars Gustäbel01385812010-03-03 12:08:54 +00001803 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001804 ]
1805
Neal Norwitza4f651a2004-07-20 22:07:44 +00001806 if hasattr(os, "link"):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001807 tests.append(HardlinkTest)
Lars Gustäbel1b512722010-06-03 12:45:16 +00001808 else:
1809 tests.append(LinkEmulationTest)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001810
Antoine Pitrou95f55602010-09-23 18:36:46 +00001811 with open(tarname, "rb") as fobj:
1812 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001813
Walter Dörwald21d3a322003-05-01 17:45:56 +00001814 if gzip:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001815 # Create testtar.tar.gz and add gzip-specific tests.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001816 support.unlink(gzipname)
1817 with gzip.open(gzipname, "wb") as tar:
1818 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001819
1820 tests += [
1821 GzipMiscReadTest,
1822 GzipUstarReadTest,
1823 GzipStreamReadTest,
1824 GzipWriteTest,
1825 GzipStreamWriteTest,
1826 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001827
1828 if bz2:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001829 # Create testtar.tar.bz2 and add bz2-specific tests.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001830 support.unlink(bz2name)
Lars Gustäbeled1ac582011-12-06 12:56:38 +01001831 with bz2.BZ2File(bz2name, "wb") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001832 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001833
1834 tests += [
1835 Bz2MiscReadTest,
1836 Bz2UstarReadTest,
1837 Bz2StreamReadTest,
1838 Bz2WriteTest,
1839 Bz2StreamWriteTest,
Lars Gustäbel42e00912009-03-22 20:34:29 +00001840 Bz2PartialReadTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001841 ]
1842
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001843 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001844 support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001845 finally:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001846 if os.path.exists(TEMPDIR):
1847 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001848
Neal Norwitz996acf12003-02-17 14:51:41 +00001849if __name__ == "__main__":
1850 test_main()