blob: 0c4328f1723cb524749f6fe07241b042b9bc2c54 [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
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010024try:
25 import lzma
26except ImportError:
27 lzma = None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000028
Guido van Rossumd8faa362007-04-27 19:54:29 +000029def md5sum(data):
Guido van Rossuma8add0e2007-05-14 22:03:55 +000030 return md5(data).hexdigest()
Guido van Rossumd8faa362007-04-27 19:54:29 +000031
Antoine Pitrouab58b5f2010-09-23 19:39:35 +000032TEMPDIR = os.path.abspath(support.TESTFN) + "-tardir"
Antoine Pitrou941ee882009-11-11 20:59:38 +000033tarname = support.findfile("testtar.tar")
Guido van Rossumd8faa362007-04-27 19:54:29 +000034gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
35bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010036xzname = os.path.join(TEMPDIR, "testtar.tar.xz")
Guido van Rossumd8faa362007-04-27 19:54:29 +000037tmpname = os.path.join(TEMPDIR, "tmp.tar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000038
Guido van Rossumd8faa362007-04-27 19:54:29 +000039md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
40md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000041
42
Guido van Rossumd8faa362007-04-27 19:54:29 +000043class ReadTest(unittest.TestCase):
44
45 tarname = tarname
46 mode = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000047
48 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +000049 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000050
51 def tearDown(self):
52 self.tar.close()
53
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000054
Guido van Rossumd8faa362007-04-27 19:54:29 +000055class UstarReadTest(ReadTest):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000056
Guido van Rossumd8faa362007-04-27 19:54:29 +000057 def test_fileobj_regular_file(self):
58 tarinfo = self.tar.getmember("ustar/regtype")
Lars Gustäbel7a919e92012-05-05 18:15:03 +020059 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000060 data = fobj.read()
61 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
62 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000063
Guido van Rossumd8faa362007-04-27 19:54:29 +000064 def test_fileobj_readlines(self):
65 self.tar.extract("ustar/regtype", TEMPDIR)
66 tarinfo = self.tar.getmember("ustar/regtype")
Antoine Pitrou95f55602010-09-23 18:36:46 +000067 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
68 lines1 = fobj1.readlines()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000069
Lars Gustäbel7a919e92012-05-05 18:15:03 +020070 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000071 fobj2 = io.TextIOWrapper(fobj)
72 lines2 = fobj2.readlines()
73 self.assertTrue(lines1 == lines2,
74 "fileobj.readlines() failed")
75 self.assertTrue(len(lines2) == 114,
76 "fileobj.readlines() failed")
77 self.assertTrue(lines2[83] ==
78 "I will gladly admit that Python is not the fastest running scripting language.\n",
79 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000080
Guido van Rossumd8faa362007-04-27 19:54:29 +000081 def test_fileobj_iter(self):
82 self.tar.extract("ustar/regtype", TEMPDIR)
83 tarinfo = self.tar.getmember("ustar/regtype")
Victor Stinner4e86d5b2011-05-04 13:55:36 +020084 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
Antoine Pitrou95f55602010-09-23 18:36:46 +000085 lines1 = fobj1.readlines()
Lars Gustäbel7a919e92012-05-05 18:15:03 +020086 with self.tar.extractfile(tarinfo) as fobj2:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000087 lines2 = list(io.TextIOWrapper(fobj2))
88 self.assertTrue(lines1 == lines2,
89 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +000090
Guido van Rossumd8faa362007-04-27 19:54:29 +000091 def test_fileobj_seek(self):
92 self.tar.extract("ustar/regtype", TEMPDIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +000093 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
94 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +000095
Guido van Rossumd8faa362007-04-27 19:54:29 +000096 tarinfo = self.tar.getmember("ustar/regtype")
97 fobj = self.tar.extractfile(tarinfo)
98
99 text = fobj.read()
100 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000101 self.assertEqual(0, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102 "seek() to file's start failed")
103 fobj.seek(2048, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000104 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000105 "seek() to absolute position failed")
106 fobj.seek(-1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000107 self.assertEqual(1024, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000108 "seek() to negative relative position failed")
109 fobj.seek(1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000110 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111 "seek() to positive relative position failed")
112 s = fobj.read(10)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000113 self.assertTrue(s == data[2048:2058],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000114 "read() after seek failed")
115 fobj.seek(0, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000116 self.assertEqual(tarinfo.size, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000117 "seek() to file's end failed")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000118 self.assertTrue(fobj.read() == b"",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000119 "read() at file's end did not return empty string")
120 fobj.seek(-tarinfo.size, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000121 self.assertEqual(0, fobj.tell(),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000122 "relative seek() to file's end failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123 fobj.seek(512)
124 s1 = fobj.readlines()
125 fobj.seek(512)
126 s2 = fobj.readlines()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000127 self.assertTrue(s1 == s2,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000128 "readlines() after seek failed")
129 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000130 self.assertEqual(len(fobj.readline()), fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000131 "tell() after readline() failed")
132 fobj.seek(512)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000133 self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134 "tell() after seek() and readline() failed")
135 fobj.seek(0)
136 line = fobj.readline()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000137 self.assertEqual(fobj.read(), data[len(line):],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000138 "read() after readline() failed")
139 fobj.close()
140
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200141 def test_fileobj_text(self):
142 with self.tar.extractfile("ustar/regtype") as fobj:
143 fobj = io.TextIOWrapper(fobj)
144 data = fobj.read().encode("iso8859-1")
145 self.assertEqual(md5sum(data), md5_regtype)
146 try:
147 fobj.seek(100)
148 except AttributeError:
149 # Issue #13815: seek() complained about a missing
150 # flush() method.
151 self.fail("seeking failed in text mode")
152
Lars Gustäbel1b512722010-06-03 12:45:16 +0000153 # Test if symbolic and hard links are resolved by extractfile(). The
154 # test link members each point to a regular member whose data is
155 # supposed to be exported.
156 def _test_fileobj_link(self, lnktype, regtype):
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200157 with self.tar.extractfile(lnktype) as a, self.tar.extractfile(regtype) as b:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000158 self.assertEqual(a.name, b.name)
Lars Gustäbel1b512722010-06-03 12:45:16 +0000159
160 def test_fileobj_link1(self):
161 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
162
163 def test_fileobj_link2(self):
164 self._test_fileobj_link("./ustar/linktest2/lnktype", "ustar/linktest1/regtype")
165
166 def test_fileobj_symlink1(self):
167 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
168
169 def test_fileobj_symlink2(self):
170 self._test_fileobj_link("./ustar/linktest2/symtype", "ustar/linktest1/regtype")
171
Lars Gustäbel1ef9eda2012-04-24 21:04:40 +0200172 def test_issue14160(self):
173 self._test_fileobj_link("symtype2", "ustar/regtype")
174
Guido van Rossumd8faa362007-04-27 19:54:29 +0000175
Lars Gustäbel9520a432009-11-22 18:48:49 +0000176class CommonReadTest(ReadTest):
177
178 def test_empty_tarfile(self):
179 # Test for issue6123: Allow opening empty archives.
180 # This test checks if tarfile.open() is able to open an empty tar
181 # archive successfully. Note that an empty tar archive is not the
182 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000183 with tarfile.open(tmpname, self.mode.replace("r", "w")):
184 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000185 try:
186 tar = tarfile.open(tmpname, self.mode)
187 tar.getnames()
188 except tarfile.ReadError:
189 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000190 else:
191 self.assertListEqual(tar.getmembers(), [])
192 finally:
193 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000194
195 def test_null_tarfile(self):
196 # Test for issue6123: Allow opening empty archives.
197 # This test guarantees that tarfile.open() does not treat an empty
198 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000199 with open(tmpname, "wb"):
200 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000201 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
202 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
203
204 def test_ignore_zeros(self):
205 # Test TarFile's ignore_zeros option.
206 if self.mode.endswith(":gz"):
207 _open = gzip.GzipFile
208 elif self.mode.endswith(":bz2"):
209 _open = bz2.BZ2File
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100210 elif self.mode.endswith(":xz"):
211 _open = lzma.LZMAFile
Lars Gustäbel9520a432009-11-22 18:48:49 +0000212 else:
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100213 _open = io.FileIO
Lars Gustäbel9520a432009-11-22 18:48:49 +0000214
215 for char in (b'\0', b'a'):
216 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
217 # are ignored correctly.
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100218 with _open(tmpname, "w") as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000219 fobj.write(char * 1024)
220 fobj.write(tarfile.TarInfo("foo").tobuf())
Lars Gustäbel9520a432009-11-22 18:48:49 +0000221
222 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000223 try:
224 self.assertListEqual(tar.getnames(), ["foo"],
Lars Gustäbel9520a432009-11-22 18:48:49 +0000225 "ignore_zeros=True should have skipped the %r-blocks" % char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000226 finally:
227 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000228
229
230class MiscReadTest(CommonReadTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
Thomas Woutersed03b412007-08-28 21:37:11 +0000232 def test_no_name_argument(self):
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100233 if self.mode.endswith(("bz2", "xz")):
234 # BZ2File and LZMAFile have no name attribute.
235 self.skipTest("no name attribute")
236
Antoine Pitrou95f55602010-09-23 18:36:46 +0000237 with open(self.tarname, "rb") as fobj:
238 tar = tarfile.open(fileobj=fobj, mode=self.mode)
239 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000240
Thomas Woutersed03b412007-08-28 21:37:11 +0000241 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000242 with open(self.tarname, "rb") as fobj:
243 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000244 fobj = io.BytesIO(data)
245 self.assertRaises(AttributeError, getattr, fobj, "name")
246 tar = tarfile.open(fileobj=fobj, mode=self.mode)
247 self.assertEqual(tar.name, None)
248
249 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000250 with open(self.tarname, "rb") as fobj:
251 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000252 fobj = io.BytesIO(data)
253 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000254 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
255 self.assertEqual(tar.name, None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000256
Christian Heimesd8654cf2007-12-02 15:22:16 +0000257 def test_fileobj_with_offset(self):
258 # Skip the first member and store values from the second member
259 # of the testtar.
260 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000261 try:
262 tar.next()
263 t = tar.next()
264 name = t.name
265 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200266 with tar.extractfile(t) as f:
267 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000268 finally:
269 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000270
271 # Open the testtar and seek to the offset of the second member.
272 if self.mode.endswith(":gz"):
273 _open = gzip.GzipFile
274 elif self.mode.endswith(":bz2"):
275 _open = bz2.BZ2File
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100276 elif self.mode.endswith(":xz"):
277 _open = lzma.LZMAFile
Christian Heimesd8654cf2007-12-02 15:22:16 +0000278 else:
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100279 _open = io.FileIO
280
281 with _open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000282 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000283
Antoine Pitrou95f55602010-09-23 18:36:46 +0000284 # Test if the tarfile starts with the second member.
285 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
286 t = tar.next()
287 self.assertEqual(t.name, name)
288 # Read to the end of fileobj and test if seeking back to the
289 # beginning works.
290 tar.getmembers()
291 self.assertEqual(tar.extractfile(t).read(), data,
292 "seek back did not work")
293 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000294
Guido van Rossumd8faa362007-04-27 19:54:29 +0000295 def test_fail_comp(self):
296 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
297 if self.mode == "r:":
298 return
299 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000300 with open(tarname, "rb") as fobj:
301 self.assertRaises(tarfile.ReadError, tarfile.open,
302 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000303
304 def test_v7_dirtype(self):
305 # Test old style dirtype member (bug #1336623):
306 # Old V7 tars create directory members using an AREGTYPE
307 # header with a "/" appended to the filename field.
308 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000309 self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000310 "v7 dirtype failed")
311
Christian Heimes126d29a2008-02-11 22:57:17 +0000312 def test_xstar_type(self):
313 # The xstar format stores extra atime and ctime fields inside the
314 # space reserved for the prefix field. The prefix field must be
315 # ignored in this case, otherwise it will mess up the name.
316 try:
317 self.tar.getmember("misc/regtype-xstar")
318 except KeyError:
319 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
320
Guido van Rossumd8faa362007-04-27 19:54:29 +0000321 def test_check_members(self):
322 for tarinfo in self.tar:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000323 self.assertTrue(int(tarinfo.mtime) == 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000324 "wrong mtime for %s" % tarinfo.name)
325 if not tarinfo.name.startswith("ustar/"):
326 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000327 self.assertTrue(tarinfo.uname == "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000328 "wrong uname for %s" % tarinfo.name)
329
330 def test_find_members(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000331 self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000332 "could not find all members")
333
Brian Curtin74e45612010-07-09 15:58:59 +0000334 @unittest.skipUnless(hasattr(os, "link"),
335 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000336 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337 def test_extract_hardlink(self):
338 # Test hardlink extraction (e.g. bug #857297).
339 tar = tarfile.open(tarname, errorlevel=1, encoding="iso8859-1")
340
Neal Norwitzf3396542005-10-28 05:52:22 +0000341 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000342 tar.extract("ustar/regtype", TEMPDIR)
343 try:
344 tar.extract("ustar/lnktype", TEMPDIR)
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200345 except OSError as e:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000346 if e.errno == errno.ENOENT:
347 self.fail("hardlink not extracted properly")
Neal Norwitzf3396542005-10-28 05:52:22 +0000348
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000349 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
350 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000351 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000352
Antoine Pitrou95f55602010-09-23 18:36:46 +0000353 try:
354 tar.extract("ustar/symtype", TEMPDIR)
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200355 except OSError as e:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000356 if e.errno == errno.ENOENT:
357 self.fail("symlink not extracted properly")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000358
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000359 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
360 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000361 self.assertEqual(md5sum(data), md5_regtype)
362 finally:
363 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000364
Christian Heimesfaf2f632008-01-06 16:59:19 +0000365 def test_extractall(self):
366 # Test if extractall() correctly restores directory permissions
367 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000368 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000369 DIR = os.path.join(TEMPDIR, "extractall")
370 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000371 try:
372 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000373 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000374 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000375 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000376 if sys.platform != "win32":
377 # Win32 has no support for fine grained permissions.
378 self.assertEqual(tarinfo.mode & 0o777, os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000379 def format_mtime(mtime):
380 if isinstance(mtime, float):
381 return "{} ({})".format(mtime, mtime.hex())
382 else:
383 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000384 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000385 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
386 format_mtime(tarinfo.mtime),
387 format_mtime(file_mtime),
388 path)
389 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000390 finally:
391 tar.close()
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000392 shutil.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000393
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000394 def test_extract_directory(self):
395 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000396 DIR = os.path.join(TEMPDIR, "extractdir")
397 os.mkdir(DIR)
398 try:
399 with tarfile.open(tarname, encoding="iso8859-1") as tar:
400 tarinfo = tar.getmember(dirtype)
401 tar.extract(tarinfo, path=DIR)
402 extracted = os.path.join(DIR, dirtype)
403 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
404 if sys.platform != "win32":
405 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
406 finally:
407 shutil.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000408
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000409 def test_init_close_fobj(self):
410 # Issue #7341: Close the internal file object in the TarFile
411 # constructor in case of an error. For the test we rely on
412 # the fact that opening an empty file raises a ReadError.
413 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000414 with open(empty, "wb") as fobj:
415 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000416
417 try:
418 tar = object.__new__(tarfile.TarFile)
419 try:
420 tar.__init__(empty)
421 except tarfile.ReadError:
422 self.assertTrue(tar.fileobj.closed)
423 else:
424 self.fail("ReadError not raised")
425 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000426 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000427
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428
Lars Gustäbel9520a432009-11-22 18:48:49 +0000429class StreamReadTest(CommonReadTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000430
431 mode="r|"
432
Lars Gustäbeldd071042011-02-23 11:42:22 +0000433 def test_read_through(self):
434 # Issue #11224: A poorly designed _FileInFile.read() method
435 # caused seeking errors with stream tar files.
436 for tarinfo in self.tar:
437 if not tarinfo.isreg():
438 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200439 with self.tar.extractfile(tarinfo) as fobj:
440 while True:
441 try:
442 buf = fobj.read(512)
443 except tarfile.StreamError:
444 self.fail("simple read-through using TarFile.extractfile() failed")
445 if not buf:
446 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000447
Guido van Rossumd8faa362007-04-27 19:54:29 +0000448 def test_fileobj_regular_file(self):
449 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200450 with self.tar.extractfile(tarinfo) as fobj:
451 data = fobj.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000452 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000453 "regular file extraction failed")
454
455 def test_provoke_stream_error(self):
456 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200457 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
458 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000459
Guido van Rossumd8faa362007-04-27 19:54:29 +0000460 def test_compare_members(self):
461 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000462 try:
463 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000464
Antoine Pitrou95f55602010-09-23 18:36:46 +0000465 while True:
466 t1 = tar1.next()
467 t2 = tar2.next()
468 if t1 is None:
469 break
470 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000471
Antoine Pitrou95f55602010-09-23 18:36:46 +0000472 if t2.islnk() or t2.issym():
473 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
474 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000475
Antoine Pitrou95f55602010-09-23 18:36:46 +0000476 v1 = tar1.extractfile(t1)
477 v2 = tar2.extractfile(t2)
478 if v1 is None:
479 continue
480 self.assertTrue(v2 is not None, "stream.extractfile() failed")
481 self.assertEqual(v1.read(), v2.read(), "stream extraction failed")
482 finally:
483 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000484
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485
Guido van Rossumd8faa362007-04-27 19:54:29 +0000486class DetectReadTest(unittest.TestCase):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000487
Guido van Rossumd8faa362007-04-27 19:54:29 +0000488 def _testfunc_file(self, name, mode):
489 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000490 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000491 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000492 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000493 else:
494 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000495
Guido van Rossumd8faa362007-04-27 19:54:29 +0000496 def _testfunc_fileobj(self, name, mode):
497 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000498 with open(name, "rb") as f:
499 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000500 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000502 else:
503 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000504
505 def _test_modes(self, testfunc):
506 testfunc(tarname, "r")
507 testfunc(tarname, "r:")
508 testfunc(tarname, "r:*")
509 testfunc(tarname, "r|")
510 testfunc(tarname, "r|*")
511
512 if gzip:
513 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
514 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
515 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
516 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
517
518 testfunc(gzipname, "r")
519 testfunc(gzipname, "r:*")
520 testfunc(gzipname, "r:gz")
521 testfunc(gzipname, "r|*")
522 testfunc(gzipname, "r|gz")
523
524 if bz2:
525 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
526 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
527 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
528 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
529
530 testfunc(bz2name, "r")
531 testfunc(bz2name, "r:*")
532 testfunc(bz2name, "r:bz2")
533 testfunc(bz2name, "r|*")
534 testfunc(bz2name, "r|bz2")
535
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100536 if lzma:
537 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:xz")
538 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|xz")
539 self.assertRaises(tarfile.ReadError, tarfile.open, xzname, mode="r:")
540 self.assertRaises(tarfile.ReadError, tarfile.open, xzname, mode="r|")
541
542 testfunc(xzname, "r")
543 testfunc(xzname, "r:*")
544 testfunc(xzname, "r:xz")
545 testfunc(xzname, "r|*")
546 testfunc(xzname, "r|xz")
547
Guido van Rossumd8faa362007-04-27 19:54:29 +0000548 def test_detect_file(self):
549 self._test_modes(self._testfunc_file)
550
551 def test_detect_fileobj(self):
552 self._test_modes(self._testfunc_fileobj)
553
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100554 def test_detect_stream_bz2(self):
555 # Originally, tarfile's stream detection looked for the string
556 # "BZh91" at the start of the file. This is incorrect because
557 # the '9' represents the blocksize (900kB). If the file was
558 # compressed using another blocksize autodetection fails.
559 if not bz2:
560 return
561
562 with open(tarname, "rb") as fobj:
563 data = fobj.read()
564
565 # Compress with blocksize 100kB, the file starts with "BZh11".
566 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
567 fobj.write(data)
568
569 self._testfunc_file(tmpname, "r|*")
570
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571
572class MemberReadTest(ReadTest):
573
574 def _test_member(self, tarinfo, chksum=None, **kwargs):
575 if chksum is not None:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000576 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000577 "wrong md5sum for %s" % tarinfo.name)
578
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000579 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000580 kwargs["uid"] = 1000
581 kwargs["gid"] = 100
582 if "old-v7" not in tarinfo.name:
583 # V7 tar can't handle alphabetic owners.
584 kwargs["uname"] = "tarfile"
585 kwargs["gname"] = "tarfile"
586 for k, v in kwargs.items():
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000587 self.assertTrue(getattr(tarinfo, k) == v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000588 "wrong value in %s field of %s" % (k, tarinfo.name))
589
590 def test_find_regtype(self):
591 tarinfo = self.tar.getmember("ustar/regtype")
592 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
593
594 def test_find_conttype(self):
595 tarinfo = self.tar.getmember("ustar/conttype")
596 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
597
598 def test_find_dirtype(self):
599 tarinfo = self.tar.getmember("ustar/dirtype")
600 self._test_member(tarinfo, size=0)
601
602 def test_find_dirtype_with_size(self):
603 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
604 self._test_member(tarinfo, size=255)
605
606 def test_find_lnktype(self):
607 tarinfo = self.tar.getmember("ustar/lnktype")
608 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
609
610 def test_find_symtype(self):
611 tarinfo = self.tar.getmember("ustar/symtype")
612 self._test_member(tarinfo, size=0, linkname="regtype")
613
614 def test_find_blktype(self):
615 tarinfo = self.tar.getmember("ustar/blktype")
616 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
617
618 def test_find_chrtype(self):
619 tarinfo = self.tar.getmember("ustar/chrtype")
620 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
621
622 def test_find_fifotype(self):
623 tarinfo = self.tar.getmember("ustar/fifotype")
624 self._test_member(tarinfo, size=0)
625
626 def test_find_sparse(self):
627 tarinfo = self.tar.getmember("ustar/sparse")
628 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
629
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000630 def test_find_gnusparse(self):
631 tarinfo = self.tar.getmember("gnu/sparse")
632 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
633
634 def test_find_gnusparse_00(self):
635 tarinfo = self.tar.getmember("gnu/sparse-0.0")
636 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
637
638 def test_find_gnusparse_01(self):
639 tarinfo = self.tar.getmember("gnu/sparse-0.1")
640 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
641
642 def test_find_gnusparse_10(self):
643 tarinfo = self.tar.getmember("gnu/sparse-1.0")
644 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
645
Guido van Rossumd8faa362007-04-27 19:54:29 +0000646 def test_find_umlauts(self):
Guido van Rossuma0557702007-08-07 23:19:53 +0000647 tarinfo = self.tar.getmember("ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000648 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
649
650 def test_find_ustar_longname(self):
651 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000652 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000653
654 def test_find_regtype_oldv7(self):
655 tarinfo = self.tar.getmember("misc/regtype-old-v7")
656 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
657
658 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000659 self.tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000660 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Guido van Rossuma0557702007-08-07 23:19:53 +0000661 tarinfo = self.tar.getmember("pax/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000662 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
663
664
665class LongnameTest(ReadTest):
666
667 def test_read_longname(self):
668 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000669 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000670 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000671 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000672 except KeyError:
673 self.fail("longname not found")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000674 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000675
676 def test_read_longlink(self):
677 longname = self.subdir + "/" + "123/" * 125 + "longname"
678 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
679 try:
680 tarinfo = self.tar.getmember(longlink)
681 except KeyError:
682 self.fail("longlink not found")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000683 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000684
685 def test_truncated_longname(self):
686 longname = self.subdir + "/" + "123/" * 125 + "longname"
687 tarinfo = self.tar.getmember(longname)
688 offset = tarinfo.offset
689 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000690 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
692
Guido van Rossume7ba4952007-06-06 23:52:48 +0000693 def test_header_offset(self):
694 # Test if the start offset of the TarInfo object includes
695 # the preceding extended header.
696 longname = self.subdir + "/" + "123/" * 125 + "longname"
697 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000698 with open(tarname, "rb") as fobj:
699 fobj.seek(offset)
700 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512), "iso8859-1", "strict")
701 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000702
Guido van Rossumd8faa362007-04-27 19:54:29 +0000703
704class GNUReadTest(LongnameTest):
705
706 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000707 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000708
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000709 # Since 3.2 tarfile is supposed to accurately restore sparse members and
710 # produce files with holes. This is what we actually want to test here.
711 # Unfortunately, not all platforms/filesystems support sparse files, and
712 # even on platforms that do it is non-trivial to make reliable assertions
713 # about holes in files. Therefore, we first do one basic test which works
714 # an all platforms, and after that a test that will work only on
715 # platforms/filesystems that prove to support sparse files.
716 def _test_sparse_file(self, name):
717 self.tar.extract(name, TEMPDIR)
718 filename = os.path.join(TEMPDIR, name)
719 with open(filename, "rb") as fobj:
720 data = fobj.read()
721 self.assertEqual(md5sum(data), md5_sparse,
722 "wrong md5sum for %s" % name)
723
724 if self._fs_supports_holes():
725 s = os.stat(filename)
726 self.assertTrue(s.st_blocks * 512 < s.st_size)
727
728 def test_sparse_file_old(self):
729 self._test_sparse_file("gnu/sparse")
730
731 def test_sparse_file_00(self):
732 self._test_sparse_file("gnu/sparse-0.0")
733
734 def test_sparse_file_01(self):
735 self._test_sparse_file("gnu/sparse-0.1")
736
737 def test_sparse_file_10(self):
738 self._test_sparse_file("gnu/sparse-1.0")
739
740 @staticmethod
741 def _fs_supports_holes():
742 # Return True if the platform knows the st_blocks stat attribute and
743 # uses st_blocks units of 512 bytes, and if the filesystem is able to
744 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200745 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000746 # Linux evidentially has 512 byte st_blocks units.
747 name = os.path.join(TEMPDIR, "sparse-test")
748 with open(name, "wb") as fobj:
749 fobj.seek(4096)
750 fobj.truncate()
751 s = os.stat(name)
752 os.remove(name)
753 return s.st_blocks == 0
754 else:
755 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756
757
Guido van Rossume7ba4952007-06-06 23:52:48 +0000758class PaxReadTest(LongnameTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000759
760 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000761 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000762
Guido van Rossume7ba4952007-06-06 23:52:48 +0000763 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000764 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000765 try:
766 tarinfo = tar.getmember("pax/regtype1")
767 self.assertEqual(tarinfo.uname, "foo")
768 self.assertEqual(tarinfo.gname, "bar")
769 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000770
Antoine Pitrou95f55602010-09-23 18:36:46 +0000771 tarinfo = tar.getmember("pax/regtype2")
772 self.assertEqual(tarinfo.uname, "")
773 self.assertEqual(tarinfo.gname, "bar")
774 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000775
Antoine Pitrou95f55602010-09-23 18:36:46 +0000776 tarinfo = tar.getmember("pax/regtype3")
777 self.assertEqual(tarinfo.uname, "tarfile")
778 self.assertEqual(tarinfo.gname, "tarfile")
779 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
780 finally:
781 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000782
783 def test_pax_number_fields(self):
784 # All following number fields are read from the pax header.
785 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000786 try:
787 tarinfo = tar.getmember("pax/regtype4")
788 self.assertEqual(tarinfo.size, 7011)
789 self.assertEqual(tarinfo.uid, 123)
790 self.assertEqual(tarinfo.gid, 123)
791 self.assertEqual(tarinfo.mtime, 1041808783.0)
792 self.assertEqual(type(tarinfo.mtime), float)
793 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
794 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
795 finally:
796 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000797
798
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000799class WriteTestBase(unittest.TestCase):
800 # Put all write tests in here that are supposed to be tested
801 # in all possible mode combinations.
802
803 def test_fileobj_no_close(self):
804 fobj = io.BytesIO()
805 tar = tarfile.open(fileobj=fobj, mode=self.mode)
806 tar.addfile(tarfile.TarInfo("foo"))
807 tar.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000808 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000809
810
811class WriteTest(WriteTestBase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000812
813 mode = "w:"
814
815 def test_100_char_name(self):
816 # The name field in a tar header stores strings of at most 100 chars.
817 # If a string is shorter than 100 chars it has to be padded with '\0',
818 # which implies that a string of exactly 100 chars is stored without
819 # a trailing '\0'.
820 name = "0123456789" * 10
821 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000822 try:
823 t = tarfile.TarInfo(name)
824 tar.addfile(t)
825 finally:
826 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000827
Guido van Rossumd8faa362007-04-27 19:54:29 +0000828 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000829 try:
830 self.assertTrue(tar.getnames()[0] == name,
831 "failed to store 100 char filename")
832 finally:
833 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000834
Guido van Rossumd8faa362007-04-27 19:54:29 +0000835 def test_tar_size(self):
836 # Test for bug #1013882.
837 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000838 try:
839 path = os.path.join(TEMPDIR, "file")
840 with open(path, "wb") as fobj:
841 fobj.write(b"aaa")
842 tar.add(path)
843 finally:
844 tar.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000845 self.assertTrue(os.path.getsize(tmpname) > 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000846 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000847
Guido van Rossumd8faa362007-04-27 19:54:29 +0000848 # The test_*_size tests test for bug #1167128.
849 def test_file_size(self):
850 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000851 try:
852 path = os.path.join(TEMPDIR, "file")
853 with open(path, "wb"):
854 pass
855 tarinfo = tar.gettarinfo(path)
856 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000857
Antoine Pitrou95f55602010-09-23 18:36:46 +0000858 with open(path, "wb") as fobj:
859 fobj.write(b"aaa")
860 tarinfo = tar.gettarinfo(path)
861 self.assertEqual(tarinfo.size, 3)
862 finally:
863 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000864
865 def test_directory_size(self):
866 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000867 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000868 try:
869 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000870 try:
871 tarinfo = tar.gettarinfo(path)
872 self.assertEqual(tarinfo.size, 0)
873 finally:
874 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000875 finally:
876 os.rmdir(path)
877
878 def test_link_size(self):
879 if hasattr(os, "link"):
880 link = os.path.join(TEMPDIR, "link")
881 target = os.path.join(TEMPDIR, "link_target")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000882 with open(target, "wb") as fobj:
883 fobj.write(b"aaa")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884 os.link(target, link)
885 try:
886 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000887 try:
888 # Record the link target in the inodes list.
889 tar.gettarinfo(target)
890 tarinfo = tar.gettarinfo(link)
891 self.assertEqual(tarinfo.size, 0)
892 finally:
893 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000894 finally:
895 os.remove(target)
896 os.remove(link)
897
Brian Curtin3b4499c2010-12-28 14:31:47 +0000898 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000899 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +0000900 path = os.path.join(TEMPDIR, "symlink")
901 os.symlink("link_target", path)
902 try:
903 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000904 try:
905 tarinfo = tar.gettarinfo(path)
906 self.assertEqual(tarinfo.size, 0)
907 finally:
908 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +0000909 finally:
910 os.remove(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000911
912 def test_add_self(self):
913 # Test for #1257255.
914 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000915 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000916 try:
917 self.assertTrue(tar.name == dstname, "archive name must be absolute")
918 tar.add(dstname)
919 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000920
Antoine Pitrou95f55602010-09-23 18:36:46 +0000921 cwd = os.getcwd()
922 os.chdir(TEMPDIR)
923 tar.add(dstname)
924 os.chdir(cwd)
925 self.assertTrue(tar.getnames() == [], "added the archive to itself")
926 finally:
927 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000928
Guido van Rossum486364b2007-06-30 05:01:58 +0000929 def test_exclude(self):
930 tempdir = os.path.join(TEMPDIR, "exclude")
931 os.mkdir(tempdir)
932 try:
933 for name in ("foo", "bar", "baz"):
934 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +0200935 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +0000936
Benjamin Peterson886af962010-03-21 23:13:07 +0000937 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +0000938
939 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000940 try:
941 with support.check_warnings(("use the filter argument",
942 DeprecationWarning)):
943 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
944 finally:
945 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000946
947 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000948 try:
949 self.assertEqual(len(tar.getmembers()), 1)
950 self.assertEqual(tar.getnames()[0], "empty_dir")
951 finally:
952 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000953 finally:
954 shutil.rmtree(tempdir)
955
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000956 def test_filter(self):
957 tempdir = os.path.join(TEMPDIR, "filter")
958 os.mkdir(tempdir)
959 try:
960 for name in ("foo", "bar", "baz"):
961 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +0200962 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000963
964 def filter(tarinfo):
965 if os.path.basename(tarinfo.name) == "bar":
966 return
967 tarinfo.uid = 123
968 tarinfo.uname = "foo"
969 return tarinfo
970
971 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000972 try:
973 tar.add(tempdir, arcname="empty_dir", filter=filter)
974 finally:
975 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000976
Raymond Hettingera63a3122011-01-26 20:34:14 +0000977 # Verify that filter is a keyword-only argument
978 with self.assertRaises(TypeError):
979 tar.add(tempdir, "empty_dir", True, None, filter)
980
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000981 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000982 try:
983 for tarinfo in tar:
984 self.assertEqual(tarinfo.uid, 123)
985 self.assertEqual(tarinfo.uname, "foo")
986 self.assertEqual(len(tar.getmembers()), 3)
987 finally:
988 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000989 finally:
990 shutil.rmtree(tempdir)
991
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000992 # Guarantee that stored pathnames are not modified. Don't
993 # remove ./ or ../ or double slashes. Still make absolute
994 # pathnames relative.
995 # For details see bug #6054.
996 def _test_pathname(self, path, cmp_path=None, dir=False):
997 # Create a tarfile with an empty member named path
998 # and compare the stored name with the original.
999 foo = os.path.join(TEMPDIR, "foo")
1000 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001001 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001002 else:
1003 os.mkdir(foo)
1004
1005 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001006 try:
1007 tar.add(foo, arcname=path)
1008 finally:
1009 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001010
1011 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001012 try:
1013 t = tar.next()
1014 finally:
1015 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001016
1017 if not dir:
1018 os.remove(foo)
1019 else:
1020 os.rmdir(foo)
1021
1022 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1023
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001024
1025 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001026 def test_extractall_symlinks(self):
1027 # Test if extractall works properly when tarfile contains symlinks
1028 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1029 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1030 os.mkdir(tempdir)
1031 try:
1032 source_file = os.path.join(tempdir,'source')
1033 target_file = os.path.join(tempdir,'symlink')
1034 with open(source_file,'w') as f:
1035 f.write('something\n')
1036 os.symlink(source_file, target_file)
1037 tar = tarfile.open(temparchive,'w')
1038 tar.add(source_file)
1039 tar.add(target_file)
1040 tar.close()
1041 # Let's extract it to the location which contains the symlink
1042 tar = tarfile.open(temparchive,'r')
1043 # this should not raise OSError: [Errno 17] File exists
1044 try:
1045 tar.extractall(path=tempdir)
1046 except OSError:
1047 self.fail("extractall failed with symlinked files")
1048 finally:
1049 tar.close()
1050 finally:
1051 os.unlink(temparchive)
1052 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001053
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001054 def test_pathnames(self):
1055 self._test_pathname("foo")
1056 self._test_pathname(os.path.join("foo", ".", "bar"))
1057 self._test_pathname(os.path.join("foo", "..", "bar"))
1058 self._test_pathname(os.path.join(".", "foo"))
1059 self._test_pathname(os.path.join(".", "foo", "."))
1060 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1061 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1062 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1063 self._test_pathname(os.path.join("..", "foo"))
1064 self._test_pathname(os.path.join("..", "foo", ".."))
1065 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1066 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1067
1068 self._test_pathname("foo" + os.sep + os.sep + "bar")
1069 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1070
1071 def test_abs_pathnames(self):
1072 if sys.platform == "win32":
1073 self._test_pathname("C:\\foo", "foo")
1074 else:
1075 self._test_pathname("/foo", "foo")
1076 self._test_pathname("///foo", "foo")
1077
1078 def test_cwd(self):
1079 # Test adding the current working directory.
1080 cwd = os.getcwd()
1081 os.chdir(TEMPDIR)
1082 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001083 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001084 try:
1085 tar.add(".")
1086 finally:
1087 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001088
1089 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001090 try:
1091 for t in tar:
Ezio Melottib3aedd42010-11-20 19:04:17 +00001092 self.assertTrue(t.name == "." or t.name.startswith("./"))
Antoine Pitrou95f55602010-09-23 18:36:46 +00001093 finally:
1094 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001095 finally:
1096 os.chdir(cwd)
1097
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001098
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001099class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001100
Guido van Rossumd8faa362007-04-27 19:54:29 +00001101 mode = "w|"
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001102
Guido van Rossumd8faa362007-04-27 19:54:29 +00001103 def test_stream_padding(self):
1104 # Test for bug #1543303.
1105 tar = tarfile.open(tmpname, self.mode)
1106 tar.close()
1107
1108 if self.mode.endswith("gz"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001109 with gzip.GzipFile(tmpname) as fobj:
1110 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001111 elif self.mode.endswith("bz2"):
1112 dec = bz2.BZ2Decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001113 with open(tmpname, "rb") as fobj:
1114 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001115 data = dec.decompress(data)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001116 self.assertTrue(len(dec.unused_data) == 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001117 "found trailing data")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001118 elif self.mode.endswith("xz"):
1119 with lzma.LZMAFile(tmpname) as fobj:
1120 data = fobj.read()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001121 else:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001122 with open(tmpname, "rb") as fobj:
1123 data = fobj.read()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001124
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001125 self.assertTrue(data.count(b"\0") == tarfile.RECORDSIZE,
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001126 "incorrect zero padding")
1127
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001128 def test_file_mode(self):
1129 # Test for issue #8464: Create files with correct
1130 # permissions.
1131 if sys.platform == "win32" or not hasattr(os, "umask"):
1132 return
1133
1134 if os.path.exists(tmpname):
1135 os.remove(tmpname)
1136
1137 original_umask = os.umask(0o022)
1138 try:
1139 tar = tarfile.open(tmpname, self.mode)
1140 tar.close()
1141 mode = os.stat(tmpname).st_mode & 0o777
1142 self.assertEqual(mode, 0o644, "wrong file permissions")
1143 finally:
1144 os.umask(original_umask)
1145
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001146
Guido van Rossumd8faa362007-04-27 19:54:29 +00001147class GNUWriteTest(unittest.TestCase):
1148 # This testcase checks for correct creation of GNU Longname
1149 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001150
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001151 def _length(self, s):
1152 blocks, remainder = divmod(len(s) + 1, 512)
1153 if remainder:
1154 blocks += 1
1155 return blocks * 512
1156
1157 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001158 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001159 count = 512
1160
1161 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001162 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001163 count += 512
1164 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001165 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001166 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001167 count += 512
1168 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001169 return count
1170
1171 def _test(self, name, link=None):
1172 tarinfo = tarfile.TarInfo(name)
1173 if link:
1174 tarinfo.linkname = link
1175 tarinfo.type = tarfile.LNKTYPE
1176
Guido van Rossumd8faa362007-04-27 19:54:29 +00001177 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001178 try:
1179 tar.format = tarfile.GNU_FORMAT
1180 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001181
Antoine Pitrou95f55602010-09-23 18:36:46 +00001182 v1 = self._calc_size(name, link)
1183 v2 = tar.offset
1184 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
1185 finally:
1186 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001187
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001189 try:
1190 member = tar.next()
1191 self.assertIsNotNone(member,
1192 "unable to read longname member")
1193 self.assertEqual(tarinfo.name, member.name,
1194 "unable to read longname member")
1195 self.assertEqual(tarinfo.linkname, member.linkname,
1196 "unable to read longname member")
1197 finally:
1198 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001199
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001200 def test_longname_1023(self):
1201 self._test(("longnam/" * 127) + "longnam")
1202
1203 def test_longname_1024(self):
1204 self._test(("longnam/" * 127) + "longname")
1205
1206 def test_longname_1025(self):
1207 self._test(("longnam/" * 127) + "longname_")
1208
1209 def test_longlink_1023(self):
1210 self._test("name", ("longlnk/" * 127) + "longlnk")
1211
1212 def test_longlink_1024(self):
1213 self._test("name", ("longlnk/" * 127) + "longlink")
1214
1215 def test_longlink_1025(self):
1216 self._test("name", ("longlnk/" * 127) + "longlink_")
1217
1218 def test_longnamelink_1023(self):
1219 self._test(("longnam/" * 127) + "longnam",
1220 ("longlnk/" * 127) + "longlnk")
1221
1222 def test_longnamelink_1024(self):
1223 self._test(("longnam/" * 127) + "longname",
1224 ("longlnk/" * 127) + "longlink")
1225
1226 def test_longnamelink_1025(self):
1227 self._test(("longnam/" * 127) + "longname_",
1228 ("longlnk/" * 127) + "longlink_")
1229
Guido van Rossumd8faa362007-04-27 19:54:29 +00001230
1231class HardlinkTest(unittest.TestCase):
1232 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001233
1234 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001235 self.foo = os.path.join(TEMPDIR, "foo")
1236 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001237
Antoine Pitrou95f55602010-09-23 18:36:46 +00001238 with open(self.foo, "wb") as fobj:
1239 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001240
Guido van Rossumd8faa362007-04-27 19:54:29 +00001241 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001242
Guido van Rossumd8faa362007-04-27 19:54:29 +00001243 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001244 self.tar.add(self.foo)
1245
Guido van Rossumd8faa362007-04-27 19:54:29 +00001246 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001247 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001248 support.unlink(self.foo)
1249 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001250
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001251 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001252 # The same name will be added as a REGTYPE every
1253 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001254 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001255 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001256 "add file as regular failed")
1257
1258 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001259 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001260 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001261 "add file as hardlink failed")
1262
1263 def test_dereference_hardlink(self):
1264 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001265 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001266 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001267 "dereferencing hardlink failed")
1268
Neal Norwitza4f651a2004-07-20 22:07:44 +00001269
Guido van Rossumd8faa362007-04-27 19:54:29 +00001270class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001271
Guido van Rossumd8faa362007-04-27 19:54:29 +00001272 def _test(self, name, link=None):
1273 # See GNUWriteTest.
1274 tarinfo = tarfile.TarInfo(name)
1275 if link:
1276 tarinfo.linkname = link
1277 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001278
Guido van Rossumd8faa362007-04-27 19:54:29 +00001279 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001280 try:
1281 tar.addfile(tarinfo)
1282 finally:
1283 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001284
Guido van Rossumd8faa362007-04-27 19:54:29 +00001285 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001286 try:
1287 if link:
1288 l = tar.getmembers()[0].linkname
1289 self.assertTrue(link == l, "PAX longlink creation failed")
1290 else:
1291 n = tar.getmembers()[0].name
1292 self.assertTrue(name == n, "PAX longname creation failed")
1293 finally:
1294 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001295
Guido van Rossume7ba4952007-06-06 23:52:48 +00001296 def test_pax_global_header(self):
1297 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001298 "foo": "bar",
1299 "uid": "0",
1300 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001301 "test": "\xe4\xf6\xfc",
1302 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001303
Benjamin Peterson886af962010-03-21 23:13:07 +00001304 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001305 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001306 try:
1307 tar.addfile(tarfile.TarInfo("test"))
1308 finally:
1309 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001310
1311 # Test if the global header was written correctly.
1312 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001313 try:
1314 self.assertEqual(tar.pax_headers, pax_headers)
1315 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1316 # Test if all the fields are strings.
1317 for key, val in tar.pax_headers.items():
1318 self.assertTrue(type(key) is not bytes)
1319 self.assertTrue(type(val) is not bytes)
1320 if key in tarfile.PAX_NUMBER_FIELDS:
1321 try:
1322 tarfile.PAX_NUMBER_FIELDS[key](val)
1323 except (TypeError, ValueError):
1324 self.fail("unable to convert pax header field")
1325 finally:
1326 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001327
1328 def test_pax_extended_header(self):
1329 # The fields from the pax header have priority over the
1330 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001331 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001332
1333 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001334 try:
1335 t = tarfile.TarInfo()
1336 t.name = "\xe4\xf6\xfc" # non-ASCII
1337 t.uid = 8**8 # too large
1338 t.pax_headers = pax_headers
1339 tar.addfile(t)
1340 finally:
1341 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001342
1343 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001344 try:
1345 t = tar.getmembers()[0]
1346 self.assertEqual(t.pax_headers, pax_headers)
1347 self.assertEqual(t.name, "foo")
1348 self.assertEqual(t.uid, 123)
1349 finally:
1350 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001351
1352
1353class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001354
1355 format = tarfile.USTAR_FORMAT
1356
1357 def test_iso8859_1_filename(self):
1358 self._test_unicode_filename("iso8859-1")
1359
1360 def test_utf7_filename(self):
1361 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001362
1363 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001364 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001365
Guido van Rossumd8faa362007-04-27 19:54:29 +00001366 def _test_unicode_filename(self, encoding):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001367 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001368 try:
1369 name = "\xe4\xf6\xfc"
1370 tar.addfile(tarfile.TarInfo(name))
1371 finally:
1372 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001373
1374 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001375 try:
1376 self.assertEqual(tar.getmembers()[0].name, name)
1377 finally:
1378 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001379
1380 def test_unicode_filename_error(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001381 if self.format == tarfile.PAX_FORMAT:
1382 # PAX_FORMAT ignores encoding in write mode.
1383 return
1384
Guido van Rossume7ba4952007-06-06 23:52:48 +00001385 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001386 try:
1387 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001388
Antoine Pitrou95f55602010-09-23 18:36:46 +00001389 tarinfo.name = "\xe4\xf6\xfc"
1390 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001391
Antoine Pitrou95f55602010-09-23 18:36:46 +00001392 tarinfo.name = "foo"
1393 tarinfo.uname = "\xe4\xf6\xfc"
1394 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1395 finally:
1396 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001397
1398 def test_unicode_argument(self):
1399 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001400 try:
1401 for t in tar:
1402 self.assertTrue(type(t.name) is str)
1403 self.assertTrue(type(t.linkname) is str)
1404 self.assertTrue(type(t.uname) is str)
1405 self.assertTrue(type(t.gname) is str)
1406 finally:
1407 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001408
Guido van Rossume7ba4952007-06-06 23:52:48 +00001409 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001410 t = tarfile.TarInfo("foo")
1411 t.uname = "\xe4\xf6\xfc"
1412 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001413
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001414 tar = tarfile.open(tmpname, mode="w", format=self.format, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001415 try:
1416 tar.addfile(t)
1417 finally:
1418 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001419
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001420 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001421 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001422 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001423 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1424 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1425
1426 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001427 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001428 tar = tarfile.open(tmpname, encoding="ascii")
1429 t = tar.getmember("foo")
1430 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1431 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1432 finally:
1433 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001434
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001435
Guido van Rossume7ba4952007-06-06 23:52:48 +00001436class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001437
Guido van Rossume7ba4952007-06-06 23:52:48 +00001438 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001439
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001440 def test_bad_pax_header(self):
1441 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1442 # without a hdrcharset=BINARY header.
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001443 for encoding, name in (("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001444 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
1445 with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar:
1446 try:
1447 t = tar.getmember(name)
1448 except KeyError:
1449 self.fail("unable to read bad GNU tar pax header")
1450
Guido van Rossumd8faa362007-04-27 19:54:29 +00001451
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001452class PAXUnicodeTest(UstarUnicodeTest):
1453
1454 format = tarfile.PAX_FORMAT
1455
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001456 def test_binary_header(self):
1457 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001458 for encoding, name in (("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001459 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
1460 with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar:
1461 try:
1462 t = tar.getmember(name)
1463 except KeyError:
1464 self.fail("unable to read POSIX.1-2008 binary header")
1465
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001466
Guido van Rossumd8faa362007-04-27 19:54:29 +00001467class AppendTest(unittest.TestCase):
1468 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001469
Guido van Rossumd8faa362007-04-27 19:54:29 +00001470 def setUp(self):
1471 self.tarname = tmpname
1472 if os.path.exists(self.tarname):
1473 os.remove(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001474
Guido van Rossumd8faa362007-04-27 19:54:29 +00001475 def _add_testfile(self, fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001476 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1477 tar.addfile(tarfile.TarInfo("bar"))
Tim Peters8ceefc52004-10-25 03:19:41 +00001478
Guido van Rossumd8faa362007-04-27 19:54:29 +00001479 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001480 with tarfile.open(tarname, encoding="iso8859-1") as src:
1481 t = src.getmember("ustar/regtype")
1482 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001483 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001484 with tarfile.open(self.tarname, mode) as tar:
1485 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001486
Guido van Rossumd8faa362007-04-27 19:54:29 +00001487 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001488 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1489 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001490
1491 def test_non_existing(self):
1492 self._add_testfile()
1493 self._test()
1494
1495 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001496 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001497 self._add_testfile()
1498 self._test()
1499
1500 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001501 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001502 self._add_testfile(fobj)
1503 fobj.seek(0)
1504 self._test(fileobj=fobj)
1505
1506 def test_fileobj(self):
1507 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001508 with open(self.tarname, "rb") as fobj:
1509 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001510 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001511 self._add_testfile(fobj)
1512 fobj.seek(0)
1513 self._test(names=["foo", "bar"], fileobj=fobj)
1514
1515 def test_existing(self):
1516 self._create_testtar()
1517 self._add_testfile()
1518 self._test(names=["foo", "bar"])
1519
1520 def test_append_gz(self):
1521 if gzip is None:
1522 return
1523 self._create_testtar("w:gz")
1524 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1525
1526 def test_append_bz2(self):
1527 if bz2 is None:
1528 return
1529 self._create_testtar("w:bz2")
1530 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1531
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001532 def test_append_lzma(self):
1533 if lzma is None:
1534 self.skipTest("lzma module not available")
1535 self._create_testtar("w:xz")
1536 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1537
Lars Gustäbel9520a432009-11-22 18:48:49 +00001538 # Append mode is supposed to fail if the tarfile to append to
1539 # does not end with a zero block.
1540 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001541 with open(self.tarname, "wb") as fobj:
1542 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001543 self.assertRaises(tarfile.ReadError, self._add_testfile)
1544
1545 def test_null(self):
1546 self._test_error(b"")
1547
1548 def test_incomplete(self):
1549 self._test_error(b"\0" * 13)
1550
1551 def test_premature_eof(self):
1552 data = tarfile.TarInfo("foo").tobuf()
1553 self._test_error(data)
1554
1555 def test_trailing_garbage(self):
1556 data = tarfile.TarInfo("foo").tobuf()
1557 self._test_error(data + b"\0" * 13)
1558
1559 def test_invalid(self):
1560 self._test_error(b"a" * 512)
1561
Guido van Rossumd8faa362007-04-27 19:54:29 +00001562
1563class LimitsTest(unittest.TestCase):
1564
1565 def test_ustar_limits(self):
1566 # 100 char name
1567 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001568 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001569
1570 # 101 char name that cannot be stored
1571 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001572 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001573
1574 # 256 char name with a slash at pos 156
1575 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001576 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001577
1578 # 256 char name that cannot be stored
1579 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001580 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001581
1582 # 512 char name
1583 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001584 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001585
1586 # 512 char linkname
1587 tarinfo = tarfile.TarInfo("longlink")
1588 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001589 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001590
1591 # uid > 8 digits
1592 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001593 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001594 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001595
1596 def test_gnu_limits(self):
1597 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001598 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001599
1600 tarinfo = tarfile.TarInfo("longlink")
1601 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001602 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001603
1604 # uid >= 256 ** 7
1605 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001606 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001607 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001608
1609 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001610 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001611 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001612
1613 tarinfo = tarfile.TarInfo("longlink")
1614 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001615 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001616
1617 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001618 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001619 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001620
1621
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001622class MiscTest(unittest.TestCase):
1623
1624 def test_char_fields(self):
1625 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"), b"foo\0\0\0\0\0")
1626 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"), b"foo")
1627 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"), "foo")
1628 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"), "foo")
1629
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001630 def test_read_number_fields(self):
1631 # Issue 13158: Test if GNU tar specific base-256 number fields
1632 # are decoded correctly.
1633 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1634 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
1635 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"), 0o10000000)
1636 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"), 0xffffffff)
1637 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"), -1)
1638 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"), -100)
1639 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"), -0x100000000000000)
1640
1641 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001642 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001643 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
1644 self.assertEqual(tarfile.itn(0o10000000), b"\x80\x00\x00\x00\x00\x20\x00\x00")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001645 self.assertEqual(tarfile.itn(0xffffffff), b"\x80\x00\x00\x00\xff\xff\xff\xff")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001646 self.assertEqual(tarfile.itn(-1), b"\xff\xff\xff\xff\xff\xff\xff\xff")
1647 self.assertEqual(tarfile.itn(-100), b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1648 self.assertEqual(tarfile.itn(-0x100000000000000), b"\xff\x00\x00\x00\x00\x00\x00\x00")
1649
1650 def test_number_field_limits(self):
1651 self.assertRaises(ValueError, tarfile.itn, -1, 8, tarfile.USTAR_FORMAT)
1652 self.assertRaises(ValueError, tarfile.itn, 0o10000000, 8, tarfile.USTAR_FORMAT)
1653 self.assertRaises(ValueError, tarfile.itn, -0x10000000001, 6, tarfile.GNU_FORMAT)
1654 self.assertRaises(ValueError, tarfile.itn, 0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001655
1656
Lars Gustäbel01385812010-03-03 12:08:54 +00001657class ContextManagerTest(unittest.TestCase):
1658
1659 def test_basic(self):
1660 with tarfile.open(tarname) as tar:
1661 self.assertFalse(tar.closed, "closed inside runtime context")
1662 self.assertTrue(tar.closed, "context manager failed")
1663
1664 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001665 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00001666 # if the TarFile object is already closed.
1667 tar = tarfile.open(tarname)
1668 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001669 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00001670 with tar:
1671 pass
1672
1673 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001674 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00001675 with self.assertRaises(Exception) as exc:
1676 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001677 raise OSError
1678 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00001679 "wrong exception raised in context manager")
1680 self.assertTrue(tar.closed, "context manager failed")
1681
1682 def test_no_eof(self):
1683 # __exit__() must not write end-of-archive blocks if an
1684 # exception was raised.
1685 try:
1686 with tarfile.open(tmpname, "w") as tar:
1687 raise Exception
1688 except:
1689 pass
1690 self.assertEqual(os.path.getsize(tmpname), 0,
1691 "context manager wrote an end-of-archive block")
1692 self.assertTrue(tar.closed, "context manager failed")
1693
1694 def test_eof(self):
1695 # __exit__() must write end-of-archive blocks, i.e. call
1696 # TarFile.close() if there was no error.
1697 with tarfile.open(tmpname, "w"):
1698 pass
1699 self.assertNotEqual(os.path.getsize(tmpname), 0,
1700 "context manager wrote no end-of-archive block")
1701
1702 def test_fileobj(self):
1703 # Test that __exit__() did not close the external file
1704 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001705 with open(tmpname, "wb") as fobj:
1706 try:
1707 with tarfile.open(fileobj=fobj, mode="w") as tar:
1708 raise Exception
1709 except:
1710 pass
1711 self.assertFalse(fobj.closed, "external file object was closed")
1712 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00001713
1714
Lars Gustäbel1b512722010-06-03 12:45:16 +00001715class LinkEmulationTest(ReadTest):
1716
1717 # Test for issue #8741 regression. On platforms that do not support
1718 # symbolic or hard links tarfile tries to extract these types of members as
1719 # the regular files they point to.
1720 def _test_link_extraction(self, name):
1721 self.tar.extract(name, TEMPDIR)
1722 data = open(os.path.join(TEMPDIR, name), "rb").read()
1723 self.assertEqual(md5sum(data), md5_regtype)
1724
Brian Curtind40e6f72010-07-08 21:39:08 +00001725 # When 8879 gets fixed, this will need to change. Currently on Windows
1726 # we have os.path.islink but no os.link, so these tests fail without the
1727 # following skip until link is completed.
1728 @unittest.skipIf(hasattr(os.path, "islink"),
1729 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001730 def test_hardlink_extraction1(self):
1731 self._test_link_extraction("ustar/lnktype")
1732
Brian Curtind40e6f72010-07-08 21:39:08 +00001733 @unittest.skipIf(hasattr(os.path, "islink"),
1734 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001735 def test_hardlink_extraction2(self):
1736 self._test_link_extraction("./ustar/linktest2/lnktype")
1737
Brian Curtin74e45612010-07-09 15:58:59 +00001738 @unittest.skipIf(hasattr(os, "symlink"),
1739 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001740 def test_symlink_extraction1(self):
1741 self._test_link_extraction("ustar/symtype")
1742
Brian Curtin74e45612010-07-09 15:58:59 +00001743 @unittest.skipIf(hasattr(os, "symlink"),
1744 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001745 def test_symlink_extraction2(self):
1746 self._test_link_extraction("./ustar/linktest2/symtype")
1747
1748
Guido van Rossumd8faa362007-04-27 19:54:29 +00001749class GzipMiscReadTest(MiscReadTest):
1750 tarname = gzipname
1751 mode = "r:gz"
Georg Brandl3abb3722011-08-13 11:48:12 +02001752
1753 def test_non_existent_targz_file(self):
1754 # Test for issue11513: prevent non-existent gzipped tarfiles raising
1755 # multiple exceptions.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001756 with self.assertRaisesRegex(OSError, "xxx") as ex:
Georg Brandl3abb3722011-08-13 11:48:12 +02001757 tarfile.open("xxx", self.mode)
1758 self.assertEqual(ex.exception.errno, errno.ENOENT)
1759
Guido van Rossumd8faa362007-04-27 19:54:29 +00001760class GzipUstarReadTest(UstarReadTest):
1761 tarname = gzipname
1762 mode = "r:gz"
1763class GzipStreamReadTest(StreamReadTest):
1764 tarname = gzipname
1765 mode = "r|gz"
1766class GzipWriteTest(WriteTest):
1767 mode = "w:gz"
1768class GzipStreamWriteTest(StreamWriteTest):
1769 mode = "w|gz"
1770
1771
1772class Bz2MiscReadTest(MiscReadTest):
1773 tarname = bz2name
1774 mode = "r:bz2"
1775class Bz2UstarReadTest(UstarReadTest):
1776 tarname = bz2name
1777 mode = "r:bz2"
1778class Bz2StreamReadTest(StreamReadTest):
1779 tarname = bz2name
1780 mode = "r|bz2"
1781class Bz2WriteTest(WriteTest):
1782 mode = "w:bz2"
1783class Bz2StreamWriteTest(StreamWriteTest):
1784 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001785
Lars Gustäbel42e00912009-03-22 20:34:29 +00001786class Bz2PartialReadTest(unittest.TestCase):
1787 # Issue5068: The _BZ2Proxy.read() method loops forever
1788 # on an empty or partial bzipped file.
1789
1790 def _test_partial_input(self, mode):
1791 class MyBytesIO(io.BytesIO):
1792 hit_eof = False
1793 def read(self, n):
1794 if self.hit_eof:
1795 raise AssertionError("infinite loop detected in tarfile.open()")
1796 self.hit_eof = self.tell() == len(self.getvalue())
1797 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001798 def seek(self, *args):
1799 self.hit_eof = False
1800 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00001801
1802 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1803 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001804 try:
1805 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
1806 except tarfile.ReadError:
1807 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00001808
1809 def test_partial_input(self):
1810 self._test_partial_input("r")
1811
1812 def test_partial_input_bz2(self):
1813 self._test_partial_input("r:bz2")
1814
1815
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001816class LzmaMiscReadTest(MiscReadTest):
1817 tarname = xzname
1818 mode = "r:xz"
1819class LzmaUstarReadTest(UstarReadTest):
1820 tarname = xzname
1821 mode = "r:xz"
1822class LzmaStreamReadTest(StreamReadTest):
1823 tarname = xzname
1824 mode = "r|xz"
1825class LzmaWriteTest(WriteTest):
1826 mode = "w:xz"
1827class LzmaStreamWriteTest(StreamWriteTest):
1828 mode = "w|xz"
1829
1830
Neal Norwitz996acf12003-02-17 14:51:41 +00001831def test_main():
Antoine Pitrou95f55602010-09-23 18:36:46 +00001832 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00001833 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001834
Walter Dörwald21d3a322003-05-01 17:45:56 +00001835 tests = [
Guido van Rossumd8faa362007-04-27 19:54:29 +00001836 UstarReadTest,
1837 MiscReadTest,
1838 StreamReadTest,
1839 DetectReadTest,
1840 MemberReadTest,
1841 GNUReadTest,
1842 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001843 WriteTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001844 StreamWriteTest,
1845 GNUWriteTest,
1846 PaxWriteTest,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001847 UstarUnicodeTest,
1848 GNUUnicodeTest,
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001849 PAXUnicodeTest,
Thomas Wouterscf297e42007-02-23 15:07:44 +00001850 AppendTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001851 LimitsTest,
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001852 MiscTest,
Lars Gustäbel01385812010-03-03 12:08:54 +00001853 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001854 ]
1855
Neal Norwitza4f651a2004-07-20 22:07:44 +00001856 if hasattr(os, "link"):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001857 tests.append(HardlinkTest)
Lars Gustäbel1b512722010-06-03 12:45:16 +00001858 else:
1859 tests.append(LinkEmulationTest)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001860
Antoine Pitrou95f55602010-09-23 18:36:46 +00001861 with open(tarname, "rb") as fobj:
1862 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001863
Walter Dörwald21d3a322003-05-01 17:45:56 +00001864 if gzip:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001865 # Create testtar.tar.gz and add gzip-specific tests.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001866 support.unlink(gzipname)
1867 with gzip.open(gzipname, "wb") as tar:
1868 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001869
1870 tests += [
1871 GzipMiscReadTest,
1872 GzipUstarReadTest,
1873 GzipStreamReadTest,
1874 GzipWriteTest,
1875 GzipStreamWriteTest,
1876 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001877
1878 if bz2:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001879 # Create testtar.tar.bz2 and add bz2-specific tests.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001880 support.unlink(bz2name)
Lars Gustäbeled1ac582011-12-06 12:56:38 +01001881 with bz2.BZ2File(bz2name, "wb") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001882 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001883
1884 tests += [
1885 Bz2MiscReadTest,
1886 Bz2UstarReadTest,
1887 Bz2StreamReadTest,
1888 Bz2WriteTest,
1889 Bz2StreamWriteTest,
Lars Gustäbel42e00912009-03-22 20:34:29 +00001890 Bz2PartialReadTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001891 ]
1892
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001893 if lzma:
1894 # Create testtar.tar.xz and add lzma-specific tests.
1895 support.unlink(xzname)
1896 with lzma.LZMAFile(xzname, "w") as tar:
1897 tar.write(data)
1898
1899 tests += [
1900 LzmaMiscReadTest,
1901 LzmaUstarReadTest,
1902 LzmaStreamReadTest,
1903 LzmaWriteTest,
1904 LzmaStreamWriteTest,
1905 ]
1906
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001907 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001908 support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001909 finally:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001910 if os.path.exists(TEMPDIR):
1911 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001912
Neal Norwitz996acf12003-02-17 14:51:41 +00001913if __name__ == "__main__":
1914 test_main()