blob: 238175ff3c1c5bab6fc9598e9ce24869d5e697c5 [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 Rossuma8add0e2007-05-14 22:03:55 +00005from hashlib import md5
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00006
7import unittest
8import tarfile
9
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000011
12# Check for our compression modules.
13try:
14 import gzip
Serhiy Storchaka8b562922013-06-17 15:38:50 +030015except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000016 gzip = None
17try:
18 import bz2
19except ImportError:
20 bz2 = None
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010021try:
22 import lzma
23except ImportError:
24 lzma = None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000025
Guido van Rossumd8faa362007-04-27 19:54:29 +000026def md5sum(data):
Guido van Rossuma8add0e2007-05-14 22:03:55 +000027 return md5(data).hexdigest()
Guido van Rossumd8faa362007-04-27 19:54:29 +000028
Antoine Pitrouab58b5f2010-09-23 19:39:35 +000029TEMPDIR = os.path.abspath(support.TESTFN) + "-tardir"
Antoine Pitrou941ee882009-11-11 20:59:38 +000030tarname = support.findfile("testtar.tar")
Guido van Rossumd8faa362007-04-27 19:54:29 +000031gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
32bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010033xzname = os.path.join(TEMPDIR, "testtar.tar.xz")
Guido van Rossumd8faa362007-04-27 19:54:29 +000034tmpname = os.path.join(TEMPDIR, "tmp.tar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000035
Guido van Rossumd8faa362007-04-27 19:54:29 +000036md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
37md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000038
39
Serhiy Storchaka8b562922013-06-17 15:38:50 +030040class TarTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +000041 tarname = tarname
Serhiy Storchaka8b562922013-06-17 15:38:50 +030042 suffix = ''
43 open = io.FileIO
44
45 @property
46 def mode(self):
47 return self.prefix + self.suffix
48
49@support.requires_gzip
50class GzipTest:
51 tarname = gzipname
52 suffix = 'gz'
53 open = gzip.GzipFile if gzip else None
54
55@support.requires_bz2
56class Bz2Test:
57 tarname = bz2name
58 suffix = 'bz2'
59 open = bz2.BZ2File if bz2 else None
60
61@support.requires_lzma
62class LzmaTest:
63 tarname = xzname
64 suffix = 'xz'
65 open = lzma.LZMAFile if lzma else None
66
67
68class ReadTest(TarTest):
69
70 prefix = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000071
72 def setUp(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +030073 self.tar = tarfile.open(self.tarname, mode=self.mode,
74 encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000075
76 def tearDown(self):
77 self.tar.close()
78
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000079
Serhiy Storchaka8b562922013-06-17 15:38:50 +030080class UstarReadTest(ReadTest, unittest.TestCase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000081
Guido van Rossumd8faa362007-04-27 19:54:29 +000082 def test_fileobj_regular_file(self):
83 tarinfo = self.tar.getmember("ustar/regtype")
Lars Gustäbel7a919e92012-05-05 18:15:03 +020084 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000085 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +030086 self.assertEqual(len(data), tarinfo.size,
87 "regular file extraction failed")
88 self.assertEqual(md5sum(data), md5_regtype,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000089 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000090
Guido van Rossumd8faa362007-04-27 19:54:29 +000091 def test_fileobj_readlines(self):
92 self.tar.extract("ustar/regtype", TEMPDIR)
93 tarinfo = self.tar.getmember("ustar/regtype")
Antoine Pitrou95f55602010-09-23 18:36:46 +000094 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
95 lines1 = fobj1.readlines()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000096
Lars Gustäbel7a919e92012-05-05 18:15:03 +020097 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000098 fobj2 = io.TextIOWrapper(fobj)
99 lines2 = fobj2.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300100 self.assertEqual(lines1, lines2,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000101 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300102 self.assertEqual(len(lines2), 114,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000103 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300104 self.assertEqual(lines2[83],
105 "I will gladly admit that Python is not the fastest "
106 "running scripting language.\n",
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000107 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000108
Guido van Rossumd8faa362007-04-27 19:54:29 +0000109 def test_fileobj_iter(self):
110 self.tar.extract("ustar/regtype", TEMPDIR)
111 tarinfo = self.tar.getmember("ustar/regtype")
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200112 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000113 lines1 = fobj1.readlines()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200114 with self.tar.extractfile(tarinfo) as fobj2:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000115 lines2 = list(io.TextIOWrapper(fobj2))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300116 self.assertEqual(lines1, lines2,
117 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +0000118
Guido van Rossumd8faa362007-04-27 19:54:29 +0000119 def test_fileobj_seek(self):
120 self.tar.extract("ustar/regtype", TEMPDIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000121 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
122 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +0000123
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124 tarinfo = self.tar.getmember("ustar/regtype")
125 fobj = self.tar.extractfile(tarinfo)
126
127 text = fobj.read()
128 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000129 self.assertEqual(0, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130 "seek() to file's start failed")
131 fobj.seek(2048, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000132 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000133 "seek() to absolute position failed")
134 fobj.seek(-1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000135 self.assertEqual(1024, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000136 "seek() to negative relative position failed")
137 fobj.seek(1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000138 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000139 "seek() to positive relative position failed")
140 s = fobj.read(10)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300141 self.assertEqual(s, data[2048:2058],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000142 "read() after seek failed")
143 fobj.seek(0, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000144 self.assertEqual(tarinfo.size, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000145 "seek() to file's end failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300146 self.assertEqual(fobj.read(), b"",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147 "read() at file's end did not return empty string")
148 fobj.seek(-tarinfo.size, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000149 self.assertEqual(0, fobj.tell(),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000150 "relative seek() to file's end failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000151 fobj.seek(512)
152 s1 = fobj.readlines()
153 fobj.seek(512)
154 s2 = fobj.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300155 self.assertEqual(s1, s2,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156 "readlines() after seek failed")
157 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000158 self.assertEqual(len(fobj.readline()), fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000159 "tell() after readline() failed")
160 fobj.seek(512)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300161 self.assertEqual(len(fobj.readline()) + 512, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000162 "tell() after seek() and readline() failed")
163 fobj.seek(0)
164 line = fobj.readline()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000165 self.assertEqual(fobj.read(), data[len(line):],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000166 "read() after readline() failed")
167 fobj.close()
168
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200169 def test_fileobj_text(self):
170 with self.tar.extractfile("ustar/regtype") as fobj:
171 fobj = io.TextIOWrapper(fobj)
172 data = fobj.read().encode("iso8859-1")
173 self.assertEqual(md5sum(data), md5_regtype)
174 try:
175 fobj.seek(100)
176 except AttributeError:
177 # Issue #13815: seek() complained about a missing
178 # flush() method.
179 self.fail("seeking failed in text mode")
180
Lars Gustäbel1b512722010-06-03 12:45:16 +0000181 # Test if symbolic and hard links are resolved by extractfile(). The
182 # test link members each point to a regular member whose data is
183 # supposed to be exported.
184 def _test_fileobj_link(self, lnktype, regtype):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300185 with self.tar.extractfile(lnktype) as a, \
186 self.tar.extractfile(regtype) as b:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000187 self.assertEqual(a.name, b.name)
Lars Gustäbel1b512722010-06-03 12:45:16 +0000188
189 def test_fileobj_link1(self):
190 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
191
192 def test_fileobj_link2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300193 self._test_fileobj_link("./ustar/linktest2/lnktype",
194 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000195
196 def test_fileobj_symlink1(self):
197 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
198
199 def test_fileobj_symlink2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300200 self._test_fileobj_link("./ustar/linktest2/symtype",
201 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000202
Lars Gustäbel1ef9eda2012-04-24 21:04:40 +0200203 def test_issue14160(self):
204 self._test_fileobj_link("symtype2", "ustar/regtype")
205
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300206class GzipUstarReadTest(GzipTest, UstarReadTest):
207 pass
208
209class Bz2UstarReadTest(Bz2Test, UstarReadTest):
210 pass
211
212class LzmaUstarReadTest(LzmaTest, UstarReadTest):
213 pass
214
Guido van Rossumd8faa362007-04-27 19:54:29 +0000215
Lars Gustäbel9520a432009-11-22 18:48:49 +0000216class CommonReadTest(ReadTest):
217
218 def test_empty_tarfile(self):
219 # Test for issue6123: Allow opening empty archives.
220 # This test checks if tarfile.open() is able to open an empty tar
221 # archive successfully. Note that an empty tar archive is not the
222 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000223 with tarfile.open(tmpname, self.mode.replace("r", "w")):
224 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000225 try:
226 tar = tarfile.open(tmpname, self.mode)
227 tar.getnames()
228 except tarfile.ReadError:
229 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000230 else:
231 self.assertListEqual(tar.getmembers(), [])
232 finally:
233 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000234
235 def test_null_tarfile(self):
236 # Test for issue6123: Allow opening empty archives.
237 # This test guarantees that tarfile.open() does not treat an empty
238 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000239 with open(tmpname, "wb"):
240 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000241 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
242 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
243
244 def test_ignore_zeros(self):
245 # Test TarFile's ignore_zeros option.
Lars Gustäbel9520a432009-11-22 18:48:49 +0000246 for char in (b'\0', b'a'):
247 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
248 # are ignored correctly.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300249 with self.open(tmpname, "w") as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000250 fobj.write(char * 1024)
251 fobj.write(tarfile.TarInfo("foo").tobuf())
Lars Gustäbel9520a432009-11-22 18:48:49 +0000252
253 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000254 try:
255 self.assertListEqual(tar.getnames(), ["foo"],
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300256 "ignore_zeros=True should have skipped the %r-blocks" %
257 char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000258 finally:
259 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000260
261
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300262class MiscReadTestBase(CommonReadTest):
Thomas Woutersed03b412007-08-28 21:37:11 +0000263 def test_no_name_argument(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000264 with open(self.tarname, "rb") as fobj:
265 tar = tarfile.open(fileobj=fobj, mode=self.mode)
266 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000267
Thomas Woutersed03b412007-08-28 21:37:11 +0000268 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000269 with open(self.tarname, "rb") as fobj:
270 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000271 fobj = io.BytesIO(data)
272 self.assertRaises(AttributeError, getattr, fobj, "name")
273 tar = tarfile.open(fileobj=fobj, mode=self.mode)
274 self.assertEqual(tar.name, None)
275
276 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000277 with open(self.tarname, "rb") as fobj:
278 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000279 fobj = io.BytesIO(data)
280 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000281 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
282 self.assertEqual(tar.name, None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000283
Christian Heimesd8654cf2007-12-02 15:22:16 +0000284 def test_fileobj_with_offset(self):
285 # Skip the first member and store values from the second member
286 # of the testtar.
287 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000288 try:
289 tar.next()
290 t = tar.next()
291 name = t.name
292 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200293 with tar.extractfile(t) as f:
294 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000295 finally:
296 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000297
298 # Open the testtar and seek to the offset of the second member.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300299 with self.open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000300 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000301
Antoine Pitrou95f55602010-09-23 18:36:46 +0000302 # Test if the tarfile starts with the second member.
303 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
304 t = tar.next()
305 self.assertEqual(t.name, name)
306 # Read to the end of fileobj and test if seeking back to the
307 # beginning works.
308 tar.getmembers()
309 self.assertEqual(tar.extractfile(t).read(), data,
310 "seek back did not work")
311 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000312
Guido van Rossumd8faa362007-04-27 19:54:29 +0000313 def test_fail_comp(self):
314 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000315 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000316 with open(tarname, "rb") as fobj:
317 self.assertRaises(tarfile.ReadError, tarfile.open,
318 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000319
320 def test_v7_dirtype(self):
321 # Test old style dirtype member (bug #1336623):
322 # Old V7 tars create directory members using an AREGTYPE
323 # header with a "/" appended to the filename field.
324 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300325 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000326 "v7 dirtype failed")
327
Christian Heimes126d29a2008-02-11 22:57:17 +0000328 def test_xstar_type(self):
329 # The xstar format stores extra atime and ctime fields inside the
330 # space reserved for the prefix field. The prefix field must be
331 # ignored in this case, otherwise it will mess up the name.
332 try:
333 self.tar.getmember("misc/regtype-xstar")
334 except KeyError:
335 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
336
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337 def test_check_members(self):
338 for tarinfo in self.tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300339 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000340 "wrong mtime for %s" % tarinfo.name)
341 if not tarinfo.name.startswith("ustar/"):
342 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300343 self.assertEqual(tarinfo.uname, "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000344 "wrong uname for %s" % tarinfo.name)
345
346 def test_find_members(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300347 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000348 "could not find all members")
349
Brian Curtin74e45612010-07-09 15:58:59 +0000350 @unittest.skipUnless(hasattr(os, "link"),
351 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000352 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000353 def test_extract_hardlink(self):
354 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200355 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000356 tar.extract("ustar/regtype", TEMPDIR)
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200357 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000358
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200359 tar.extract("ustar/lnktype", TEMPDIR)
360 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000361 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
362 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000363 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000364
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200365 tar.extract("ustar/symtype", TEMPDIR)
366 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000367 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
368 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000369 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000370
Christian Heimesfaf2f632008-01-06 16:59:19 +0000371 def test_extractall(self):
372 # Test if extractall() correctly restores directory permissions
373 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000374 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000375 DIR = os.path.join(TEMPDIR, "extractall")
376 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000377 try:
378 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000379 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000380 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000381 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000382 if sys.platform != "win32":
383 # Win32 has no support for fine grained permissions.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300384 self.assertEqual(tarinfo.mode & 0o777,
385 os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000386 def format_mtime(mtime):
387 if isinstance(mtime, float):
388 return "{} ({})".format(mtime, mtime.hex())
389 else:
390 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000391 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000392 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
393 format_mtime(tarinfo.mtime),
394 format_mtime(file_mtime),
395 path)
396 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000397 finally:
398 tar.close()
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000399 shutil.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000400
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000401 def test_extract_directory(self):
402 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000403 DIR = os.path.join(TEMPDIR, "extractdir")
404 os.mkdir(DIR)
405 try:
406 with tarfile.open(tarname, encoding="iso8859-1") as tar:
407 tarinfo = tar.getmember(dirtype)
408 tar.extract(tarinfo, path=DIR)
409 extracted = os.path.join(DIR, dirtype)
410 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
411 if sys.platform != "win32":
412 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
413 finally:
414 shutil.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000415
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000416 def test_init_close_fobj(self):
417 # Issue #7341: Close the internal file object in the TarFile
418 # constructor in case of an error. For the test we rely on
419 # the fact that opening an empty file raises a ReadError.
420 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000421 with open(empty, "wb") as fobj:
422 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000423
424 try:
425 tar = object.__new__(tarfile.TarFile)
426 try:
427 tar.__init__(empty)
428 except tarfile.ReadError:
429 self.assertTrue(tar.fileobj.closed)
430 else:
431 self.fail("ReadError not raised")
432 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000433 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000434
Serhiy Storchaka263fab92013-05-09 14:22:26 +0300435 def test_parallel_iteration(self):
436 # Issue #16601: Restarting iteration over tarfile continued
437 # from where it left off.
438 with tarfile.open(self.tarname) as tar:
439 for m1, m2 in zip(tar, tar):
440 self.assertEqual(m1.offset, m2.offset)
441 self.assertEqual(m1.get_info(), m2.get_info())
442
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300443class MiscReadTest(MiscReadTestBase, unittest.TestCase):
444 test_fail_comp = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000445
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300446class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
447 def test_non_existent_targz_file(self):
448 # Test for issue11513: prevent non-existent gzipped tarfiles raising
449 # multiple exceptions.
450 with self.assertRaisesRegex(FileNotFoundError, "xxx"):
451 tarfile.open("xxx", self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000452
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300453class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
454 def test_no_name_argument(self):
455 self.skipTest("BZ2File have no name attribute")
456
457class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
458 def test_no_name_argument(self):
459 self.skipTest("LZMAFile have no name attribute")
460
461
462class StreamReadTest(CommonReadTest, unittest.TestCase):
463
464 prefix="r|"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000465
Lars Gustäbeldd071042011-02-23 11:42:22 +0000466 def test_read_through(self):
467 # Issue #11224: A poorly designed _FileInFile.read() method
468 # caused seeking errors with stream tar files.
469 for tarinfo in self.tar:
470 if not tarinfo.isreg():
471 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200472 with self.tar.extractfile(tarinfo) as fobj:
473 while True:
474 try:
475 buf = fobj.read(512)
476 except tarfile.StreamError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300477 self.fail("simple read-through using "
478 "TarFile.extractfile() failed")
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200479 if not buf:
480 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000481
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482 def test_fileobj_regular_file(self):
483 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200484 with self.tar.extractfile(tarinfo) as fobj:
485 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300486 self.assertEqual(len(data), tarinfo.size,
487 "regular file extraction failed")
488 self.assertEqual(md5sum(data), md5_regtype,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000489 "regular file extraction failed")
490
491 def test_provoke_stream_error(self):
492 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200493 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
494 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000495
Guido van Rossumd8faa362007-04-27 19:54:29 +0000496 def test_compare_members(self):
497 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000498 try:
499 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000500
Antoine Pitrou95f55602010-09-23 18:36:46 +0000501 while True:
502 t1 = tar1.next()
503 t2 = tar2.next()
504 if t1 is None:
505 break
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300506 self.assertIsNotNone(t2, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000507
Antoine Pitrou95f55602010-09-23 18:36:46 +0000508 if t2.islnk() or t2.issym():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300509 with self.assertRaises(tarfile.StreamError):
510 tar2.extractfile(t2)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000511 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000512
Antoine Pitrou95f55602010-09-23 18:36:46 +0000513 v1 = tar1.extractfile(t1)
514 v2 = tar2.extractfile(t2)
515 if v1 is None:
516 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300517 self.assertIsNotNone(v2, "stream.extractfile() failed")
518 self.assertEqual(v1.read(), v2.read(),
519 "stream extraction failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000520 finally:
521 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000522
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300523class GzipStreamReadTest(GzipTest, StreamReadTest):
524 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000525
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300526class Bz2StreamReadTest(Bz2Test, StreamReadTest):
527 pass
Thomas Wouterscf297e42007-02-23 15:07:44 +0000528
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300529class LzmaStreamReadTest(LzmaTest, StreamReadTest):
530 pass
531
532
533class DetectReadTest(TarTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000534 def _testfunc_file(self, name, mode):
535 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000536 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000537 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000538 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000539 else:
540 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000541
Guido van Rossumd8faa362007-04-27 19:54:29 +0000542 def _testfunc_fileobj(self, name, mode):
543 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000544 with open(name, "rb") as f:
545 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000546 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000547 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000548 else:
549 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000550
551 def _test_modes(self, testfunc):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300552 if self.suffix:
553 with self.assertRaises(tarfile.ReadError):
554 tarfile.open(tarname, mode="r:" + self.suffix)
555 with self.assertRaises(tarfile.ReadError):
556 tarfile.open(tarname, mode="r|" + self.suffix)
557 with self.assertRaises(tarfile.ReadError):
558 tarfile.open(self.tarname, mode="r:")
559 with self.assertRaises(tarfile.ReadError):
560 tarfile.open(self.tarname, mode="r|")
561 testfunc(self.tarname, "r")
562 testfunc(self.tarname, "r:" + self.suffix)
563 testfunc(self.tarname, "r:*")
564 testfunc(self.tarname, "r|" + self.suffix)
565 testfunc(self.tarname, "r|*")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100566
Guido van Rossumd8faa362007-04-27 19:54:29 +0000567 def test_detect_file(self):
568 self._test_modes(self._testfunc_file)
569
570 def test_detect_fileobj(self):
571 self._test_modes(self._testfunc_fileobj)
572
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300573class GzipDetectReadTest(GzipTest, DetectReadTest):
574 pass
575
576class Bz2DetectReadTest(Bz2Test, DetectReadTest):
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100577 def test_detect_stream_bz2(self):
578 # Originally, tarfile's stream detection looked for the string
579 # "BZh91" at the start of the file. This is incorrect because
580 # the '9' represents the blocksize (900kB). If the file was
581 # compressed using another blocksize autodetection fails.
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100582 with open(tarname, "rb") as fobj:
583 data = fobj.read()
584
585 # Compress with blocksize 100kB, the file starts with "BZh11".
586 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
587 fobj.write(data)
588
589 self._testfunc_file(tmpname, "r|*")
590
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300591class LzmaDetectReadTest(LzmaTest, DetectReadTest):
592 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000593
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300594
595class MemberReadTest(ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000596
597 def _test_member(self, tarinfo, chksum=None, **kwargs):
598 if chksum is not None:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300599 with self.tar.extractfile(tarinfo) as f:
600 self.assertEqual(md5sum(f.read()), chksum,
601 "wrong md5sum for %s" % tarinfo.name)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000602
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000603 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000604 kwargs["uid"] = 1000
605 kwargs["gid"] = 100
606 if "old-v7" not in tarinfo.name:
607 # V7 tar can't handle alphabetic owners.
608 kwargs["uname"] = "tarfile"
609 kwargs["gname"] = "tarfile"
610 for k, v in kwargs.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300611 self.assertEqual(getattr(tarinfo, k), v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000612 "wrong value in %s field of %s" % (k, tarinfo.name))
613
614 def test_find_regtype(self):
615 tarinfo = self.tar.getmember("ustar/regtype")
616 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
617
618 def test_find_conttype(self):
619 tarinfo = self.tar.getmember("ustar/conttype")
620 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
621
622 def test_find_dirtype(self):
623 tarinfo = self.tar.getmember("ustar/dirtype")
624 self._test_member(tarinfo, size=0)
625
626 def test_find_dirtype_with_size(self):
627 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
628 self._test_member(tarinfo, size=255)
629
630 def test_find_lnktype(self):
631 tarinfo = self.tar.getmember("ustar/lnktype")
632 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
633
634 def test_find_symtype(self):
635 tarinfo = self.tar.getmember("ustar/symtype")
636 self._test_member(tarinfo, size=0, linkname="regtype")
637
638 def test_find_blktype(self):
639 tarinfo = self.tar.getmember("ustar/blktype")
640 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
641
642 def test_find_chrtype(self):
643 tarinfo = self.tar.getmember("ustar/chrtype")
644 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
645
646 def test_find_fifotype(self):
647 tarinfo = self.tar.getmember("ustar/fifotype")
648 self._test_member(tarinfo, size=0)
649
650 def test_find_sparse(self):
651 tarinfo = self.tar.getmember("ustar/sparse")
652 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
653
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000654 def test_find_gnusparse(self):
655 tarinfo = self.tar.getmember("gnu/sparse")
656 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
657
658 def test_find_gnusparse_00(self):
659 tarinfo = self.tar.getmember("gnu/sparse-0.0")
660 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
661
662 def test_find_gnusparse_01(self):
663 tarinfo = self.tar.getmember("gnu/sparse-0.1")
664 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
665
666 def test_find_gnusparse_10(self):
667 tarinfo = self.tar.getmember("gnu/sparse-1.0")
668 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
669
Guido van Rossumd8faa362007-04-27 19:54:29 +0000670 def test_find_umlauts(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300671 tarinfo = self.tar.getmember("ustar/umlauts-"
672 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000673 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
674
675 def test_find_ustar_longname(self):
676 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000677 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000678
679 def test_find_regtype_oldv7(self):
680 tarinfo = self.tar.getmember("misc/regtype-old-v7")
681 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
682
683 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000684 self.tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300685 self.tar = tarfile.open(self.tarname, mode=self.mode,
686 encoding="iso8859-1")
687 tarinfo = self.tar.getmember("pax/umlauts-"
688 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000689 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
690
691
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300692class LongnameTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000693
694 def test_read_longname(self):
695 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000696 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000697 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000698 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000699 except KeyError:
700 self.fail("longname not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300701 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
702 "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000703
704 def test_read_longlink(self):
705 longname = self.subdir + "/" + "123/" * 125 + "longname"
706 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
707 try:
708 tarinfo = self.tar.getmember(longlink)
709 except KeyError:
710 self.fail("longlink not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300711 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000712
713 def test_truncated_longname(self):
714 longname = self.subdir + "/" + "123/" * 125 + "longname"
715 tarinfo = self.tar.getmember(longname)
716 offset = tarinfo.offset
717 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000718 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300719 with self.assertRaises(tarfile.ReadError):
720 tarfile.open(name="foo.tar", fileobj=fobj)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000721
Guido van Rossume7ba4952007-06-06 23:52:48 +0000722 def test_header_offset(self):
723 # Test if the start offset of the TarInfo object includes
724 # the preceding extended header.
725 longname = self.subdir + "/" + "123/" * 125 + "longname"
726 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000727 with open(tarname, "rb") as fobj:
728 fobj.seek(offset)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300729 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
730 "iso8859-1", "strict")
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000731 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000732
Guido van Rossumd8faa362007-04-27 19:54:29 +0000733
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300734class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000735
736 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000737 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000738
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000739 # Since 3.2 tarfile is supposed to accurately restore sparse members and
740 # produce files with holes. This is what we actually want to test here.
741 # Unfortunately, not all platforms/filesystems support sparse files, and
742 # even on platforms that do it is non-trivial to make reliable assertions
743 # about holes in files. Therefore, we first do one basic test which works
744 # an all platforms, and after that a test that will work only on
745 # platforms/filesystems that prove to support sparse files.
746 def _test_sparse_file(self, name):
747 self.tar.extract(name, TEMPDIR)
748 filename = os.path.join(TEMPDIR, name)
749 with open(filename, "rb") as fobj:
750 data = fobj.read()
751 self.assertEqual(md5sum(data), md5_sparse,
752 "wrong md5sum for %s" % name)
753
754 if self._fs_supports_holes():
755 s = os.stat(filename)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300756 self.assertLess(s.st_blocks * 512, s.st_size)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000757
758 def test_sparse_file_old(self):
759 self._test_sparse_file("gnu/sparse")
760
761 def test_sparse_file_00(self):
762 self._test_sparse_file("gnu/sparse-0.0")
763
764 def test_sparse_file_01(self):
765 self._test_sparse_file("gnu/sparse-0.1")
766
767 def test_sparse_file_10(self):
768 self._test_sparse_file("gnu/sparse-1.0")
769
770 @staticmethod
771 def _fs_supports_holes():
772 # Return True if the platform knows the st_blocks stat attribute and
773 # uses st_blocks units of 512 bytes, and if the filesystem is able to
774 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200775 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000776 # Linux evidentially has 512 byte st_blocks units.
777 name = os.path.join(TEMPDIR, "sparse-test")
778 with open(name, "wb") as fobj:
779 fobj.seek(4096)
780 fobj.truncate()
781 s = os.stat(name)
782 os.remove(name)
783 return s.st_blocks == 0
784 else:
785 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000786
787
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300788class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000789
790 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000791 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000792
Guido van Rossume7ba4952007-06-06 23:52:48 +0000793 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000794 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000795 try:
796 tarinfo = tar.getmember("pax/regtype1")
797 self.assertEqual(tarinfo.uname, "foo")
798 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300799 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
800 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000801
Antoine Pitrou95f55602010-09-23 18:36:46 +0000802 tarinfo = tar.getmember("pax/regtype2")
803 self.assertEqual(tarinfo.uname, "")
804 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300805 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
806 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000807
Antoine Pitrou95f55602010-09-23 18:36:46 +0000808 tarinfo = tar.getmember("pax/regtype3")
809 self.assertEqual(tarinfo.uname, "tarfile")
810 self.assertEqual(tarinfo.gname, "tarfile")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300811 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
812 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000813 finally:
814 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000815
816 def test_pax_number_fields(self):
817 # All following number fields are read from the pax header.
818 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000819 try:
820 tarinfo = tar.getmember("pax/regtype4")
821 self.assertEqual(tarinfo.size, 7011)
822 self.assertEqual(tarinfo.uid, 123)
823 self.assertEqual(tarinfo.gid, 123)
824 self.assertEqual(tarinfo.mtime, 1041808783.0)
825 self.assertEqual(type(tarinfo.mtime), float)
826 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
827 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
828 finally:
829 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000830
831
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300832class WriteTestBase(TarTest):
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000833 # Put all write tests in here that are supposed to be tested
834 # in all possible mode combinations.
835
836 def test_fileobj_no_close(self):
837 fobj = io.BytesIO()
838 tar = tarfile.open(fileobj=fobj, mode=self.mode)
839 tar.addfile(tarfile.TarInfo("foo"))
840 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300841 self.assertFalse(fobj.closed, "external fileobjs must never closed")
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000842
843
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300844class WriteTest(WriteTestBase, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000845
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300846 prefix = "w:"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000847
848 def test_100_char_name(self):
849 # The name field in a tar header stores strings of at most 100 chars.
850 # If a string is shorter than 100 chars it has to be padded with '\0',
851 # which implies that a string of exactly 100 chars is stored without
852 # a trailing '\0'.
853 name = "0123456789" * 10
854 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000855 try:
856 t = tarfile.TarInfo(name)
857 tar.addfile(t)
858 finally:
859 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000860
Guido van Rossumd8faa362007-04-27 19:54:29 +0000861 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000862 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300863 self.assertEqual(tar.getnames()[0], name,
Antoine Pitrou95f55602010-09-23 18:36:46 +0000864 "failed to store 100 char filename")
865 finally:
866 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000867
Guido van Rossumd8faa362007-04-27 19:54:29 +0000868 def test_tar_size(self):
869 # Test for bug #1013882.
870 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000871 try:
872 path = os.path.join(TEMPDIR, "file")
873 with open(path, "wb") as fobj:
874 fobj.write(b"aaa")
875 tar.add(path)
876 finally:
877 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300878 self.assertGreater(os.path.getsize(tmpname), 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000879 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000880
Guido van Rossumd8faa362007-04-27 19:54:29 +0000881 # The test_*_size tests test for bug #1167128.
882 def test_file_size(self):
883 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000884 try:
885 path = os.path.join(TEMPDIR, "file")
886 with open(path, "wb"):
887 pass
888 tarinfo = tar.gettarinfo(path)
889 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000890
Antoine Pitrou95f55602010-09-23 18:36:46 +0000891 with open(path, "wb") as fobj:
892 fobj.write(b"aaa")
893 tarinfo = tar.gettarinfo(path)
894 self.assertEqual(tarinfo.size, 3)
895 finally:
896 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000897
898 def test_directory_size(self):
899 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000900 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000901 try:
902 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000903 try:
904 tarinfo = tar.gettarinfo(path)
905 self.assertEqual(tarinfo.size, 0)
906 finally:
907 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000908 finally:
909 os.rmdir(path)
910
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300911 @unittest.skipUnless(hasattr(os, "link"),
912 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000913 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300914 link = os.path.join(TEMPDIR, "link")
915 target = os.path.join(TEMPDIR, "link_target")
916 with open(target, "wb") as fobj:
917 fobj.write(b"aaa")
918 os.link(target, link)
919 try:
920 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000921 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300922 # Record the link target in the inodes list.
923 tar.gettarinfo(target)
924 tarinfo = tar.gettarinfo(link)
925 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000926 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300927 tar.close()
928 finally:
929 os.remove(target)
930 os.remove(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000931
Brian Curtin3b4499c2010-12-28 14:31:47 +0000932 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000933 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +0000934 path = os.path.join(TEMPDIR, "symlink")
935 os.symlink("link_target", path)
936 try:
937 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000938 try:
939 tarinfo = tar.gettarinfo(path)
940 self.assertEqual(tarinfo.size, 0)
941 finally:
942 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +0000943 finally:
944 os.remove(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000945
946 def test_add_self(self):
947 # Test for #1257255.
948 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000949 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000950 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300951 self.assertEqual(tar.name, dstname,
952 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000953 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300954 self.assertEqual(tar.getnames(), [],
955 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000956
Antoine Pitrou95f55602010-09-23 18:36:46 +0000957 cwd = os.getcwd()
958 os.chdir(TEMPDIR)
959 tar.add(dstname)
960 os.chdir(cwd)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300961 self.assertEqual(tar.getnames(), [],
962 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000963 finally:
964 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000965
Guido van Rossum486364b2007-06-30 05:01:58 +0000966 def test_exclude(self):
967 tempdir = os.path.join(TEMPDIR, "exclude")
968 os.mkdir(tempdir)
969 try:
970 for name in ("foo", "bar", "baz"):
971 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +0200972 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +0000973
Benjamin Peterson886af962010-03-21 23:13:07 +0000974 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +0000975
976 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000977 try:
978 with support.check_warnings(("use the filter argument",
979 DeprecationWarning)):
980 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
981 finally:
982 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000983
984 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000985 try:
986 self.assertEqual(len(tar.getmembers()), 1)
987 self.assertEqual(tar.getnames()[0], "empty_dir")
988 finally:
989 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +0000990 finally:
991 shutil.rmtree(tempdir)
992
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000993 def test_filter(self):
994 tempdir = os.path.join(TEMPDIR, "filter")
995 os.mkdir(tempdir)
996 try:
997 for name in ("foo", "bar", "baz"):
998 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +0200999 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001000
1001 def filter(tarinfo):
1002 if os.path.basename(tarinfo.name) == "bar":
1003 return
1004 tarinfo.uid = 123
1005 tarinfo.uname = "foo"
1006 return tarinfo
1007
1008 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001009 try:
1010 tar.add(tempdir, arcname="empty_dir", filter=filter)
1011 finally:
1012 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001013
Raymond Hettingera63a3122011-01-26 20:34:14 +00001014 # Verify that filter is a keyword-only argument
1015 with self.assertRaises(TypeError):
1016 tar.add(tempdir, "empty_dir", True, None, filter)
1017
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001018 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001019 try:
1020 for tarinfo in tar:
1021 self.assertEqual(tarinfo.uid, 123)
1022 self.assertEqual(tarinfo.uname, "foo")
1023 self.assertEqual(len(tar.getmembers()), 3)
1024 finally:
1025 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001026 finally:
1027 shutil.rmtree(tempdir)
1028
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001029 # Guarantee that stored pathnames are not modified. Don't
1030 # remove ./ or ../ or double slashes. Still make absolute
1031 # pathnames relative.
1032 # For details see bug #6054.
1033 def _test_pathname(self, path, cmp_path=None, dir=False):
1034 # Create a tarfile with an empty member named path
1035 # and compare the stored name with the original.
1036 foo = os.path.join(TEMPDIR, "foo")
1037 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001038 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001039 else:
1040 os.mkdir(foo)
1041
1042 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001043 try:
1044 tar.add(foo, arcname=path)
1045 finally:
1046 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001047
1048 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001049 try:
1050 t = tar.next()
1051 finally:
1052 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001053
1054 if not dir:
1055 os.remove(foo)
1056 else:
1057 os.rmdir(foo)
1058
1059 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1060
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001061
1062 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001063 def test_extractall_symlinks(self):
1064 # Test if extractall works properly when tarfile contains symlinks
1065 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1066 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1067 os.mkdir(tempdir)
1068 try:
1069 source_file = os.path.join(tempdir,'source')
1070 target_file = os.path.join(tempdir,'symlink')
1071 with open(source_file,'w') as f:
1072 f.write('something\n')
1073 os.symlink(source_file, target_file)
1074 tar = tarfile.open(temparchive,'w')
1075 tar.add(source_file)
1076 tar.add(target_file)
1077 tar.close()
1078 # Let's extract it to the location which contains the symlink
1079 tar = tarfile.open(temparchive,'r')
1080 # this should not raise OSError: [Errno 17] File exists
1081 try:
1082 tar.extractall(path=tempdir)
1083 except OSError:
1084 self.fail("extractall failed with symlinked files")
1085 finally:
1086 tar.close()
1087 finally:
1088 os.unlink(temparchive)
1089 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001090
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001091 def test_pathnames(self):
1092 self._test_pathname("foo")
1093 self._test_pathname(os.path.join("foo", ".", "bar"))
1094 self._test_pathname(os.path.join("foo", "..", "bar"))
1095 self._test_pathname(os.path.join(".", "foo"))
1096 self._test_pathname(os.path.join(".", "foo", "."))
1097 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1098 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1099 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1100 self._test_pathname(os.path.join("..", "foo"))
1101 self._test_pathname(os.path.join("..", "foo", ".."))
1102 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1103 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1104
1105 self._test_pathname("foo" + os.sep + os.sep + "bar")
1106 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1107
1108 def test_abs_pathnames(self):
1109 if sys.platform == "win32":
1110 self._test_pathname("C:\\foo", "foo")
1111 else:
1112 self._test_pathname("/foo", "foo")
1113 self._test_pathname("///foo", "foo")
1114
1115 def test_cwd(self):
1116 # Test adding the current working directory.
1117 cwd = os.getcwd()
1118 os.chdir(TEMPDIR)
1119 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001120 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001121 try:
1122 tar.add(".")
1123 finally:
1124 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001125
1126 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001127 try:
1128 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001129 if t.name != ".":
1130 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001131 finally:
1132 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001133 finally:
1134 os.chdir(cwd)
1135
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001136class GzipWriteTest(GzipTest, WriteTest):
1137 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001138
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001139class Bz2WriteTest(Bz2Test, WriteTest):
1140 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001141
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001142class LzmaWriteTest(LzmaTest, WriteTest):
1143 pass
1144
1145
1146class StreamWriteTest(WriteTestBase, unittest.TestCase):
1147
1148 prefix = "w|"
1149 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001150
Guido van Rossumd8faa362007-04-27 19:54:29 +00001151 def test_stream_padding(self):
1152 # Test for bug #1543303.
1153 tar = tarfile.open(tmpname, self.mode)
1154 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001155 if self.decompressor:
1156 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001157 with open(tmpname, "rb") as fobj:
1158 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001159 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001160 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001161 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001162 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001163 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001164 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1165 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001166
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001167 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1168 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001169 def test_file_mode(self):
1170 # Test for issue #8464: Create files with correct
1171 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001172 if os.path.exists(tmpname):
1173 os.remove(tmpname)
1174
1175 original_umask = os.umask(0o022)
1176 try:
1177 tar = tarfile.open(tmpname, self.mode)
1178 tar.close()
1179 mode = os.stat(tmpname).st_mode & 0o777
1180 self.assertEqual(mode, 0o644, "wrong file permissions")
1181 finally:
1182 os.umask(original_umask)
1183
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001184class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1185 pass
1186
1187class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1188 decompressor = bz2.BZ2Decompressor if bz2 else None
1189
1190class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1191 decompressor = lzma.LZMADecompressor if lzma else None
1192
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001193
Guido van Rossumd8faa362007-04-27 19:54:29 +00001194class GNUWriteTest(unittest.TestCase):
1195 # This testcase checks for correct creation of GNU Longname
1196 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001197
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001198 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001199 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001200 return blocks * 512
1201
1202 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001203 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001204 count = 512
1205
1206 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001207 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001208 count += 512
1209 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001210 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001211 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001212 count += 512
1213 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001214 return count
1215
1216 def _test(self, name, link=None):
1217 tarinfo = tarfile.TarInfo(name)
1218 if link:
1219 tarinfo.linkname = link
1220 tarinfo.type = tarfile.LNKTYPE
1221
Guido van Rossumd8faa362007-04-27 19:54:29 +00001222 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001223 try:
1224 tar.format = tarfile.GNU_FORMAT
1225 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001226
Antoine Pitrou95f55602010-09-23 18:36:46 +00001227 v1 = self._calc_size(name, link)
1228 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001229 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001230 finally:
1231 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001232
Guido van Rossumd8faa362007-04-27 19:54:29 +00001233 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001234 try:
1235 member = tar.next()
1236 self.assertIsNotNone(member,
1237 "unable to read longname member")
1238 self.assertEqual(tarinfo.name, member.name,
1239 "unable to read longname member")
1240 self.assertEqual(tarinfo.linkname, member.linkname,
1241 "unable to read longname member")
1242 finally:
1243 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001244
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001245 def test_longname_1023(self):
1246 self._test(("longnam/" * 127) + "longnam")
1247
1248 def test_longname_1024(self):
1249 self._test(("longnam/" * 127) + "longname")
1250
1251 def test_longname_1025(self):
1252 self._test(("longnam/" * 127) + "longname_")
1253
1254 def test_longlink_1023(self):
1255 self._test("name", ("longlnk/" * 127) + "longlnk")
1256
1257 def test_longlink_1024(self):
1258 self._test("name", ("longlnk/" * 127) + "longlink")
1259
1260 def test_longlink_1025(self):
1261 self._test("name", ("longlnk/" * 127) + "longlink_")
1262
1263 def test_longnamelink_1023(self):
1264 self._test(("longnam/" * 127) + "longnam",
1265 ("longlnk/" * 127) + "longlnk")
1266
1267 def test_longnamelink_1024(self):
1268 self._test(("longnam/" * 127) + "longname",
1269 ("longlnk/" * 127) + "longlink")
1270
1271 def test_longnamelink_1025(self):
1272 self._test(("longnam/" * 127) + "longname_",
1273 ("longlnk/" * 127) + "longlink_")
1274
Guido van Rossumd8faa362007-04-27 19:54:29 +00001275
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001276@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001277class HardlinkTest(unittest.TestCase):
1278 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001279
1280 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001281 self.foo = os.path.join(TEMPDIR, "foo")
1282 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001283
Antoine Pitrou95f55602010-09-23 18:36:46 +00001284 with open(self.foo, "wb") as fobj:
1285 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001286
Guido van Rossumd8faa362007-04-27 19:54:29 +00001287 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001288
Guido van Rossumd8faa362007-04-27 19:54:29 +00001289 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001290 self.tar.add(self.foo)
1291
Guido van Rossumd8faa362007-04-27 19:54:29 +00001292 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001293 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001294 support.unlink(self.foo)
1295 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001296
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001297 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001298 # The same name will be added as a REGTYPE every
1299 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001300 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001301 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001302 "add file as regular failed")
1303
1304 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001305 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001306 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001307 "add file as hardlink failed")
1308
1309 def test_dereference_hardlink(self):
1310 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001311 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001312 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001313 "dereferencing hardlink failed")
1314
Neal Norwitza4f651a2004-07-20 22:07:44 +00001315
Guido van Rossumd8faa362007-04-27 19:54:29 +00001316class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001317
Guido van Rossumd8faa362007-04-27 19:54:29 +00001318 def _test(self, name, link=None):
1319 # See GNUWriteTest.
1320 tarinfo = tarfile.TarInfo(name)
1321 if link:
1322 tarinfo.linkname = link
1323 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001324
Guido van Rossumd8faa362007-04-27 19:54:29 +00001325 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001326 try:
1327 tar.addfile(tarinfo)
1328 finally:
1329 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001330
Guido van Rossumd8faa362007-04-27 19:54:29 +00001331 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001332 try:
1333 if link:
1334 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001335 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001336 else:
1337 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001338 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001339 finally:
1340 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001341
Guido van Rossume7ba4952007-06-06 23:52:48 +00001342 def test_pax_global_header(self):
1343 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001344 "foo": "bar",
1345 "uid": "0",
1346 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001347 "test": "\xe4\xf6\xfc",
1348 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001349
Benjamin Peterson886af962010-03-21 23:13:07 +00001350 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001351 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001352 try:
1353 tar.addfile(tarfile.TarInfo("test"))
1354 finally:
1355 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001356
1357 # Test if the global header was written correctly.
1358 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001359 try:
1360 self.assertEqual(tar.pax_headers, pax_headers)
1361 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1362 # Test if all the fields are strings.
1363 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001364 self.assertIsNot(type(key), bytes)
1365 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001366 if key in tarfile.PAX_NUMBER_FIELDS:
1367 try:
1368 tarfile.PAX_NUMBER_FIELDS[key](val)
1369 except (TypeError, ValueError):
1370 self.fail("unable to convert pax header field")
1371 finally:
1372 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001373
1374 def test_pax_extended_header(self):
1375 # The fields from the pax header have priority over the
1376 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001377 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001378
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001379 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1380 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001381 try:
1382 t = tarfile.TarInfo()
1383 t.name = "\xe4\xf6\xfc" # non-ASCII
1384 t.uid = 8**8 # too large
1385 t.pax_headers = pax_headers
1386 tar.addfile(t)
1387 finally:
1388 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001389
1390 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001391 try:
1392 t = tar.getmembers()[0]
1393 self.assertEqual(t.pax_headers, pax_headers)
1394 self.assertEqual(t.name, "foo")
1395 self.assertEqual(t.uid, 123)
1396 finally:
1397 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001398
1399
1400class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001401
1402 format = tarfile.USTAR_FORMAT
1403
1404 def test_iso8859_1_filename(self):
1405 self._test_unicode_filename("iso8859-1")
1406
1407 def test_utf7_filename(self):
1408 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001409
1410 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001411 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001412
Guido van Rossumd8faa362007-04-27 19:54:29 +00001413 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001414 tar = tarfile.open(tmpname, "w", format=self.format,
1415 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001416 try:
1417 name = "\xe4\xf6\xfc"
1418 tar.addfile(tarfile.TarInfo(name))
1419 finally:
1420 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001421
1422 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001423 try:
1424 self.assertEqual(tar.getmembers()[0].name, name)
1425 finally:
1426 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001427
1428 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001429 tar = tarfile.open(tmpname, "w", format=self.format,
1430 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001431 try:
1432 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001433
Antoine Pitrou95f55602010-09-23 18:36:46 +00001434 tarinfo.name = "\xe4\xf6\xfc"
1435 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001436
Antoine Pitrou95f55602010-09-23 18:36:46 +00001437 tarinfo.name = "foo"
1438 tarinfo.uname = "\xe4\xf6\xfc"
1439 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1440 finally:
1441 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001442
1443 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001444 tar = tarfile.open(tarname, "r",
1445 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001446 try:
1447 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001448 self.assertIs(type(t.name), str)
1449 self.assertIs(type(t.linkname), str)
1450 self.assertIs(type(t.uname), str)
1451 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001452 finally:
1453 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001454
Guido van Rossume7ba4952007-06-06 23:52:48 +00001455 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001456 t = tarfile.TarInfo("foo")
1457 t.uname = "\xe4\xf6\xfc"
1458 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001459
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001460 tar = tarfile.open(tmpname, mode="w", format=self.format,
1461 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001462 try:
1463 tar.addfile(t)
1464 finally:
1465 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001466
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001467 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001468 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001469 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001470 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1471 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1472
1473 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001474 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001475 tar = tarfile.open(tmpname, encoding="ascii")
1476 t = tar.getmember("foo")
1477 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1478 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1479 finally:
1480 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001481
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001482
Guido van Rossume7ba4952007-06-06 23:52:48 +00001483class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001484
Guido van Rossume7ba4952007-06-06 23:52:48 +00001485 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001486
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001487 def test_bad_pax_header(self):
1488 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1489 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001490 for encoding, name in (
1491 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001492 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001493 with tarfile.open(tarname, encoding=encoding,
1494 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001495 try:
1496 t = tar.getmember(name)
1497 except KeyError:
1498 self.fail("unable to read bad GNU tar pax header")
1499
Guido van Rossumd8faa362007-04-27 19:54:29 +00001500
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001501class PAXUnicodeTest(UstarUnicodeTest):
1502
1503 format = tarfile.PAX_FORMAT
1504
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001505 # PAX_FORMAT ignores encoding in write mode.
1506 test_unicode_filename_error = None
1507
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001508 def test_binary_header(self):
1509 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001510 for encoding, name in (
1511 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001512 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001513 with tarfile.open(tarname, encoding=encoding,
1514 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001515 try:
1516 t = tar.getmember(name)
1517 except KeyError:
1518 self.fail("unable to read POSIX.1-2008 binary header")
1519
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001520
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001521class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001522 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001523
Guido van Rossumd8faa362007-04-27 19:54:29 +00001524 def setUp(self):
1525 self.tarname = tmpname
1526 if os.path.exists(self.tarname):
1527 os.remove(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001528
Guido van Rossumd8faa362007-04-27 19:54:29 +00001529 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001530 with tarfile.open(tarname, encoding="iso8859-1") as src:
1531 t = src.getmember("ustar/regtype")
1532 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001533 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001534 with tarfile.open(self.tarname, mode) as tar:
1535 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001536
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001537 def test_append_compressed(self):
1538 self._create_testtar("w:" + self.suffix)
1539 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1540
1541class AppendTest(AppendTestBase, unittest.TestCase):
1542 test_append_compressed = None
1543
1544 def _add_testfile(self, fileobj=None):
1545 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1546 tar.addfile(tarfile.TarInfo("bar"))
1547
Guido van Rossumd8faa362007-04-27 19:54:29 +00001548 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001549 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1550 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001551
1552 def test_non_existing(self):
1553 self._add_testfile()
1554 self._test()
1555
1556 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001557 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001558 self._add_testfile()
1559 self._test()
1560
1561 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001562 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001563 self._add_testfile(fobj)
1564 fobj.seek(0)
1565 self._test(fileobj=fobj)
1566
1567 def test_fileobj(self):
1568 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001569 with open(self.tarname, "rb") as fobj:
1570 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001571 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001572 self._add_testfile(fobj)
1573 fobj.seek(0)
1574 self._test(names=["foo", "bar"], fileobj=fobj)
1575
1576 def test_existing(self):
1577 self._create_testtar()
1578 self._add_testfile()
1579 self._test(names=["foo", "bar"])
1580
Lars Gustäbel9520a432009-11-22 18:48:49 +00001581 # Append mode is supposed to fail if the tarfile to append to
1582 # does not end with a zero block.
1583 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001584 with open(self.tarname, "wb") as fobj:
1585 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001586 self.assertRaises(tarfile.ReadError, self._add_testfile)
1587
1588 def test_null(self):
1589 self._test_error(b"")
1590
1591 def test_incomplete(self):
1592 self._test_error(b"\0" * 13)
1593
1594 def test_premature_eof(self):
1595 data = tarfile.TarInfo("foo").tobuf()
1596 self._test_error(data)
1597
1598 def test_trailing_garbage(self):
1599 data = tarfile.TarInfo("foo").tobuf()
1600 self._test_error(data + b"\0" * 13)
1601
1602 def test_invalid(self):
1603 self._test_error(b"a" * 512)
1604
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001605class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
1606 pass
1607
1608class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
1609 pass
1610
1611class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
1612 pass
1613
Guido van Rossumd8faa362007-04-27 19:54:29 +00001614
1615class LimitsTest(unittest.TestCase):
1616
1617 def test_ustar_limits(self):
1618 # 100 char name
1619 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001620 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001621
1622 # 101 char name that cannot be stored
1623 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001624 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001625
1626 # 256 char name with a slash at pos 156
1627 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001628 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001629
1630 # 256 char name that cannot be stored
1631 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001632 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001633
1634 # 512 char name
1635 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001636 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001637
1638 # 512 char linkname
1639 tarinfo = tarfile.TarInfo("longlink")
1640 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001641 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001642
1643 # uid > 8 digits
1644 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001645 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001646 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001647
1648 def test_gnu_limits(self):
1649 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001650 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001651
1652 tarinfo = tarfile.TarInfo("longlink")
1653 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001654 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001655
1656 # uid >= 256 ** 7
1657 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001658 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001659 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001660
1661 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001662 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001663 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001664
1665 tarinfo = tarfile.TarInfo("longlink")
1666 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001667 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001668
1669 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001670 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001671 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001672
1673
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001674class MiscTest(unittest.TestCase):
1675
1676 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001677 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
1678 b"foo\0\0\0\0\0")
1679 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
1680 b"foo")
1681 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
1682 "foo")
1683 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
1684 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001685
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001686 def test_read_number_fields(self):
1687 # Issue 13158: Test if GNU tar specific base-256 number fields
1688 # are decoded correctly.
1689 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1690 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001691 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
1692 0o10000000)
1693 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
1694 0xffffffff)
1695 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
1696 -1)
1697 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
1698 -100)
1699 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
1700 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001701
1702 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001703 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001704 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001705 self.assertEqual(tarfile.itn(0o10000000),
1706 b"\x80\x00\x00\x00\x00\x20\x00\x00")
1707 self.assertEqual(tarfile.itn(0xffffffff),
1708 b"\x80\x00\x00\x00\xff\xff\xff\xff")
1709 self.assertEqual(tarfile.itn(-1),
1710 b"\xff\xff\xff\xff\xff\xff\xff\xff")
1711 self.assertEqual(tarfile.itn(-100),
1712 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1713 self.assertEqual(tarfile.itn(-0x100000000000000),
1714 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001715
1716 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001717 with self.assertRaises(ValueError):
1718 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
1719 with self.assertRaises(ValueError):
1720 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
1721 with self.assertRaises(ValueError):
1722 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
1723 with self.assertRaises(ValueError):
1724 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001725
1726
Lars Gustäbel01385812010-03-03 12:08:54 +00001727class ContextManagerTest(unittest.TestCase):
1728
1729 def test_basic(self):
1730 with tarfile.open(tarname) as tar:
1731 self.assertFalse(tar.closed, "closed inside runtime context")
1732 self.assertTrue(tar.closed, "context manager failed")
1733
1734 def test_closed(self):
1735 # The __enter__() method is supposed to raise IOError
1736 # if the TarFile object is already closed.
1737 tar = tarfile.open(tarname)
1738 tar.close()
1739 with self.assertRaises(IOError):
1740 with tar:
1741 pass
1742
1743 def test_exception(self):
1744 # Test if the IOError exception is passed through properly.
1745 with self.assertRaises(Exception) as exc:
1746 with tarfile.open(tarname) as tar:
1747 raise IOError
1748 self.assertIsInstance(exc.exception, IOError,
1749 "wrong exception raised in context manager")
1750 self.assertTrue(tar.closed, "context manager failed")
1751
1752 def test_no_eof(self):
1753 # __exit__() must not write end-of-archive blocks if an
1754 # exception was raised.
1755 try:
1756 with tarfile.open(tmpname, "w") as tar:
1757 raise Exception
1758 except:
1759 pass
1760 self.assertEqual(os.path.getsize(tmpname), 0,
1761 "context manager wrote an end-of-archive block")
1762 self.assertTrue(tar.closed, "context manager failed")
1763
1764 def test_eof(self):
1765 # __exit__() must write end-of-archive blocks, i.e. call
1766 # TarFile.close() if there was no error.
1767 with tarfile.open(tmpname, "w"):
1768 pass
1769 self.assertNotEqual(os.path.getsize(tmpname), 0,
1770 "context manager wrote no end-of-archive block")
1771
1772 def test_fileobj(self):
1773 # Test that __exit__() did not close the external file
1774 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001775 with open(tmpname, "wb") as fobj:
1776 try:
1777 with tarfile.open(fileobj=fobj, mode="w") as tar:
1778 raise Exception
1779 except:
1780 pass
1781 self.assertFalse(fobj.closed, "external file object was closed")
1782 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00001783
1784
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001785@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
1786class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00001787
1788 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001789 # symbolic or hard links tarfile tries to extract these types of members
1790 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00001791 def _test_link_extraction(self, name):
1792 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001793 with open(os.path.join(TEMPDIR, name), "rb") as f:
1794 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00001795 self.assertEqual(md5sum(data), md5_regtype)
1796
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001797 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00001798 @unittest.skipIf(hasattr(os.path, "islink"),
1799 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001800 def test_hardlink_extraction1(self):
1801 self._test_link_extraction("ustar/lnktype")
1802
Brian Curtind40e6f72010-07-08 21:39:08 +00001803 @unittest.skipIf(hasattr(os.path, "islink"),
1804 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001805 def test_hardlink_extraction2(self):
1806 self._test_link_extraction("./ustar/linktest2/lnktype")
1807
Brian Curtin74e45612010-07-09 15:58:59 +00001808 @unittest.skipIf(hasattr(os, "symlink"),
1809 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001810 def test_symlink_extraction1(self):
1811 self._test_link_extraction("ustar/symtype")
1812
Brian Curtin74e45612010-07-09 15:58:59 +00001813 @unittest.skipIf(hasattr(os, "symlink"),
1814 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001815 def test_symlink_extraction2(self):
1816 self._test_link_extraction("./ustar/linktest2/symtype")
1817
1818
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001819class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00001820 # Issue5068: The _BZ2Proxy.read() method loops forever
1821 # on an empty or partial bzipped file.
1822
1823 def _test_partial_input(self, mode):
1824 class MyBytesIO(io.BytesIO):
1825 hit_eof = False
1826 def read(self, n):
1827 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001828 raise AssertionError("infinite loop detected in "
1829 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00001830 self.hit_eof = self.tell() == len(self.getvalue())
1831 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001832 def seek(self, *args):
1833 self.hit_eof = False
1834 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00001835
1836 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1837 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001838 try:
1839 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
1840 except tarfile.ReadError:
1841 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00001842
1843 def test_partial_input(self):
1844 self._test_partial_input("r")
1845
1846 def test_partial_input_bz2(self):
1847 self._test_partial_input("r:bz2")
1848
1849
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001850def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00001851 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00001852 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001853
Antoine Pitrou95f55602010-09-23 18:36:46 +00001854 with open(tarname, "rb") as fobj:
1855 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001856
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001857 # Create compressed tarfiles.
1858 for c in GzipTest, Bz2Test, LzmaTest:
1859 if c.open:
1860 support.unlink(c.tarname)
1861 with c.open(c.tarname, "wb") as tar:
1862 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001863
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001864def tearDownModule():
1865 if os.path.exists(TEMPDIR):
1866 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001867
Neal Norwitz996acf12003-02-17 14:51:41 +00001868if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001869 unittest.main()