blob: b224bf093fc8d7b8630ac7de5784101ae7ba1429 [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).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200339 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000340 tar.extract("ustar/regtype", TEMPDIR)
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200341 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000342
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200343 tar.extract("ustar/lnktype", TEMPDIR)
344 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000345 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
346 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000347 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000348
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200349 tar.extract("ustar/symtype", TEMPDIR)
350 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000351 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
352 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000353 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000354
Christian Heimesfaf2f632008-01-06 16:59:19 +0000355 def test_extractall(self):
356 # Test if extractall() correctly restores directory permissions
357 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000358 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000359 DIR = os.path.join(TEMPDIR, "extractall")
360 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000361 try:
362 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000363 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000364 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000365 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000366 if sys.platform != "win32":
367 # Win32 has no support for fine grained permissions.
368 self.assertEqual(tarinfo.mode & 0o777, os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000369 def format_mtime(mtime):
370 if isinstance(mtime, float):
371 return "{} ({})".format(mtime, mtime.hex())
372 else:
373 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000374 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000375 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
376 format_mtime(tarinfo.mtime),
377 format_mtime(file_mtime),
378 path)
379 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000380 finally:
381 tar.close()
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000382 shutil.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000383
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000384 def test_extract_directory(self):
385 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000386 DIR = os.path.join(TEMPDIR, "extractdir")
387 os.mkdir(DIR)
388 try:
389 with tarfile.open(tarname, encoding="iso8859-1") as tar:
390 tarinfo = tar.getmember(dirtype)
391 tar.extract(tarinfo, path=DIR)
392 extracted = os.path.join(DIR, dirtype)
393 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
394 if sys.platform != "win32":
395 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
396 finally:
397 shutil.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000398
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000399 def test_init_close_fobj(self):
400 # Issue #7341: Close the internal file object in the TarFile
401 # constructor in case of an error. For the test we rely on
402 # the fact that opening an empty file raises a ReadError.
403 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000404 with open(empty, "wb") as fobj:
405 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000406
407 try:
408 tar = object.__new__(tarfile.TarFile)
409 try:
410 tar.__init__(empty)
411 except tarfile.ReadError:
412 self.assertTrue(tar.fileobj.closed)
413 else:
414 self.fail("ReadError not raised")
415 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000416 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000417
Guido van Rossumd8faa362007-04-27 19:54:29 +0000418
Lars Gustäbel9520a432009-11-22 18:48:49 +0000419class StreamReadTest(CommonReadTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000420
421 mode="r|"
422
Lars Gustäbeldd071042011-02-23 11:42:22 +0000423 def test_read_through(self):
424 # Issue #11224: A poorly designed _FileInFile.read() method
425 # caused seeking errors with stream tar files.
426 for tarinfo in self.tar:
427 if not tarinfo.isreg():
428 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200429 with self.tar.extractfile(tarinfo) as fobj:
430 while True:
431 try:
432 buf = fobj.read(512)
433 except tarfile.StreamError:
434 self.fail("simple read-through using TarFile.extractfile() failed")
435 if not buf:
436 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000437
Guido van Rossumd8faa362007-04-27 19:54:29 +0000438 def test_fileobj_regular_file(self):
439 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200440 with self.tar.extractfile(tarinfo) as fobj:
441 data = fobj.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000442 self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000443 "regular file extraction failed")
444
445 def test_provoke_stream_error(self):
446 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200447 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
448 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000449
Guido van Rossumd8faa362007-04-27 19:54:29 +0000450 def test_compare_members(self):
451 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000452 try:
453 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000454
Antoine Pitrou95f55602010-09-23 18:36:46 +0000455 while True:
456 t1 = tar1.next()
457 t2 = tar2.next()
458 if t1 is None:
459 break
460 self.assertTrue(t2 is not None, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000461
Antoine Pitrou95f55602010-09-23 18:36:46 +0000462 if t2.islnk() or t2.issym():
463 self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
464 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000465
Antoine Pitrou95f55602010-09-23 18:36:46 +0000466 v1 = tar1.extractfile(t1)
467 v2 = tar2.extractfile(t2)
468 if v1 is None:
469 continue
470 self.assertTrue(v2 is not None, "stream.extractfile() failed")
471 self.assertEqual(v1.read(), v2.read(), "stream extraction failed")
472 finally:
473 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000474
Thomas Wouters89f507f2006-12-13 04:49:30 +0000475
Guido van Rossumd8faa362007-04-27 19:54:29 +0000476class DetectReadTest(unittest.TestCase):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000477
Guido van Rossumd8faa362007-04-27 19:54:29 +0000478 def _testfunc_file(self, name, mode):
479 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000480 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000481 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000483 else:
484 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000485
Guido van Rossumd8faa362007-04-27 19:54:29 +0000486 def _testfunc_fileobj(self, name, mode):
487 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000488 with open(name, "rb") as f:
489 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000490 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000491 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000492 else:
493 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000494
495 def _test_modes(self, testfunc):
496 testfunc(tarname, "r")
497 testfunc(tarname, "r:")
498 testfunc(tarname, "r:*")
499 testfunc(tarname, "r|")
500 testfunc(tarname, "r|*")
501
502 if gzip:
503 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:gz")
504 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|gz")
505 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r:")
506 self.assertRaises(tarfile.ReadError, tarfile.open, gzipname, mode="r|")
507
508 testfunc(gzipname, "r")
509 testfunc(gzipname, "r:*")
510 testfunc(gzipname, "r:gz")
511 testfunc(gzipname, "r|*")
512 testfunc(gzipname, "r|gz")
513
514 if bz2:
515 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:bz2")
516 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|bz2")
517 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r:")
518 self.assertRaises(tarfile.ReadError, tarfile.open, bz2name, mode="r|")
519
520 testfunc(bz2name, "r")
521 testfunc(bz2name, "r:*")
522 testfunc(bz2name, "r:bz2")
523 testfunc(bz2name, "r|*")
524 testfunc(bz2name, "r|bz2")
525
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100526 if lzma:
527 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r:xz")
528 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, mode="r|xz")
529 self.assertRaises(tarfile.ReadError, tarfile.open, xzname, mode="r:")
530 self.assertRaises(tarfile.ReadError, tarfile.open, xzname, mode="r|")
531
532 testfunc(xzname, "r")
533 testfunc(xzname, "r:*")
534 testfunc(xzname, "r:xz")
535 testfunc(xzname, "r|*")
536 testfunc(xzname, "r|xz")
537
Guido van Rossumd8faa362007-04-27 19:54:29 +0000538 def test_detect_file(self):
539 self._test_modes(self._testfunc_file)
540
541 def test_detect_fileobj(self):
542 self._test_modes(self._testfunc_fileobj)
543
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100544 def test_detect_stream_bz2(self):
545 # Originally, tarfile's stream detection looked for the string
546 # "BZh91" at the start of the file. This is incorrect because
547 # the '9' represents the blocksize (900kB). If the file was
548 # compressed using another blocksize autodetection fails.
549 if not bz2:
550 return
551
552 with open(tarname, "rb") as fobj:
553 data = fobj.read()
554
555 # Compress with blocksize 100kB, the file starts with "BZh11".
556 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
557 fobj.write(data)
558
559 self._testfunc_file(tmpname, "r|*")
560
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561
562class MemberReadTest(ReadTest):
563
564 def _test_member(self, tarinfo, chksum=None, **kwargs):
565 if chksum is not None:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000566 self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000567 "wrong md5sum for %s" % tarinfo.name)
568
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000569 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000570 kwargs["uid"] = 1000
571 kwargs["gid"] = 100
572 if "old-v7" not in tarinfo.name:
573 # V7 tar can't handle alphabetic owners.
574 kwargs["uname"] = "tarfile"
575 kwargs["gname"] = "tarfile"
576 for k, v in kwargs.items():
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000577 self.assertTrue(getattr(tarinfo, k) == v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000578 "wrong value in %s field of %s" % (k, tarinfo.name))
579
580 def test_find_regtype(self):
581 tarinfo = self.tar.getmember("ustar/regtype")
582 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
583
584 def test_find_conttype(self):
585 tarinfo = self.tar.getmember("ustar/conttype")
586 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
587
588 def test_find_dirtype(self):
589 tarinfo = self.tar.getmember("ustar/dirtype")
590 self._test_member(tarinfo, size=0)
591
592 def test_find_dirtype_with_size(self):
593 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
594 self._test_member(tarinfo, size=255)
595
596 def test_find_lnktype(self):
597 tarinfo = self.tar.getmember("ustar/lnktype")
598 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
599
600 def test_find_symtype(self):
601 tarinfo = self.tar.getmember("ustar/symtype")
602 self._test_member(tarinfo, size=0, linkname="regtype")
603
604 def test_find_blktype(self):
605 tarinfo = self.tar.getmember("ustar/blktype")
606 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
607
608 def test_find_chrtype(self):
609 tarinfo = self.tar.getmember("ustar/chrtype")
610 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
611
612 def test_find_fifotype(self):
613 tarinfo = self.tar.getmember("ustar/fifotype")
614 self._test_member(tarinfo, size=0)
615
616 def test_find_sparse(self):
617 tarinfo = self.tar.getmember("ustar/sparse")
618 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
619
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000620 def test_find_gnusparse(self):
621 tarinfo = self.tar.getmember("gnu/sparse")
622 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
623
624 def test_find_gnusparse_00(self):
625 tarinfo = self.tar.getmember("gnu/sparse-0.0")
626 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
627
628 def test_find_gnusparse_01(self):
629 tarinfo = self.tar.getmember("gnu/sparse-0.1")
630 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
631
632 def test_find_gnusparse_10(self):
633 tarinfo = self.tar.getmember("gnu/sparse-1.0")
634 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
635
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636 def test_find_umlauts(self):
Guido van Rossuma0557702007-08-07 23:19:53 +0000637 tarinfo = self.tar.getmember("ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000638 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
639
640 def test_find_ustar_longname(self):
641 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000642 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000643
644 def test_find_regtype_oldv7(self):
645 tarinfo = self.tar.getmember("misc/regtype-old-v7")
646 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
647
648 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000649 self.tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000650 self.tar = tarfile.open(self.tarname, mode=self.mode, encoding="iso8859-1")
Guido van Rossuma0557702007-08-07 23:19:53 +0000651 tarinfo = self.tar.getmember("pax/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000652 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
653
654
655class LongnameTest(ReadTest):
656
657 def test_read_longname(self):
658 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000659 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000660 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000661 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000662 except KeyError:
663 self.fail("longname not found")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000664 self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000665
666 def test_read_longlink(self):
667 longname = self.subdir + "/" + "123/" * 125 + "longname"
668 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
669 try:
670 tarinfo = self.tar.getmember(longlink)
671 except KeyError:
672 self.fail("longlink not found")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000673 self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000674
675 def test_truncated_longname(self):
676 longname = self.subdir + "/" + "123/" * 125 + "longname"
677 tarinfo = self.tar.getmember(longname)
678 offset = tarinfo.offset
679 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000680 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000681 self.assertRaises(tarfile.ReadError, tarfile.open, name="foo.tar", fileobj=fobj)
682
Guido van Rossume7ba4952007-06-06 23:52:48 +0000683 def test_header_offset(self):
684 # Test if the start offset of the TarInfo object includes
685 # the preceding extended header.
686 longname = self.subdir + "/" + "123/" * 125 + "longname"
687 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000688 with open(tarname, "rb") as fobj:
689 fobj.seek(offset)
690 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512), "iso8859-1", "strict")
691 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000692
Guido van Rossumd8faa362007-04-27 19:54:29 +0000693
694class GNUReadTest(LongnameTest):
695
696 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000697 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000698
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000699 # Since 3.2 tarfile is supposed to accurately restore sparse members and
700 # produce files with holes. This is what we actually want to test here.
701 # Unfortunately, not all platforms/filesystems support sparse files, and
702 # even on platforms that do it is non-trivial to make reliable assertions
703 # about holes in files. Therefore, we first do one basic test which works
704 # an all platforms, and after that a test that will work only on
705 # platforms/filesystems that prove to support sparse files.
706 def _test_sparse_file(self, name):
707 self.tar.extract(name, TEMPDIR)
708 filename = os.path.join(TEMPDIR, name)
709 with open(filename, "rb") as fobj:
710 data = fobj.read()
711 self.assertEqual(md5sum(data), md5_sparse,
712 "wrong md5sum for %s" % name)
713
714 if self._fs_supports_holes():
715 s = os.stat(filename)
716 self.assertTrue(s.st_blocks * 512 < s.st_size)
717
718 def test_sparse_file_old(self):
719 self._test_sparse_file("gnu/sparse")
720
721 def test_sparse_file_00(self):
722 self._test_sparse_file("gnu/sparse-0.0")
723
724 def test_sparse_file_01(self):
725 self._test_sparse_file("gnu/sparse-0.1")
726
727 def test_sparse_file_10(self):
728 self._test_sparse_file("gnu/sparse-1.0")
729
730 @staticmethod
731 def _fs_supports_holes():
732 # Return True if the platform knows the st_blocks stat attribute and
733 # uses st_blocks units of 512 bytes, and if the filesystem is able to
734 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200735 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000736 # Linux evidentially has 512 byte st_blocks units.
737 name = os.path.join(TEMPDIR, "sparse-test")
738 with open(name, "wb") as fobj:
739 fobj.seek(4096)
740 fobj.truncate()
741 s = os.stat(name)
742 os.remove(name)
743 return s.st_blocks == 0
744 else:
745 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000746
747
Guido van Rossume7ba4952007-06-06 23:52:48 +0000748class PaxReadTest(LongnameTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000749
750 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000751 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000752
Guido van Rossume7ba4952007-06-06 23:52:48 +0000753 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000754 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000755 try:
756 tarinfo = tar.getmember("pax/regtype1")
757 self.assertEqual(tarinfo.uname, "foo")
758 self.assertEqual(tarinfo.gname, "bar")
759 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000760
Antoine Pitrou95f55602010-09-23 18:36:46 +0000761 tarinfo = tar.getmember("pax/regtype2")
762 self.assertEqual(tarinfo.uname, "")
763 self.assertEqual(tarinfo.gname, "bar")
764 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000765
Antoine Pitrou95f55602010-09-23 18:36:46 +0000766 tarinfo = tar.getmember("pax/regtype3")
767 self.assertEqual(tarinfo.uname, "tarfile")
768 self.assertEqual(tarinfo.gname, "tarfile")
769 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"), "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
770 finally:
771 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000772
773 def test_pax_number_fields(self):
774 # All following number fields are read from the pax header.
775 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000776 try:
777 tarinfo = tar.getmember("pax/regtype4")
778 self.assertEqual(tarinfo.size, 7011)
779 self.assertEqual(tarinfo.uid, 123)
780 self.assertEqual(tarinfo.gid, 123)
781 self.assertEqual(tarinfo.mtime, 1041808783.0)
782 self.assertEqual(type(tarinfo.mtime), float)
783 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
784 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
785 finally:
786 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000787
788
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000789class WriteTestBase(unittest.TestCase):
790 # Put all write tests in here that are supposed to be tested
791 # in all possible mode combinations.
792
793 def test_fileobj_no_close(self):
794 fobj = io.BytesIO()
795 tar = tarfile.open(fileobj=fobj, mode=self.mode)
796 tar.addfile(tarfile.TarInfo("foo"))
797 tar.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000798 self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000799
800
801class WriteTest(WriteTestBase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000802
803 mode = "w:"
804
805 def test_100_char_name(self):
806 # The name field in a tar header stores strings of at most 100 chars.
807 # If a string is shorter than 100 chars it has to be padded with '\0',
808 # which implies that a string of exactly 100 chars is stored without
809 # a trailing '\0'.
810 name = "0123456789" * 10
811 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000812 try:
813 t = tarfile.TarInfo(name)
814 tar.addfile(t)
815 finally:
816 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000817
Guido van Rossumd8faa362007-04-27 19:54:29 +0000818 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000819 try:
820 self.assertTrue(tar.getnames()[0] == name,
821 "failed to store 100 char filename")
822 finally:
823 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000824
Guido van Rossumd8faa362007-04-27 19:54:29 +0000825 def test_tar_size(self):
826 # Test for bug #1013882.
827 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000828 try:
829 path = os.path.join(TEMPDIR, "file")
830 with open(path, "wb") as fobj:
831 fobj.write(b"aaa")
832 tar.add(path)
833 finally:
834 tar.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000835 self.assertTrue(os.path.getsize(tmpname) > 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000836 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000837
Guido van Rossumd8faa362007-04-27 19:54:29 +0000838 # The test_*_size tests test for bug #1167128.
839 def test_file_size(self):
840 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000841 try:
842 path = os.path.join(TEMPDIR, "file")
843 with open(path, "wb"):
844 pass
845 tarinfo = tar.gettarinfo(path)
846 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000847
Antoine Pitrou95f55602010-09-23 18:36:46 +0000848 with open(path, "wb") as fobj:
849 fobj.write(b"aaa")
850 tarinfo = tar.gettarinfo(path)
851 self.assertEqual(tarinfo.size, 3)
852 finally:
853 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000854
855 def test_directory_size(self):
856 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000857 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000858 try:
859 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000860 try:
861 tarinfo = tar.gettarinfo(path)
862 self.assertEqual(tarinfo.size, 0)
863 finally:
864 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000865 finally:
866 os.rmdir(path)
867
868 def test_link_size(self):
869 if hasattr(os, "link"):
870 link = os.path.join(TEMPDIR, "link")
871 target = os.path.join(TEMPDIR, "link_target")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000872 with open(target, "wb") as fobj:
873 fobj.write(b"aaa")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000874 os.link(target, link)
875 try:
876 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000877 try:
878 # Record the link target in the inodes list.
879 tar.gettarinfo(target)
880 tarinfo = tar.gettarinfo(link)
881 self.assertEqual(tarinfo.size, 0)
882 finally:
883 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884 finally:
885 os.remove(target)
886 os.remove(link)
887
Brian Curtin3b4499c2010-12-28 14:31:47 +0000888 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000889 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +0000890 path = os.path.join(TEMPDIR, "symlink")
891 os.symlink("link_target", path)
892 try:
893 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000894 try:
895 tarinfo = tar.gettarinfo(path)
896 self.assertEqual(tarinfo.size, 0)
897 finally:
898 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +0000899 finally:
900 os.remove(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000901
902 def test_add_self(self):
903 # Test for #1257255.
904 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000905 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000906 try:
907 self.assertTrue(tar.name == dstname, "archive name must be absolute")
908 tar.add(dstname)
909 self.assertTrue(tar.getnames() == [], "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000910
Antoine Pitrou95f55602010-09-23 18:36:46 +0000911 cwd = os.getcwd()
912 os.chdir(TEMPDIR)
913 tar.add(dstname)
914 os.chdir(cwd)
915 self.assertTrue(tar.getnames() == [], "added the archive to itself")
916 finally:
917 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000918
Guido van Rossum486364b2007-06-30 05:01:58 +0000919 def test_exclude(self):
920 tempdir = os.path.join(TEMPDIR, "exclude")
921 os.mkdir(tempdir)
922 try:
923 for name in ("foo", "bar", "baz"):
924 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +0200925 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +0000926
Benjamin Peterson886af962010-03-21 23:13:07 +0000927 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +0000928
929 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000930 try:
931 with support.check_warnings(("use the filter argument",
932 DeprecationWarning)):
933 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
934 finally:
935 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000936
937 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000938 try:
939 self.assertEqual(len(tar.getmembers()), 1)
940 self.assertEqual(tar.getnames()[0], "empty_dir")
941 finally:
942 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000943 finally:
944 shutil.rmtree(tempdir)
945
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000946 def test_filter(self):
947 tempdir = os.path.join(TEMPDIR, "filter")
948 os.mkdir(tempdir)
949 try:
950 for name in ("foo", "bar", "baz"):
951 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +0200952 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000953
954 def filter(tarinfo):
955 if os.path.basename(tarinfo.name) == "bar":
956 return
957 tarinfo.uid = 123
958 tarinfo.uname = "foo"
959 return tarinfo
960
961 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000962 try:
963 tar.add(tempdir, arcname="empty_dir", filter=filter)
964 finally:
965 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000966
Raymond Hettingera63a3122011-01-26 20:34:14 +0000967 # Verify that filter is a keyword-only argument
968 with self.assertRaises(TypeError):
969 tar.add(tempdir, "empty_dir", True, None, filter)
970
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000971 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000972 try:
973 for tarinfo in tar:
974 self.assertEqual(tarinfo.uid, 123)
975 self.assertEqual(tarinfo.uname, "foo")
976 self.assertEqual(len(tar.getmembers()), 3)
977 finally:
978 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000979 finally:
980 shutil.rmtree(tempdir)
981
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000982 # Guarantee that stored pathnames are not modified. Don't
983 # remove ./ or ../ or double slashes. Still make absolute
984 # pathnames relative.
985 # For details see bug #6054.
986 def _test_pathname(self, path, cmp_path=None, dir=False):
987 # Create a tarfile with an empty member named path
988 # and compare the stored name with the original.
989 foo = os.path.join(TEMPDIR, "foo")
990 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +0200991 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000992 else:
993 os.mkdir(foo)
994
995 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000996 try:
997 tar.add(foo, arcname=path)
998 finally:
999 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001000
1001 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001002 try:
1003 t = tar.next()
1004 finally:
1005 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001006
1007 if not dir:
1008 os.remove(foo)
1009 else:
1010 os.rmdir(foo)
1011
1012 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1013
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001014
1015 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001016 def test_extractall_symlinks(self):
1017 # Test if extractall works properly when tarfile contains symlinks
1018 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1019 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1020 os.mkdir(tempdir)
1021 try:
1022 source_file = os.path.join(tempdir,'source')
1023 target_file = os.path.join(tempdir,'symlink')
1024 with open(source_file,'w') as f:
1025 f.write('something\n')
1026 os.symlink(source_file, target_file)
1027 tar = tarfile.open(temparchive,'w')
1028 tar.add(source_file)
1029 tar.add(target_file)
1030 tar.close()
1031 # Let's extract it to the location which contains the symlink
1032 tar = tarfile.open(temparchive,'r')
1033 # this should not raise OSError: [Errno 17] File exists
1034 try:
1035 tar.extractall(path=tempdir)
1036 except OSError:
1037 self.fail("extractall failed with symlinked files")
1038 finally:
1039 tar.close()
1040 finally:
1041 os.unlink(temparchive)
1042 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001043
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001044 def test_pathnames(self):
1045 self._test_pathname("foo")
1046 self._test_pathname(os.path.join("foo", ".", "bar"))
1047 self._test_pathname(os.path.join("foo", "..", "bar"))
1048 self._test_pathname(os.path.join(".", "foo"))
1049 self._test_pathname(os.path.join(".", "foo", "."))
1050 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1051 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1052 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1053 self._test_pathname(os.path.join("..", "foo"))
1054 self._test_pathname(os.path.join("..", "foo", ".."))
1055 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1056 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1057
1058 self._test_pathname("foo" + os.sep + os.sep + "bar")
1059 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1060
1061 def test_abs_pathnames(self):
1062 if sys.platform == "win32":
1063 self._test_pathname("C:\\foo", "foo")
1064 else:
1065 self._test_pathname("/foo", "foo")
1066 self._test_pathname("///foo", "foo")
1067
1068 def test_cwd(self):
1069 # Test adding the current working directory.
1070 cwd = os.getcwd()
1071 os.chdir(TEMPDIR)
1072 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001073 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001074 try:
1075 tar.add(".")
1076 finally:
1077 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001078
1079 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001080 try:
1081 for t in tar:
Ezio Melottib3aedd42010-11-20 19:04:17 +00001082 self.assertTrue(t.name == "." or t.name.startswith("./"))
Antoine Pitrou95f55602010-09-23 18:36:46 +00001083 finally:
1084 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001085 finally:
1086 os.chdir(cwd)
1087
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001088
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001089class StreamWriteTest(WriteTestBase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001090
Guido van Rossumd8faa362007-04-27 19:54:29 +00001091 mode = "w|"
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001092
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093 def test_stream_padding(self):
1094 # Test for bug #1543303.
1095 tar = tarfile.open(tmpname, self.mode)
1096 tar.close()
1097
1098 if self.mode.endswith("gz"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001099 with gzip.GzipFile(tmpname) as fobj:
1100 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001101 elif self.mode.endswith("bz2"):
1102 dec = bz2.BZ2Decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001103 with open(tmpname, "rb") as fobj:
1104 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001105 data = dec.decompress(data)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001106 self.assertTrue(len(dec.unused_data) == 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001107 "found trailing data")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001108 elif self.mode.endswith("xz"):
1109 with lzma.LZMAFile(tmpname) as fobj:
1110 data = fobj.read()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001111 else:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001112 with open(tmpname, "rb") as fobj:
1113 data = fobj.read()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001114
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001115 self.assertTrue(data.count(b"\0") == tarfile.RECORDSIZE,
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001116 "incorrect zero padding")
1117
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001118 def test_file_mode(self):
1119 # Test for issue #8464: Create files with correct
1120 # permissions.
1121 if sys.platform == "win32" or not hasattr(os, "umask"):
1122 return
1123
1124 if os.path.exists(tmpname):
1125 os.remove(tmpname)
1126
1127 original_umask = os.umask(0o022)
1128 try:
1129 tar = tarfile.open(tmpname, self.mode)
1130 tar.close()
1131 mode = os.stat(tmpname).st_mode & 0o777
1132 self.assertEqual(mode, 0o644, "wrong file permissions")
1133 finally:
1134 os.umask(original_umask)
1135
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001136
Guido van Rossumd8faa362007-04-27 19:54:29 +00001137class GNUWriteTest(unittest.TestCase):
1138 # This testcase checks for correct creation of GNU Longname
1139 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001140
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001141 def _length(self, s):
1142 blocks, remainder = divmod(len(s) + 1, 512)
1143 if remainder:
1144 blocks += 1
1145 return blocks * 512
1146
1147 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001148 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001149 count = 512
1150
1151 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001152 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001153 count += 512
1154 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001155 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001156 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001157 count += 512
1158 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001159 return count
1160
1161 def _test(self, name, link=None):
1162 tarinfo = tarfile.TarInfo(name)
1163 if link:
1164 tarinfo.linkname = link
1165 tarinfo.type = tarfile.LNKTYPE
1166
Guido van Rossumd8faa362007-04-27 19:54:29 +00001167 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001168 try:
1169 tar.format = tarfile.GNU_FORMAT
1170 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001171
Antoine Pitrou95f55602010-09-23 18:36:46 +00001172 v1 = self._calc_size(name, link)
1173 v2 = tar.offset
1174 self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
1175 finally:
1176 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001177
Guido van Rossumd8faa362007-04-27 19:54:29 +00001178 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001179 try:
1180 member = tar.next()
1181 self.assertIsNotNone(member,
1182 "unable to read longname member")
1183 self.assertEqual(tarinfo.name, member.name,
1184 "unable to read longname member")
1185 self.assertEqual(tarinfo.linkname, member.linkname,
1186 "unable to read longname member")
1187 finally:
1188 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001189
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001190 def test_longname_1023(self):
1191 self._test(("longnam/" * 127) + "longnam")
1192
1193 def test_longname_1024(self):
1194 self._test(("longnam/" * 127) + "longname")
1195
1196 def test_longname_1025(self):
1197 self._test(("longnam/" * 127) + "longname_")
1198
1199 def test_longlink_1023(self):
1200 self._test("name", ("longlnk/" * 127) + "longlnk")
1201
1202 def test_longlink_1024(self):
1203 self._test("name", ("longlnk/" * 127) + "longlink")
1204
1205 def test_longlink_1025(self):
1206 self._test("name", ("longlnk/" * 127) + "longlink_")
1207
1208 def test_longnamelink_1023(self):
1209 self._test(("longnam/" * 127) + "longnam",
1210 ("longlnk/" * 127) + "longlnk")
1211
1212 def test_longnamelink_1024(self):
1213 self._test(("longnam/" * 127) + "longname",
1214 ("longlnk/" * 127) + "longlink")
1215
1216 def test_longnamelink_1025(self):
1217 self._test(("longnam/" * 127) + "longname_",
1218 ("longlnk/" * 127) + "longlink_")
1219
Guido van Rossumd8faa362007-04-27 19:54:29 +00001220
1221class HardlinkTest(unittest.TestCase):
1222 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001223
1224 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001225 self.foo = os.path.join(TEMPDIR, "foo")
1226 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001227
Antoine Pitrou95f55602010-09-23 18:36:46 +00001228 with open(self.foo, "wb") as fobj:
1229 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001230
Guido van Rossumd8faa362007-04-27 19:54:29 +00001231 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001232
Guido van Rossumd8faa362007-04-27 19:54:29 +00001233 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001234 self.tar.add(self.foo)
1235
Guido van Rossumd8faa362007-04-27 19:54:29 +00001236 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001237 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001238 support.unlink(self.foo)
1239 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001240
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001241 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001242 # The same name will be added as a REGTYPE every
1243 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001244 tarinfo = self.tar.gettarinfo(self.foo)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001245 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001246 "add file as regular failed")
1247
1248 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001249 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001250 self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001251 "add file as hardlink failed")
1252
1253 def test_dereference_hardlink(self):
1254 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001255 tarinfo = self.tar.gettarinfo(self.bar)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001256 self.assertTrue(tarinfo.type == tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001257 "dereferencing hardlink failed")
1258
Neal Norwitza4f651a2004-07-20 22:07:44 +00001259
Guido van Rossumd8faa362007-04-27 19:54:29 +00001260class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001261
Guido van Rossumd8faa362007-04-27 19:54:29 +00001262 def _test(self, name, link=None):
1263 # See GNUWriteTest.
1264 tarinfo = tarfile.TarInfo(name)
1265 if link:
1266 tarinfo.linkname = link
1267 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001268
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001270 try:
1271 tar.addfile(tarinfo)
1272 finally:
1273 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001274
Guido van Rossumd8faa362007-04-27 19:54:29 +00001275 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001276 try:
1277 if link:
1278 l = tar.getmembers()[0].linkname
1279 self.assertTrue(link == l, "PAX longlink creation failed")
1280 else:
1281 n = tar.getmembers()[0].name
1282 self.assertTrue(name == n, "PAX longname creation failed")
1283 finally:
1284 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001285
Guido van Rossume7ba4952007-06-06 23:52:48 +00001286 def test_pax_global_header(self):
1287 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001288 "foo": "bar",
1289 "uid": "0",
1290 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001291 "test": "\xe4\xf6\xfc",
1292 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001293
Benjamin Peterson886af962010-03-21 23:13:07 +00001294 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001295 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001296 try:
1297 tar.addfile(tarfile.TarInfo("test"))
1298 finally:
1299 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001300
1301 # Test if the global header was written correctly.
1302 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001303 try:
1304 self.assertEqual(tar.pax_headers, pax_headers)
1305 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1306 # Test if all the fields are strings.
1307 for key, val in tar.pax_headers.items():
1308 self.assertTrue(type(key) is not bytes)
1309 self.assertTrue(type(val) is not bytes)
1310 if key in tarfile.PAX_NUMBER_FIELDS:
1311 try:
1312 tarfile.PAX_NUMBER_FIELDS[key](val)
1313 except (TypeError, ValueError):
1314 self.fail("unable to convert pax header field")
1315 finally:
1316 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001317
1318 def test_pax_extended_header(self):
1319 # The fields from the pax header have priority over the
1320 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001321 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001322
1323 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001324 try:
1325 t = tarfile.TarInfo()
1326 t.name = "\xe4\xf6\xfc" # non-ASCII
1327 t.uid = 8**8 # too large
1328 t.pax_headers = pax_headers
1329 tar.addfile(t)
1330 finally:
1331 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001332
1333 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001334 try:
1335 t = tar.getmembers()[0]
1336 self.assertEqual(t.pax_headers, pax_headers)
1337 self.assertEqual(t.name, "foo")
1338 self.assertEqual(t.uid, 123)
1339 finally:
1340 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001341
1342
1343class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001344
1345 format = tarfile.USTAR_FORMAT
1346
1347 def test_iso8859_1_filename(self):
1348 self._test_unicode_filename("iso8859-1")
1349
1350 def test_utf7_filename(self):
1351 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001352
1353 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001354 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001355
Guido van Rossumd8faa362007-04-27 19:54:29 +00001356 def _test_unicode_filename(self, encoding):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001357 tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001358 try:
1359 name = "\xe4\xf6\xfc"
1360 tar.addfile(tarfile.TarInfo(name))
1361 finally:
1362 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001363
1364 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001365 try:
1366 self.assertEqual(tar.getmembers()[0].name, name)
1367 finally:
1368 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001369
1370 def test_unicode_filename_error(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001371 if self.format == tarfile.PAX_FORMAT:
1372 # PAX_FORMAT ignores encoding in write mode.
1373 return
1374
Guido van Rossume7ba4952007-06-06 23:52:48 +00001375 tar = tarfile.open(tmpname, "w", format=self.format, encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001376 try:
1377 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001378
Antoine Pitrou95f55602010-09-23 18:36:46 +00001379 tarinfo.name = "\xe4\xf6\xfc"
1380 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001381
Antoine Pitrou95f55602010-09-23 18:36:46 +00001382 tarinfo.name = "foo"
1383 tarinfo.uname = "\xe4\xf6\xfc"
1384 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1385 finally:
1386 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001387
1388 def test_unicode_argument(self):
1389 tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001390 try:
1391 for t in tar:
1392 self.assertTrue(type(t.name) is str)
1393 self.assertTrue(type(t.linkname) is str)
1394 self.assertTrue(type(t.uname) is str)
1395 self.assertTrue(type(t.gname) is str)
1396 finally:
1397 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001398
Guido van Rossume7ba4952007-06-06 23:52:48 +00001399 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001400 t = tarfile.TarInfo("foo")
1401 t.uname = "\xe4\xf6\xfc"
1402 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001403
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001404 tar = tarfile.open(tmpname, mode="w", format=self.format, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001405 try:
1406 tar.addfile(t)
1407 finally:
1408 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001409
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001410 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001411 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001412 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001413 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1414 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1415
1416 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001417 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001418 tar = tarfile.open(tmpname, encoding="ascii")
1419 t = tar.getmember("foo")
1420 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1421 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1422 finally:
1423 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001424
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001425
Guido van Rossume7ba4952007-06-06 23:52:48 +00001426class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001427
Guido van Rossume7ba4952007-06-06 23:52:48 +00001428 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001429
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001430 def test_bad_pax_header(self):
1431 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1432 # without a hdrcharset=BINARY header.
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001433 for encoding, name in (("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001434 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
1435 with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar:
1436 try:
1437 t = tar.getmember(name)
1438 except KeyError:
1439 self.fail("unable to read bad GNU tar pax header")
1440
Guido van Rossumd8faa362007-04-27 19:54:29 +00001441
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001442class PAXUnicodeTest(UstarUnicodeTest):
1443
1444 format = tarfile.PAX_FORMAT
1445
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001446 def test_binary_header(self):
1447 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001448 for encoding, name in (("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001449 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
1450 with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar:
1451 try:
1452 t = tar.getmember(name)
1453 except KeyError:
1454 self.fail("unable to read POSIX.1-2008 binary header")
1455
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001456
Guido van Rossumd8faa362007-04-27 19:54:29 +00001457class AppendTest(unittest.TestCase):
1458 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001459
Guido van Rossumd8faa362007-04-27 19:54:29 +00001460 def setUp(self):
1461 self.tarname = tmpname
1462 if os.path.exists(self.tarname):
1463 os.remove(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001464
Guido van Rossumd8faa362007-04-27 19:54:29 +00001465 def _add_testfile(self, fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001466 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1467 tar.addfile(tarfile.TarInfo("bar"))
Tim Peters8ceefc52004-10-25 03:19:41 +00001468
Guido van Rossumd8faa362007-04-27 19:54:29 +00001469 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001470 with tarfile.open(tarname, encoding="iso8859-1") as src:
1471 t = src.getmember("ustar/regtype")
1472 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001473 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001474 with tarfile.open(self.tarname, mode) as tar:
1475 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001476
Guido van Rossumd8faa362007-04-27 19:54:29 +00001477 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001478 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1479 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001480
1481 def test_non_existing(self):
1482 self._add_testfile()
1483 self._test()
1484
1485 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001486 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001487 self._add_testfile()
1488 self._test()
1489
1490 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001491 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001492 self._add_testfile(fobj)
1493 fobj.seek(0)
1494 self._test(fileobj=fobj)
1495
1496 def test_fileobj(self):
1497 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001498 with open(self.tarname, "rb") as fobj:
1499 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001500 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001501 self._add_testfile(fobj)
1502 fobj.seek(0)
1503 self._test(names=["foo", "bar"], fileobj=fobj)
1504
1505 def test_existing(self):
1506 self._create_testtar()
1507 self._add_testfile()
1508 self._test(names=["foo", "bar"])
1509
1510 def test_append_gz(self):
1511 if gzip is None:
1512 return
1513 self._create_testtar("w:gz")
1514 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1515
1516 def test_append_bz2(self):
1517 if bz2 is None:
1518 return
1519 self._create_testtar("w:bz2")
1520 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1521
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001522 def test_append_lzma(self):
1523 if lzma is None:
1524 self.skipTest("lzma module not available")
1525 self._create_testtar("w:xz")
1526 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1527
Lars Gustäbel9520a432009-11-22 18:48:49 +00001528 # Append mode is supposed to fail if the tarfile to append to
1529 # does not end with a zero block.
1530 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001531 with open(self.tarname, "wb") as fobj:
1532 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001533 self.assertRaises(tarfile.ReadError, self._add_testfile)
1534
1535 def test_null(self):
1536 self._test_error(b"")
1537
1538 def test_incomplete(self):
1539 self._test_error(b"\0" * 13)
1540
1541 def test_premature_eof(self):
1542 data = tarfile.TarInfo("foo").tobuf()
1543 self._test_error(data)
1544
1545 def test_trailing_garbage(self):
1546 data = tarfile.TarInfo("foo").tobuf()
1547 self._test_error(data + b"\0" * 13)
1548
1549 def test_invalid(self):
1550 self._test_error(b"a" * 512)
1551
Guido van Rossumd8faa362007-04-27 19:54:29 +00001552
1553class LimitsTest(unittest.TestCase):
1554
1555 def test_ustar_limits(self):
1556 # 100 char name
1557 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001558 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001559
1560 # 101 char name that cannot be stored
1561 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001562 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001563
1564 # 256 char name with a slash at pos 156
1565 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001566 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001567
1568 # 256 char name that cannot be stored
1569 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001570 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001571
1572 # 512 char name
1573 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001574 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001575
1576 # 512 char linkname
1577 tarinfo = tarfile.TarInfo("longlink")
1578 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001579 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001580
1581 # uid > 8 digits
1582 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001583 tarinfo.uid = 0o10000000
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 def test_gnu_limits(self):
1587 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001588 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001589
1590 tarinfo = tarfile.TarInfo("longlink")
1591 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001592 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001593
1594 # uid >= 256 ** 7
1595 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001596 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001597 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001598
1599 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001600 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001601 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001602
1603 tarinfo = tarfile.TarInfo("longlink")
1604 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001605 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001606
1607 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001608 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001609 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001610
1611
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001612class MiscTest(unittest.TestCase):
1613
1614 def test_char_fields(self):
1615 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"), b"foo\0\0\0\0\0")
1616 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"), b"foo")
1617 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"), "foo")
1618 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"), "foo")
1619
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001620 def test_read_number_fields(self):
1621 # Issue 13158: Test if GNU tar specific base-256 number fields
1622 # are decoded correctly.
1623 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1624 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
1625 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"), 0o10000000)
1626 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"), 0xffffffff)
1627 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"), -1)
1628 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"), -100)
1629 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"), -0x100000000000000)
1630
1631 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001632 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001633 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
1634 self.assertEqual(tarfile.itn(0o10000000), b"\x80\x00\x00\x00\x00\x20\x00\x00")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001635 self.assertEqual(tarfile.itn(0xffffffff), b"\x80\x00\x00\x00\xff\xff\xff\xff")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001636 self.assertEqual(tarfile.itn(-1), b"\xff\xff\xff\xff\xff\xff\xff\xff")
1637 self.assertEqual(tarfile.itn(-100), b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1638 self.assertEqual(tarfile.itn(-0x100000000000000), b"\xff\x00\x00\x00\x00\x00\x00\x00")
1639
1640 def test_number_field_limits(self):
1641 self.assertRaises(ValueError, tarfile.itn, -1, 8, tarfile.USTAR_FORMAT)
1642 self.assertRaises(ValueError, tarfile.itn, 0o10000000, 8, tarfile.USTAR_FORMAT)
1643 self.assertRaises(ValueError, tarfile.itn, -0x10000000001, 6, tarfile.GNU_FORMAT)
1644 self.assertRaises(ValueError, tarfile.itn, 0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001645
1646
Lars Gustäbel01385812010-03-03 12:08:54 +00001647class ContextManagerTest(unittest.TestCase):
1648
1649 def test_basic(self):
1650 with tarfile.open(tarname) as tar:
1651 self.assertFalse(tar.closed, "closed inside runtime context")
1652 self.assertTrue(tar.closed, "context manager failed")
1653
1654 def test_closed(self):
1655 # The __enter__() method is supposed to raise IOError
1656 # if the TarFile object is already closed.
1657 tar = tarfile.open(tarname)
1658 tar.close()
1659 with self.assertRaises(IOError):
1660 with tar:
1661 pass
1662
1663 def test_exception(self):
1664 # Test if the IOError exception is passed through properly.
1665 with self.assertRaises(Exception) as exc:
1666 with tarfile.open(tarname) as tar:
1667 raise IOError
1668 self.assertIsInstance(exc.exception, IOError,
1669 "wrong exception raised in context manager")
1670 self.assertTrue(tar.closed, "context manager failed")
1671
1672 def test_no_eof(self):
1673 # __exit__() must not write end-of-archive blocks if an
1674 # exception was raised.
1675 try:
1676 with tarfile.open(tmpname, "w") as tar:
1677 raise Exception
1678 except:
1679 pass
1680 self.assertEqual(os.path.getsize(tmpname), 0,
1681 "context manager wrote an end-of-archive block")
1682 self.assertTrue(tar.closed, "context manager failed")
1683
1684 def test_eof(self):
1685 # __exit__() must write end-of-archive blocks, i.e. call
1686 # TarFile.close() if there was no error.
1687 with tarfile.open(tmpname, "w"):
1688 pass
1689 self.assertNotEqual(os.path.getsize(tmpname), 0,
1690 "context manager wrote no end-of-archive block")
1691
1692 def test_fileobj(self):
1693 # Test that __exit__() did not close the external file
1694 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001695 with open(tmpname, "wb") as fobj:
1696 try:
1697 with tarfile.open(fileobj=fobj, mode="w") as tar:
1698 raise Exception
1699 except:
1700 pass
1701 self.assertFalse(fobj.closed, "external file object was closed")
1702 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00001703
1704
Lars Gustäbel1b512722010-06-03 12:45:16 +00001705class LinkEmulationTest(ReadTest):
1706
1707 # Test for issue #8741 regression. On platforms that do not support
1708 # symbolic or hard links tarfile tries to extract these types of members as
1709 # the regular files they point to.
1710 def _test_link_extraction(self, name):
1711 self.tar.extract(name, TEMPDIR)
1712 data = open(os.path.join(TEMPDIR, name), "rb").read()
1713 self.assertEqual(md5sum(data), md5_regtype)
1714
Brian Curtind40e6f72010-07-08 21:39:08 +00001715 # When 8879 gets fixed, this will need to change. Currently on Windows
1716 # we have os.path.islink but no os.link, so these tests fail without the
1717 # following skip until link is completed.
1718 @unittest.skipIf(hasattr(os.path, "islink"),
1719 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001720 def test_hardlink_extraction1(self):
1721 self._test_link_extraction("ustar/lnktype")
1722
Brian Curtind40e6f72010-07-08 21:39:08 +00001723 @unittest.skipIf(hasattr(os.path, "islink"),
1724 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001725 def test_hardlink_extraction2(self):
1726 self._test_link_extraction("./ustar/linktest2/lnktype")
1727
Brian Curtin74e45612010-07-09 15:58:59 +00001728 @unittest.skipIf(hasattr(os, "symlink"),
1729 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001730 def test_symlink_extraction1(self):
1731 self._test_link_extraction("ustar/symtype")
1732
Brian Curtin74e45612010-07-09 15:58:59 +00001733 @unittest.skipIf(hasattr(os, "symlink"),
1734 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001735 def test_symlink_extraction2(self):
1736 self._test_link_extraction("./ustar/linktest2/symtype")
1737
1738
Guido van Rossumd8faa362007-04-27 19:54:29 +00001739class GzipMiscReadTest(MiscReadTest):
1740 tarname = gzipname
1741 mode = "r:gz"
Georg Brandl3abb3722011-08-13 11:48:12 +02001742
1743 def test_non_existent_targz_file(self):
1744 # Test for issue11513: prevent non-existent gzipped tarfiles raising
1745 # multiple exceptions.
1746 with self.assertRaisesRegex(IOError, "xxx") as ex:
1747 tarfile.open("xxx", self.mode)
1748 self.assertEqual(ex.exception.errno, errno.ENOENT)
1749
Guido van Rossumd8faa362007-04-27 19:54:29 +00001750class GzipUstarReadTest(UstarReadTest):
1751 tarname = gzipname
1752 mode = "r:gz"
1753class GzipStreamReadTest(StreamReadTest):
1754 tarname = gzipname
1755 mode = "r|gz"
1756class GzipWriteTest(WriteTest):
1757 mode = "w:gz"
1758class GzipStreamWriteTest(StreamWriteTest):
1759 mode = "w|gz"
1760
1761
1762class Bz2MiscReadTest(MiscReadTest):
1763 tarname = bz2name
1764 mode = "r:bz2"
1765class Bz2UstarReadTest(UstarReadTest):
1766 tarname = bz2name
1767 mode = "r:bz2"
1768class Bz2StreamReadTest(StreamReadTest):
1769 tarname = bz2name
1770 mode = "r|bz2"
1771class Bz2WriteTest(WriteTest):
1772 mode = "w:bz2"
1773class Bz2StreamWriteTest(StreamWriteTest):
1774 mode = "w|bz2"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001775
Lars Gustäbel42e00912009-03-22 20:34:29 +00001776class Bz2PartialReadTest(unittest.TestCase):
1777 # Issue5068: The _BZ2Proxy.read() method loops forever
1778 # on an empty or partial bzipped file.
1779
1780 def _test_partial_input(self, mode):
1781 class MyBytesIO(io.BytesIO):
1782 hit_eof = False
1783 def read(self, n):
1784 if self.hit_eof:
1785 raise AssertionError("infinite loop detected in tarfile.open()")
1786 self.hit_eof = self.tell() == len(self.getvalue())
1787 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001788 def seek(self, *args):
1789 self.hit_eof = False
1790 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00001791
1792 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1793 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001794 try:
1795 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
1796 except tarfile.ReadError:
1797 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00001798
1799 def test_partial_input(self):
1800 self._test_partial_input("r")
1801
1802 def test_partial_input_bz2(self):
1803 self._test_partial_input("r:bz2")
1804
1805
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001806class LzmaMiscReadTest(MiscReadTest):
1807 tarname = xzname
1808 mode = "r:xz"
1809class LzmaUstarReadTest(UstarReadTest):
1810 tarname = xzname
1811 mode = "r:xz"
1812class LzmaStreamReadTest(StreamReadTest):
1813 tarname = xzname
1814 mode = "r|xz"
1815class LzmaWriteTest(WriteTest):
1816 mode = "w:xz"
1817class LzmaStreamWriteTest(StreamWriteTest):
1818 mode = "w|xz"
1819
1820
Neal Norwitz996acf12003-02-17 14:51:41 +00001821def test_main():
Antoine Pitrou95f55602010-09-23 18:36:46 +00001822 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00001823 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001824
Walter Dörwald21d3a322003-05-01 17:45:56 +00001825 tests = [
Guido van Rossumd8faa362007-04-27 19:54:29 +00001826 UstarReadTest,
1827 MiscReadTest,
1828 StreamReadTest,
1829 DetectReadTest,
1830 MemberReadTest,
1831 GNUReadTest,
1832 PaxReadTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001833 WriteTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001834 StreamWriteTest,
1835 GNUWriteTest,
1836 PaxWriteTest,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001837 UstarUnicodeTest,
1838 GNUUnicodeTest,
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001839 PAXUnicodeTest,
Thomas Wouterscf297e42007-02-23 15:07:44 +00001840 AppendTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001841 LimitsTest,
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001842 MiscTest,
Lars Gustäbel01385812010-03-03 12:08:54 +00001843 ContextManagerTest,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001844 ]
1845
Neal Norwitza4f651a2004-07-20 22:07:44 +00001846 if hasattr(os, "link"):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001847 tests.append(HardlinkTest)
Lars Gustäbel1b512722010-06-03 12:45:16 +00001848 else:
1849 tests.append(LinkEmulationTest)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001850
Antoine Pitrou95f55602010-09-23 18:36:46 +00001851 with open(tarname, "rb") as fobj:
1852 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001853
Walter Dörwald21d3a322003-05-01 17:45:56 +00001854 if gzip:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001855 # Create testtar.tar.gz and add gzip-specific tests.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001856 support.unlink(gzipname)
1857 with gzip.open(gzipname, "wb") as tar:
1858 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001859
1860 tests += [
1861 GzipMiscReadTest,
1862 GzipUstarReadTest,
1863 GzipStreamReadTest,
1864 GzipWriteTest,
1865 GzipStreamWriteTest,
1866 ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00001867
1868 if bz2:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001869 # Create testtar.tar.bz2 and add bz2-specific tests.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001870 support.unlink(bz2name)
Lars Gustäbeled1ac582011-12-06 12:56:38 +01001871 with bz2.BZ2File(bz2name, "wb") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001872 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001873
1874 tests += [
1875 Bz2MiscReadTest,
1876 Bz2UstarReadTest,
1877 Bz2StreamReadTest,
1878 Bz2WriteTest,
1879 Bz2StreamWriteTest,
Lars Gustäbel42e00912009-03-22 20:34:29 +00001880 Bz2PartialReadTest,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001881 ]
1882
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001883 if lzma:
1884 # Create testtar.tar.xz and add lzma-specific tests.
1885 support.unlink(xzname)
1886 with lzma.LZMAFile(xzname, "w") as tar:
1887 tar.write(data)
1888
1889 tests += [
1890 LzmaMiscReadTest,
1891 LzmaUstarReadTest,
1892 LzmaStreamReadTest,
1893 LzmaWriteTest,
1894 LzmaStreamWriteTest,
1895 ]
1896
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001897 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001898 support.run_unittest(*tests)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001899 finally:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001900 if os.path.exists(TEMPDIR):
1901 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001902
Neal Norwitz996acf12003-02-17 14:51:41 +00001903if __name__ == "__main__":
1904 test_main()