blob: 57fc062cae59fd09224dadbd9be72ed475f37571 [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
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020044 taropen = tarfile.TarFile.taropen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030045
46 @property
47 def mode(self):
48 return self.prefix + self.suffix
49
50@support.requires_gzip
51class GzipTest:
52 tarname = gzipname
53 suffix = 'gz'
54 open = gzip.GzipFile if gzip else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020055 taropen = tarfile.TarFile.gzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030056
57@support.requires_bz2
58class Bz2Test:
59 tarname = bz2name
60 suffix = 'bz2'
61 open = bz2.BZ2File if bz2 else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020062 taropen = tarfile.TarFile.bz2open
Serhiy Storchaka8b562922013-06-17 15:38:50 +030063
64@support.requires_lzma
65class LzmaTest:
66 tarname = xzname
67 suffix = 'xz'
68 open = lzma.LZMAFile if lzma else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020069 taropen = tarfile.TarFile.xzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030070
71
72class ReadTest(TarTest):
73
74 prefix = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000075
76 def setUp(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +030077 self.tar = tarfile.open(self.tarname, mode=self.mode,
78 encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000079
80 def tearDown(self):
81 self.tar.close()
82
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000083
Serhiy Storchaka8b562922013-06-17 15:38:50 +030084class UstarReadTest(ReadTest, unittest.TestCase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000085
Guido van Rossumd8faa362007-04-27 19:54:29 +000086 def test_fileobj_regular_file(self):
87 tarinfo = self.tar.getmember("ustar/regtype")
Lars Gustäbel7a919e92012-05-05 18:15:03 +020088 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000089 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +030090 self.assertEqual(len(data), tarinfo.size,
91 "regular file extraction failed")
92 self.assertEqual(md5sum(data), md5_regtype,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000093 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000094
Guido van Rossumd8faa362007-04-27 19:54:29 +000095 def test_fileobj_readlines(self):
96 self.tar.extract("ustar/regtype", TEMPDIR)
97 tarinfo = self.tar.getmember("ustar/regtype")
Antoine Pitrou95f55602010-09-23 18:36:46 +000098 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
99 lines1 = fobj1.readlines()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000100
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200101 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000102 fobj2 = io.TextIOWrapper(fobj)
103 lines2 = fobj2.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300104 self.assertEqual(lines1, lines2,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000105 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300106 self.assertEqual(len(lines2), 114,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000107 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300108 self.assertEqual(lines2[83],
109 "I will gladly admit that Python is not the fastest "
110 "running scripting language.\n",
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000111 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000112
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113 def test_fileobj_iter(self):
114 self.tar.extract("ustar/regtype", TEMPDIR)
115 tarinfo = self.tar.getmember("ustar/regtype")
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200116 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000117 lines1 = fobj1.readlines()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200118 with self.tar.extractfile(tarinfo) as fobj2:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000119 lines2 = list(io.TextIOWrapper(fobj2))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300120 self.assertEqual(lines1, lines2,
121 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +0000122
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123 def test_fileobj_seek(self):
124 self.tar.extract("ustar/regtype", TEMPDIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000125 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
126 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +0000127
Guido van Rossumd8faa362007-04-27 19:54:29 +0000128 tarinfo = self.tar.getmember("ustar/regtype")
129 fobj = self.tar.extractfile(tarinfo)
130
131 text = fobj.read()
132 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000133 self.assertEqual(0, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134 "seek() to file's start failed")
135 fobj.seek(2048, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000136 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000137 "seek() to absolute position failed")
138 fobj.seek(-1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000139 self.assertEqual(1024, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000140 "seek() to negative relative position failed")
141 fobj.seek(1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000142 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000143 "seek() to positive relative position failed")
144 s = fobj.read(10)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300145 self.assertEqual(s, data[2048:2058],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000146 "read() after seek failed")
147 fobj.seek(0, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000148 self.assertEqual(tarinfo.size, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000149 "seek() to file's end failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300150 self.assertEqual(fobj.read(), b"",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000151 "read() at file's end did not return empty string")
152 fobj.seek(-tarinfo.size, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000153 self.assertEqual(0, fobj.tell(),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000154 "relative seek() to file's end failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155 fobj.seek(512)
156 s1 = fobj.readlines()
157 fobj.seek(512)
158 s2 = fobj.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300159 self.assertEqual(s1, s2,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000160 "readlines() after seek failed")
161 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000162 self.assertEqual(len(fobj.readline()), fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000163 "tell() after readline() failed")
164 fobj.seek(512)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300165 self.assertEqual(len(fobj.readline()) + 512, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000166 "tell() after seek() and readline() failed")
167 fobj.seek(0)
168 line = fobj.readline()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000169 self.assertEqual(fobj.read(), data[len(line):],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000170 "read() after readline() failed")
171 fobj.close()
172
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200173 def test_fileobj_text(self):
174 with self.tar.extractfile("ustar/regtype") as fobj:
175 fobj = io.TextIOWrapper(fobj)
176 data = fobj.read().encode("iso8859-1")
177 self.assertEqual(md5sum(data), md5_regtype)
178 try:
179 fobj.seek(100)
180 except AttributeError:
181 # Issue #13815: seek() complained about a missing
182 # flush() method.
183 self.fail("seeking failed in text mode")
184
Lars Gustäbel1b512722010-06-03 12:45:16 +0000185 # Test if symbolic and hard links are resolved by extractfile(). The
186 # test link members each point to a regular member whose data is
187 # supposed to be exported.
188 def _test_fileobj_link(self, lnktype, regtype):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300189 with self.tar.extractfile(lnktype) as a, \
190 self.tar.extractfile(regtype) as b:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000191 self.assertEqual(a.name, b.name)
Lars Gustäbel1b512722010-06-03 12:45:16 +0000192
193 def test_fileobj_link1(self):
194 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
195
196 def test_fileobj_link2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300197 self._test_fileobj_link("./ustar/linktest2/lnktype",
198 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000199
200 def test_fileobj_symlink1(self):
201 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
202
203 def test_fileobj_symlink2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300204 self._test_fileobj_link("./ustar/linktest2/symtype",
205 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000206
Lars Gustäbel1ef9eda2012-04-24 21:04:40 +0200207 def test_issue14160(self):
208 self._test_fileobj_link("symtype2", "ustar/regtype")
209
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300210class GzipUstarReadTest(GzipTest, UstarReadTest):
211 pass
212
213class Bz2UstarReadTest(Bz2Test, UstarReadTest):
214 pass
215
216class LzmaUstarReadTest(LzmaTest, UstarReadTest):
217 pass
218
Guido van Rossumd8faa362007-04-27 19:54:29 +0000219
Lars Gustäbel9520a432009-11-22 18:48:49 +0000220class CommonReadTest(ReadTest):
221
222 def test_empty_tarfile(self):
223 # Test for issue6123: Allow opening empty archives.
224 # This test checks if tarfile.open() is able to open an empty tar
225 # archive successfully. Note that an empty tar archive is not the
226 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000227 with tarfile.open(tmpname, self.mode.replace("r", "w")):
228 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000229 try:
230 tar = tarfile.open(tmpname, self.mode)
231 tar.getnames()
232 except tarfile.ReadError:
233 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000234 else:
235 self.assertListEqual(tar.getmembers(), [])
236 finally:
237 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000238
Serhiy Storchaka2a3d7d12014-01-13 19:07:33 +0200239 def test_non_existent_tarfile(self):
240 # Test for issue11513: prevent non-existent gzipped tarfiles raising
241 # multiple exceptions.
Serhiy Storchaka2d5a0922014-01-24 22:19:23 +0200242 test = 'xxx'
243 if sys.platform == 'win32' and '|' in self.mode:
244 # Issue #20384: On Windows os.open() error message doesn't
245 # contain file name.
246 text = ''
247 with self.assertRaisesRegex(FileNotFoundError, test):
Serhiy Storchaka2a3d7d12014-01-13 19:07:33 +0200248 tarfile.open("xxx", self.mode)
249
Lars Gustäbel9520a432009-11-22 18:48:49 +0000250 def test_null_tarfile(self):
251 # Test for issue6123: Allow opening empty archives.
252 # This test guarantees that tarfile.open() does not treat an empty
253 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000254 with open(tmpname, "wb"):
255 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000256 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
257 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
258
259 def test_ignore_zeros(self):
260 # Test TarFile's ignore_zeros option.
Lars Gustäbel9520a432009-11-22 18:48:49 +0000261 for char in (b'\0', b'a'):
262 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
263 # are ignored correctly.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300264 with self.open(tmpname, "w") as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000265 fobj.write(char * 1024)
266 fobj.write(tarfile.TarInfo("foo").tobuf())
Lars Gustäbel9520a432009-11-22 18:48:49 +0000267
268 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000269 try:
270 self.assertListEqual(tar.getnames(), ["foo"],
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300271 "ignore_zeros=True should have skipped the %r-blocks" %
272 char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000273 finally:
274 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000275
276
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300277class MiscReadTestBase(CommonReadTest):
Thomas Woutersed03b412007-08-28 21:37:11 +0000278 def test_no_name_argument(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000279 with open(self.tarname, "rb") as fobj:
280 tar = tarfile.open(fileobj=fobj, mode=self.mode)
281 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000282
Thomas Woutersed03b412007-08-28 21:37:11 +0000283 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000284 with open(self.tarname, "rb") as fobj:
285 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000286 fobj = io.BytesIO(data)
287 self.assertRaises(AttributeError, getattr, fobj, "name")
288 tar = tarfile.open(fileobj=fobj, mode=self.mode)
289 self.assertEqual(tar.name, None)
290
291 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000292 with open(self.tarname, "rb") as fobj:
293 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000294 fobj = io.BytesIO(data)
295 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000296 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
297 self.assertEqual(tar.name, None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000298
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +0200299 def test_illegal_mode_arg(self):
300 with open(tmpname, 'wb'):
301 pass
302 with self.assertRaisesRegex(ValueError, 'mode must be '):
303 tar = self.taropen(tmpname, 'q')
304 with self.assertRaisesRegex(ValueError, 'mode must be '):
305 tar = self.taropen(tmpname, 'rw')
306 with self.assertRaisesRegex(ValueError, 'mode must be '):
307 tar = self.taropen(tmpname, '')
308
Christian Heimesd8654cf2007-12-02 15:22:16 +0000309 def test_fileobj_with_offset(self):
310 # Skip the first member and store values from the second member
311 # of the testtar.
312 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000313 try:
314 tar.next()
315 t = tar.next()
316 name = t.name
317 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200318 with tar.extractfile(t) as f:
319 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000320 finally:
321 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000322
323 # Open the testtar and seek to the offset of the second member.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300324 with self.open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000325 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000326
Antoine Pitrou95f55602010-09-23 18:36:46 +0000327 # Test if the tarfile starts with the second member.
328 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
329 t = tar.next()
330 self.assertEqual(t.name, name)
331 # Read to the end of fileobj and test if seeking back to the
332 # beginning works.
333 tar.getmembers()
334 self.assertEqual(tar.extractfile(t).read(), data,
335 "seek back did not work")
336 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000337
Guido van Rossumd8faa362007-04-27 19:54:29 +0000338 def test_fail_comp(self):
339 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000340 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000341 with open(tarname, "rb") as fobj:
342 self.assertRaises(tarfile.ReadError, tarfile.open,
343 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000344
345 def test_v7_dirtype(self):
346 # Test old style dirtype member (bug #1336623):
347 # Old V7 tars create directory members using an AREGTYPE
348 # header with a "/" appended to the filename field.
349 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300350 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000351 "v7 dirtype failed")
352
Christian Heimes126d29a2008-02-11 22:57:17 +0000353 def test_xstar_type(self):
354 # The xstar format stores extra atime and ctime fields inside the
355 # space reserved for the prefix field. The prefix field must be
356 # ignored in this case, otherwise it will mess up the name.
357 try:
358 self.tar.getmember("misc/regtype-xstar")
359 except KeyError:
360 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
361
Guido van Rossumd8faa362007-04-27 19:54:29 +0000362 def test_check_members(self):
363 for tarinfo in self.tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300364 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000365 "wrong mtime for %s" % tarinfo.name)
366 if not tarinfo.name.startswith("ustar/"):
367 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300368 self.assertEqual(tarinfo.uname, "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000369 "wrong uname for %s" % tarinfo.name)
370
371 def test_find_members(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300372 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000373 "could not find all members")
374
Brian Curtin74e45612010-07-09 15:58:59 +0000375 @unittest.skipUnless(hasattr(os, "link"),
376 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000377 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000378 def test_extract_hardlink(self):
379 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200380 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000381 tar.extract("ustar/regtype", TEMPDIR)
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200382 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000383
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200384 tar.extract("ustar/lnktype", TEMPDIR)
385 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000386 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
387 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000388 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000389
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200390 tar.extract("ustar/symtype", TEMPDIR)
391 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000392 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
393 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000394 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000395
Christian Heimesfaf2f632008-01-06 16:59:19 +0000396 def test_extractall(self):
397 # Test if extractall() correctly restores directory permissions
398 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000399 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000400 DIR = os.path.join(TEMPDIR, "extractall")
401 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000402 try:
403 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000404 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000405 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000406 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000407 if sys.platform != "win32":
408 # Win32 has no support for fine grained permissions.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300409 self.assertEqual(tarinfo.mode & 0o777,
410 os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000411 def format_mtime(mtime):
412 if isinstance(mtime, float):
413 return "{} ({})".format(mtime, mtime.hex())
414 else:
415 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000416 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000417 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
418 format_mtime(tarinfo.mtime),
419 format_mtime(file_mtime),
420 path)
421 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000422 finally:
423 tar.close()
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000424 shutil.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000425
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000426 def test_extract_directory(self):
427 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000428 DIR = os.path.join(TEMPDIR, "extractdir")
429 os.mkdir(DIR)
430 try:
431 with tarfile.open(tarname, encoding="iso8859-1") as tar:
432 tarinfo = tar.getmember(dirtype)
433 tar.extract(tarinfo, path=DIR)
434 extracted = os.path.join(DIR, dirtype)
435 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
436 if sys.platform != "win32":
437 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
438 finally:
439 shutil.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000440
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000441 def test_init_close_fobj(self):
442 # Issue #7341: Close the internal file object in the TarFile
443 # constructor in case of an error. For the test we rely on
444 # the fact that opening an empty file raises a ReadError.
445 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000446 with open(empty, "wb") as fobj:
447 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000448
449 try:
450 tar = object.__new__(tarfile.TarFile)
451 try:
452 tar.__init__(empty)
453 except tarfile.ReadError:
454 self.assertTrue(tar.fileobj.closed)
455 else:
456 self.fail("ReadError not raised")
457 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000458 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000459
Serhiy Storchaka263fab92013-05-09 14:22:26 +0300460 def test_parallel_iteration(self):
461 # Issue #16601: Restarting iteration over tarfile continued
462 # from where it left off.
463 with tarfile.open(self.tarname) as tar:
464 for m1, m2 in zip(tar, tar):
465 self.assertEqual(m1.offset, m2.offset)
466 self.assertEqual(m1.get_info(), m2.get_info())
467
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300468class MiscReadTest(MiscReadTestBase, unittest.TestCase):
469 test_fail_comp = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000470
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300471class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2a3d7d12014-01-13 19:07:33 +0200472 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000473
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300474class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
475 def test_no_name_argument(self):
476 self.skipTest("BZ2File have no name attribute")
477
478class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
479 def test_no_name_argument(self):
480 self.skipTest("LZMAFile have no name attribute")
481
482
483class StreamReadTest(CommonReadTest, unittest.TestCase):
484
485 prefix="r|"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000486
Lars Gustäbeldd071042011-02-23 11:42:22 +0000487 def test_read_through(self):
488 # Issue #11224: A poorly designed _FileInFile.read() method
489 # caused seeking errors with stream tar files.
490 for tarinfo in self.tar:
491 if not tarinfo.isreg():
492 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200493 with self.tar.extractfile(tarinfo) as fobj:
494 while True:
495 try:
496 buf = fobj.read(512)
497 except tarfile.StreamError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300498 self.fail("simple read-through using "
499 "TarFile.extractfile() failed")
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200500 if not buf:
501 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000502
Guido van Rossumd8faa362007-04-27 19:54:29 +0000503 def test_fileobj_regular_file(self):
504 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200505 with self.tar.extractfile(tarinfo) as fobj:
506 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300507 self.assertEqual(len(data), tarinfo.size,
508 "regular file extraction failed")
509 self.assertEqual(md5sum(data), md5_regtype,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510 "regular file extraction failed")
511
512 def test_provoke_stream_error(self):
513 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200514 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
515 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000516
Guido van Rossumd8faa362007-04-27 19:54:29 +0000517 def test_compare_members(self):
518 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000519 try:
520 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000521
Antoine Pitrou95f55602010-09-23 18:36:46 +0000522 while True:
523 t1 = tar1.next()
524 t2 = tar2.next()
525 if t1 is None:
526 break
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300527 self.assertIsNotNone(t2, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000528
Antoine Pitrou95f55602010-09-23 18:36:46 +0000529 if t2.islnk() or t2.issym():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300530 with self.assertRaises(tarfile.StreamError):
531 tar2.extractfile(t2)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000532 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000533
Antoine Pitrou95f55602010-09-23 18:36:46 +0000534 v1 = tar1.extractfile(t1)
535 v2 = tar2.extractfile(t2)
536 if v1 is None:
537 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300538 self.assertIsNotNone(v2, "stream.extractfile() failed")
539 self.assertEqual(v1.read(), v2.read(),
540 "stream extraction failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000541 finally:
542 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000543
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300544class GzipStreamReadTest(GzipTest, StreamReadTest):
545 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000546
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300547class Bz2StreamReadTest(Bz2Test, StreamReadTest):
548 pass
Thomas Wouterscf297e42007-02-23 15:07:44 +0000549
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300550class LzmaStreamReadTest(LzmaTest, StreamReadTest):
551 pass
552
553
554class DetectReadTest(TarTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000555 def _testfunc_file(self, name, mode):
556 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000557 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000558 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000559 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000560 else:
561 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000562
Guido van Rossumd8faa362007-04-27 19:54:29 +0000563 def _testfunc_fileobj(self, name, mode):
564 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000565 with open(name, "rb") as f:
566 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000567 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000568 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000569 else:
570 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571
572 def _test_modes(self, testfunc):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300573 if self.suffix:
574 with self.assertRaises(tarfile.ReadError):
575 tarfile.open(tarname, mode="r:" + self.suffix)
576 with self.assertRaises(tarfile.ReadError):
577 tarfile.open(tarname, mode="r|" + self.suffix)
578 with self.assertRaises(tarfile.ReadError):
579 tarfile.open(self.tarname, mode="r:")
580 with self.assertRaises(tarfile.ReadError):
581 tarfile.open(self.tarname, mode="r|")
582 testfunc(self.tarname, "r")
583 testfunc(self.tarname, "r:" + self.suffix)
584 testfunc(self.tarname, "r:*")
585 testfunc(self.tarname, "r|" + self.suffix)
586 testfunc(self.tarname, "r|*")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100587
Guido van Rossumd8faa362007-04-27 19:54:29 +0000588 def test_detect_file(self):
589 self._test_modes(self._testfunc_file)
590
591 def test_detect_fileobj(self):
592 self._test_modes(self._testfunc_fileobj)
593
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300594class GzipDetectReadTest(GzipTest, DetectReadTest):
595 pass
596
597class Bz2DetectReadTest(Bz2Test, DetectReadTest):
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100598 def test_detect_stream_bz2(self):
599 # Originally, tarfile's stream detection looked for the string
600 # "BZh91" at the start of the file. This is incorrect because
601 # the '9' represents the blocksize (900kB). If the file was
602 # compressed using another blocksize autodetection fails.
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100603 with open(tarname, "rb") as fobj:
604 data = fobj.read()
605
606 # Compress with blocksize 100kB, the file starts with "BZh11".
607 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
608 fobj.write(data)
609
610 self._testfunc_file(tmpname, "r|*")
611
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300612class LzmaDetectReadTest(LzmaTest, DetectReadTest):
613 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000614
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300615
616class MemberReadTest(ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617
618 def _test_member(self, tarinfo, chksum=None, **kwargs):
619 if chksum is not None:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300620 with self.tar.extractfile(tarinfo) as f:
621 self.assertEqual(md5sum(f.read()), chksum,
622 "wrong md5sum for %s" % tarinfo.name)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000623
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000624 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000625 kwargs["uid"] = 1000
626 kwargs["gid"] = 100
627 if "old-v7" not in tarinfo.name:
628 # V7 tar can't handle alphabetic owners.
629 kwargs["uname"] = "tarfile"
630 kwargs["gname"] = "tarfile"
631 for k, v in kwargs.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300632 self.assertEqual(getattr(tarinfo, k), v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633 "wrong value in %s field of %s" % (k, tarinfo.name))
634
635 def test_find_regtype(self):
636 tarinfo = self.tar.getmember("ustar/regtype")
637 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
638
639 def test_find_conttype(self):
640 tarinfo = self.tar.getmember("ustar/conttype")
641 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
642
643 def test_find_dirtype(self):
644 tarinfo = self.tar.getmember("ustar/dirtype")
645 self._test_member(tarinfo, size=0)
646
647 def test_find_dirtype_with_size(self):
648 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
649 self._test_member(tarinfo, size=255)
650
651 def test_find_lnktype(self):
652 tarinfo = self.tar.getmember("ustar/lnktype")
653 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
654
655 def test_find_symtype(self):
656 tarinfo = self.tar.getmember("ustar/symtype")
657 self._test_member(tarinfo, size=0, linkname="regtype")
658
659 def test_find_blktype(self):
660 tarinfo = self.tar.getmember("ustar/blktype")
661 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
662
663 def test_find_chrtype(self):
664 tarinfo = self.tar.getmember("ustar/chrtype")
665 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
666
667 def test_find_fifotype(self):
668 tarinfo = self.tar.getmember("ustar/fifotype")
669 self._test_member(tarinfo, size=0)
670
671 def test_find_sparse(self):
672 tarinfo = self.tar.getmember("ustar/sparse")
673 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
674
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000675 def test_find_gnusparse(self):
676 tarinfo = self.tar.getmember("gnu/sparse")
677 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
678
679 def test_find_gnusparse_00(self):
680 tarinfo = self.tar.getmember("gnu/sparse-0.0")
681 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
682
683 def test_find_gnusparse_01(self):
684 tarinfo = self.tar.getmember("gnu/sparse-0.1")
685 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
686
687 def test_find_gnusparse_10(self):
688 tarinfo = self.tar.getmember("gnu/sparse-1.0")
689 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
690
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691 def test_find_umlauts(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300692 tarinfo = self.tar.getmember("ustar/umlauts-"
693 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000694 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
695
696 def test_find_ustar_longname(self):
697 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000698 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000699
700 def test_find_regtype_oldv7(self):
701 tarinfo = self.tar.getmember("misc/regtype-old-v7")
702 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
703
704 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000705 self.tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300706 self.tar = tarfile.open(self.tarname, mode=self.mode,
707 encoding="iso8859-1")
708 tarinfo = self.tar.getmember("pax/umlauts-"
709 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000710 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
711
712
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300713class LongnameTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000714
715 def test_read_longname(self):
716 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000717 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000718 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000719 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000720 except KeyError:
721 self.fail("longname not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300722 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
723 "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000724
725 def test_read_longlink(self):
726 longname = self.subdir + "/" + "123/" * 125 + "longname"
727 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
728 try:
729 tarinfo = self.tar.getmember(longlink)
730 except KeyError:
731 self.fail("longlink not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300732 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000733
734 def test_truncated_longname(self):
735 longname = self.subdir + "/" + "123/" * 125 + "longname"
736 tarinfo = self.tar.getmember(longname)
737 offset = tarinfo.offset
738 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000739 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300740 with self.assertRaises(tarfile.ReadError):
741 tarfile.open(name="foo.tar", fileobj=fobj)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000742
Guido van Rossume7ba4952007-06-06 23:52:48 +0000743 def test_header_offset(self):
744 # Test if the start offset of the TarInfo object includes
745 # the preceding extended header.
746 longname = self.subdir + "/" + "123/" * 125 + "longname"
747 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000748 with open(tarname, "rb") as fobj:
749 fobj.seek(offset)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300750 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
751 "iso8859-1", "strict")
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000752 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000753
Guido van Rossumd8faa362007-04-27 19:54:29 +0000754
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300755class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756
757 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000758 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000759
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000760 # Since 3.2 tarfile is supposed to accurately restore sparse members and
761 # produce files with holes. This is what we actually want to test here.
762 # Unfortunately, not all platforms/filesystems support sparse files, and
763 # even on platforms that do it is non-trivial to make reliable assertions
764 # about holes in files. Therefore, we first do one basic test which works
765 # an all platforms, and after that a test that will work only on
766 # platforms/filesystems that prove to support sparse files.
767 def _test_sparse_file(self, name):
768 self.tar.extract(name, TEMPDIR)
769 filename = os.path.join(TEMPDIR, name)
770 with open(filename, "rb") as fobj:
771 data = fobj.read()
772 self.assertEqual(md5sum(data), md5_sparse,
773 "wrong md5sum for %s" % name)
774
775 if self._fs_supports_holes():
776 s = os.stat(filename)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300777 self.assertLess(s.st_blocks * 512, s.st_size)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000778
779 def test_sparse_file_old(self):
780 self._test_sparse_file("gnu/sparse")
781
782 def test_sparse_file_00(self):
783 self._test_sparse_file("gnu/sparse-0.0")
784
785 def test_sparse_file_01(self):
786 self._test_sparse_file("gnu/sparse-0.1")
787
788 def test_sparse_file_10(self):
789 self._test_sparse_file("gnu/sparse-1.0")
790
791 @staticmethod
792 def _fs_supports_holes():
793 # Return True if the platform knows the st_blocks stat attribute and
794 # uses st_blocks units of 512 bytes, and if the filesystem is able to
795 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200796 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000797 # Linux evidentially has 512 byte st_blocks units.
798 name = os.path.join(TEMPDIR, "sparse-test")
799 with open(name, "wb") as fobj:
800 fobj.seek(4096)
801 fobj.truncate()
802 s = os.stat(name)
803 os.remove(name)
804 return s.st_blocks == 0
805 else:
806 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000807
808
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300809class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000810
811 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000812 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000813
Guido van Rossume7ba4952007-06-06 23:52:48 +0000814 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000815 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000816 try:
817 tarinfo = tar.getmember("pax/regtype1")
818 self.assertEqual(tarinfo.uname, "foo")
819 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300820 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
821 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000822
Antoine Pitrou95f55602010-09-23 18:36:46 +0000823 tarinfo = tar.getmember("pax/regtype2")
824 self.assertEqual(tarinfo.uname, "")
825 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300826 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
827 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000828
Antoine Pitrou95f55602010-09-23 18:36:46 +0000829 tarinfo = tar.getmember("pax/regtype3")
830 self.assertEqual(tarinfo.uname, "tarfile")
831 self.assertEqual(tarinfo.gname, "tarfile")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300832 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
833 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000834 finally:
835 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000836
837 def test_pax_number_fields(self):
838 # All following number fields are read from the pax header.
839 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000840 try:
841 tarinfo = tar.getmember("pax/regtype4")
842 self.assertEqual(tarinfo.size, 7011)
843 self.assertEqual(tarinfo.uid, 123)
844 self.assertEqual(tarinfo.gid, 123)
845 self.assertEqual(tarinfo.mtime, 1041808783.0)
846 self.assertEqual(type(tarinfo.mtime), float)
847 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
848 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
849 finally:
850 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000851
852
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300853class WriteTestBase(TarTest):
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000854 # Put all write tests in here that are supposed to be tested
855 # in all possible mode combinations.
856
857 def test_fileobj_no_close(self):
858 fobj = io.BytesIO()
859 tar = tarfile.open(fileobj=fobj, mode=self.mode)
860 tar.addfile(tarfile.TarInfo("foo"))
861 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300862 self.assertFalse(fobj.closed, "external fileobjs must never closed")
Serhiy Storchaka9fbec7a2014-01-18 15:53:05 +0200863 # Issue #20238: Incomplete gzip output with mode="w:gz"
864 data = fobj.getvalue()
865 del tar
866 support.gc_collect()
867 self.assertFalse(fobj.closed)
868 self.assertEqual(data, fobj.getvalue())
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000869
870
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300871class WriteTest(WriteTestBase, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000872
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300873 prefix = "w:"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000874
875 def test_100_char_name(self):
876 # The name field in a tar header stores strings of at most 100 chars.
877 # If a string is shorter than 100 chars it has to be padded with '\0',
878 # which implies that a string of exactly 100 chars is stored without
879 # a trailing '\0'.
880 name = "0123456789" * 10
881 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000882 try:
883 t = tarfile.TarInfo(name)
884 tar.addfile(t)
885 finally:
886 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000887
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000889 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300890 self.assertEqual(tar.getnames()[0], name,
Antoine Pitrou95f55602010-09-23 18:36:46 +0000891 "failed to store 100 char filename")
892 finally:
893 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000894
Guido van Rossumd8faa362007-04-27 19:54:29 +0000895 def test_tar_size(self):
896 # Test for bug #1013882.
897 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000898 try:
899 path = os.path.join(TEMPDIR, "file")
900 with open(path, "wb") as fobj:
901 fobj.write(b"aaa")
902 tar.add(path)
903 finally:
904 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300905 self.assertGreater(os.path.getsize(tmpname), 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000906 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000907
Guido van Rossumd8faa362007-04-27 19:54:29 +0000908 # The test_*_size tests test for bug #1167128.
909 def test_file_size(self):
910 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000911 try:
912 path = os.path.join(TEMPDIR, "file")
913 with open(path, "wb"):
914 pass
915 tarinfo = tar.gettarinfo(path)
916 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000917
Antoine Pitrou95f55602010-09-23 18:36:46 +0000918 with open(path, "wb") as fobj:
919 fobj.write(b"aaa")
920 tarinfo = tar.gettarinfo(path)
921 self.assertEqual(tarinfo.size, 3)
922 finally:
923 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000924
925 def test_directory_size(self):
926 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000927 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000928 try:
929 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000930 try:
931 tarinfo = tar.gettarinfo(path)
932 self.assertEqual(tarinfo.size, 0)
933 finally:
934 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000935 finally:
936 os.rmdir(path)
937
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300938 @unittest.skipUnless(hasattr(os, "link"),
939 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000940 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300941 link = os.path.join(TEMPDIR, "link")
942 target = os.path.join(TEMPDIR, "link_target")
943 with open(target, "wb") as fobj:
944 fobj.write(b"aaa")
945 os.link(target, link)
946 try:
947 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000948 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300949 # Record the link target in the inodes list.
950 tar.gettarinfo(target)
951 tarinfo = tar.gettarinfo(link)
952 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000953 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300954 tar.close()
955 finally:
956 os.remove(target)
957 os.remove(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000958
Brian Curtin3b4499c2010-12-28 14:31:47 +0000959 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000960 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +0000961 path = os.path.join(TEMPDIR, "symlink")
962 os.symlink("link_target", path)
963 try:
964 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000965 try:
966 tarinfo = tar.gettarinfo(path)
967 self.assertEqual(tarinfo.size, 0)
968 finally:
969 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +0000970 finally:
971 os.remove(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972
973 def test_add_self(self):
974 # Test for #1257255.
975 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000976 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000977 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300978 self.assertEqual(tar.name, dstname,
979 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000980 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300981 self.assertEqual(tar.getnames(), [],
982 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983
Antoine Pitrou95f55602010-09-23 18:36:46 +0000984 cwd = os.getcwd()
985 os.chdir(TEMPDIR)
986 tar.add(dstname)
987 os.chdir(cwd)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300988 self.assertEqual(tar.getnames(), [],
989 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000990 finally:
991 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000992
Guido van Rossum486364b2007-06-30 05:01:58 +0000993 def test_exclude(self):
994 tempdir = os.path.join(TEMPDIR, "exclude")
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)
Guido van Rossum486364b2007-06-30 05:01:58 +00001000
Benjamin Peterson886af962010-03-21 23:13:07 +00001001 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +00001002
1003 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001004 try:
1005 with support.check_warnings(("use the filter argument",
1006 DeprecationWarning)):
1007 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
1008 finally:
1009 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001010
1011 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001012 try:
1013 self.assertEqual(len(tar.getmembers()), 1)
1014 self.assertEqual(tar.getnames()[0], "empty_dir")
1015 finally:
1016 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001017 finally:
1018 shutil.rmtree(tempdir)
1019
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001020 def test_filter(self):
1021 tempdir = os.path.join(TEMPDIR, "filter")
1022 os.mkdir(tempdir)
1023 try:
1024 for name in ("foo", "bar", "baz"):
1025 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001026 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001027
1028 def filter(tarinfo):
1029 if os.path.basename(tarinfo.name) == "bar":
1030 return
1031 tarinfo.uid = 123
1032 tarinfo.uname = "foo"
1033 return tarinfo
1034
1035 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001036 try:
1037 tar.add(tempdir, arcname="empty_dir", filter=filter)
1038 finally:
1039 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001040
Raymond Hettingera63a3122011-01-26 20:34:14 +00001041 # Verify that filter is a keyword-only argument
1042 with self.assertRaises(TypeError):
1043 tar.add(tempdir, "empty_dir", True, None, filter)
1044
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001045 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001046 try:
1047 for tarinfo in tar:
1048 self.assertEqual(tarinfo.uid, 123)
1049 self.assertEqual(tarinfo.uname, "foo")
1050 self.assertEqual(len(tar.getmembers()), 3)
1051 finally:
1052 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001053 finally:
1054 shutil.rmtree(tempdir)
1055
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001056 # Guarantee that stored pathnames are not modified. Don't
1057 # remove ./ or ../ or double slashes. Still make absolute
1058 # pathnames relative.
1059 # For details see bug #6054.
1060 def _test_pathname(self, path, cmp_path=None, dir=False):
1061 # Create a tarfile with an empty member named path
1062 # and compare the stored name with the original.
1063 foo = os.path.join(TEMPDIR, "foo")
1064 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001065 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001066 else:
1067 os.mkdir(foo)
1068
1069 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001070 try:
1071 tar.add(foo, arcname=path)
1072 finally:
1073 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001074
1075 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001076 try:
1077 t = tar.next()
1078 finally:
1079 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001080
1081 if not dir:
1082 os.remove(foo)
1083 else:
1084 os.rmdir(foo)
1085
1086 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1087
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001088
1089 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001090 def test_extractall_symlinks(self):
1091 # Test if extractall works properly when tarfile contains symlinks
1092 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1093 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1094 os.mkdir(tempdir)
1095 try:
1096 source_file = os.path.join(tempdir,'source')
1097 target_file = os.path.join(tempdir,'symlink')
1098 with open(source_file,'w') as f:
1099 f.write('something\n')
1100 os.symlink(source_file, target_file)
1101 tar = tarfile.open(temparchive,'w')
1102 tar.add(source_file)
1103 tar.add(target_file)
1104 tar.close()
1105 # Let's extract it to the location which contains the symlink
1106 tar = tarfile.open(temparchive,'r')
1107 # this should not raise OSError: [Errno 17] File exists
1108 try:
1109 tar.extractall(path=tempdir)
1110 except OSError:
1111 self.fail("extractall failed with symlinked files")
1112 finally:
1113 tar.close()
1114 finally:
1115 os.unlink(temparchive)
1116 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001117
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001118 def test_pathnames(self):
1119 self._test_pathname("foo")
1120 self._test_pathname(os.path.join("foo", ".", "bar"))
1121 self._test_pathname(os.path.join("foo", "..", "bar"))
1122 self._test_pathname(os.path.join(".", "foo"))
1123 self._test_pathname(os.path.join(".", "foo", "."))
1124 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1125 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1126 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1127 self._test_pathname(os.path.join("..", "foo"))
1128 self._test_pathname(os.path.join("..", "foo", ".."))
1129 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1130 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1131
1132 self._test_pathname("foo" + os.sep + os.sep + "bar")
1133 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1134
1135 def test_abs_pathnames(self):
1136 if sys.platform == "win32":
1137 self._test_pathname("C:\\foo", "foo")
1138 else:
1139 self._test_pathname("/foo", "foo")
1140 self._test_pathname("///foo", "foo")
1141
1142 def test_cwd(self):
1143 # Test adding the current working directory.
1144 cwd = os.getcwd()
1145 os.chdir(TEMPDIR)
1146 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001147 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001148 try:
1149 tar.add(".")
1150 finally:
1151 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001152
1153 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001154 try:
1155 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001156 if t.name != ".":
1157 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001158 finally:
1159 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001160 finally:
1161 os.chdir(cwd)
1162
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001163 def test_open_nonwritable_fileobj(self):
1164 for exctype in OSError, EOFError, RuntimeError:
1165 class BadFile(io.BytesIO):
1166 first = True
1167 def write(self, data):
1168 if self.first:
1169 self.first = False
1170 raise exctype
1171
1172 f = BadFile()
1173 with self.assertRaises(exctype):
1174 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1175 format=tarfile.PAX_FORMAT,
1176 pax_headers={'non': 'empty'})
1177 self.assertFalse(f.closed)
1178
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001179class GzipWriteTest(GzipTest, WriteTest):
1180 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001181
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001182class Bz2WriteTest(Bz2Test, WriteTest):
1183 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001184
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001185class LzmaWriteTest(LzmaTest, WriteTest):
1186 pass
1187
1188
1189class StreamWriteTest(WriteTestBase, unittest.TestCase):
1190
1191 prefix = "w|"
1192 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001193
Guido van Rossumd8faa362007-04-27 19:54:29 +00001194 def test_stream_padding(self):
1195 # Test for bug #1543303.
1196 tar = tarfile.open(tmpname, self.mode)
1197 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001198 if self.decompressor:
1199 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001200 with open(tmpname, "rb") as fobj:
1201 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001202 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001203 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001204 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001205 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001206 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001207 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1208 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001209
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001210 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1211 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001212 def test_file_mode(self):
1213 # Test for issue #8464: Create files with correct
1214 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001215 if os.path.exists(tmpname):
1216 os.remove(tmpname)
1217
1218 original_umask = os.umask(0o022)
1219 try:
1220 tar = tarfile.open(tmpname, self.mode)
1221 tar.close()
1222 mode = os.stat(tmpname).st_mode & 0o777
1223 self.assertEqual(mode, 0o644, "wrong file permissions")
1224 finally:
1225 os.umask(original_umask)
1226
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001227class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1228 pass
1229
1230class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1231 decompressor = bz2.BZ2Decompressor if bz2 else None
1232
1233class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1234 decompressor = lzma.LZMADecompressor if lzma else None
1235
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001236
Guido van Rossumd8faa362007-04-27 19:54:29 +00001237class GNUWriteTest(unittest.TestCase):
1238 # This testcase checks for correct creation of GNU Longname
1239 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001240
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001241 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001242 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001243 return blocks * 512
1244
1245 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001246 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001247 count = 512
1248
1249 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001250 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001251 count += 512
1252 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001253 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001254 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001255 count += 512
1256 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001257 return count
1258
1259 def _test(self, name, link=None):
1260 tarinfo = tarfile.TarInfo(name)
1261 if link:
1262 tarinfo.linkname = link
1263 tarinfo.type = tarfile.LNKTYPE
1264
Guido van Rossumd8faa362007-04-27 19:54:29 +00001265 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001266 try:
1267 tar.format = tarfile.GNU_FORMAT
1268 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001269
Antoine Pitrou95f55602010-09-23 18:36:46 +00001270 v1 = self._calc_size(name, link)
1271 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001272 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001273 finally:
1274 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001275
Guido van Rossumd8faa362007-04-27 19:54:29 +00001276 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001277 try:
1278 member = tar.next()
1279 self.assertIsNotNone(member,
1280 "unable to read longname member")
1281 self.assertEqual(tarinfo.name, member.name,
1282 "unable to read longname member")
1283 self.assertEqual(tarinfo.linkname, member.linkname,
1284 "unable to read longname member")
1285 finally:
1286 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001287
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001288 def test_longname_1023(self):
1289 self._test(("longnam/" * 127) + "longnam")
1290
1291 def test_longname_1024(self):
1292 self._test(("longnam/" * 127) + "longname")
1293
1294 def test_longname_1025(self):
1295 self._test(("longnam/" * 127) + "longname_")
1296
1297 def test_longlink_1023(self):
1298 self._test("name", ("longlnk/" * 127) + "longlnk")
1299
1300 def test_longlink_1024(self):
1301 self._test("name", ("longlnk/" * 127) + "longlink")
1302
1303 def test_longlink_1025(self):
1304 self._test("name", ("longlnk/" * 127) + "longlink_")
1305
1306 def test_longnamelink_1023(self):
1307 self._test(("longnam/" * 127) + "longnam",
1308 ("longlnk/" * 127) + "longlnk")
1309
1310 def test_longnamelink_1024(self):
1311 self._test(("longnam/" * 127) + "longname",
1312 ("longlnk/" * 127) + "longlink")
1313
1314 def test_longnamelink_1025(self):
1315 self._test(("longnam/" * 127) + "longname_",
1316 ("longlnk/" * 127) + "longlink_")
1317
Guido van Rossumd8faa362007-04-27 19:54:29 +00001318
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001319@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001320class HardlinkTest(unittest.TestCase):
1321 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001322
1323 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001324 self.foo = os.path.join(TEMPDIR, "foo")
1325 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001326
Antoine Pitrou95f55602010-09-23 18:36:46 +00001327 with open(self.foo, "wb") as fobj:
1328 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001329
Guido van Rossumd8faa362007-04-27 19:54:29 +00001330 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001331
Guido van Rossumd8faa362007-04-27 19:54:29 +00001332 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001333 self.tar.add(self.foo)
1334
Guido van Rossumd8faa362007-04-27 19:54:29 +00001335 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001336 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001337 support.unlink(self.foo)
1338 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001339
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001340 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001341 # The same name will be added as a REGTYPE every
1342 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001343 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001344 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001345 "add file as regular failed")
1346
1347 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001348 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001349 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001350 "add file as hardlink failed")
1351
1352 def test_dereference_hardlink(self):
1353 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001354 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001355 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001356 "dereferencing hardlink failed")
1357
Neal Norwitza4f651a2004-07-20 22:07:44 +00001358
Guido van Rossumd8faa362007-04-27 19:54:29 +00001359class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001360
Guido van Rossumd8faa362007-04-27 19:54:29 +00001361 def _test(self, name, link=None):
1362 # See GNUWriteTest.
1363 tarinfo = tarfile.TarInfo(name)
1364 if link:
1365 tarinfo.linkname = link
1366 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001367
Guido van Rossumd8faa362007-04-27 19:54:29 +00001368 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001369 try:
1370 tar.addfile(tarinfo)
1371 finally:
1372 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001373
Guido van Rossumd8faa362007-04-27 19:54:29 +00001374 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001375 try:
1376 if link:
1377 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001378 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001379 else:
1380 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001381 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001382 finally:
1383 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001384
Guido van Rossume7ba4952007-06-06 23:52:48 +00001385 def test_pax_global_header(self):
1386 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001387 "foo": "bar",
1388 "uid": "0",
1389 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001390 "test": "\xe4\xf6\xfc",
1391 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001392
Benjamin Peterson886af962010-03-21 23:13:07 +00001393 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001394 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001395 try:
1396 tar.addfile(tarfile.TarInfo("test"))
1397 finally:
1398 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001399
1400 # Test if the global header was written correctly.
1401 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001402 try:
1403 self.assertEqual(tar.pax_headers, pax_headers)
1404 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1405 # Test if all the fields are strings.
1406 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001407 self.assertIsNot(type(key), bytes)
1408 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001409 if key in tarfile.PAX_NUMBER_FIELDS:
1410 try:
1411 tarfile.PAX_NUMBER_FIELDS[key](val)
1412 except (TypeError, ValueError):
1413 self.fail("unable to convert pax header field")
1414 finally:
1415 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001416
1417 def test_pax_extended_header(self):
1418 # The fields from the pax header have priority over the
1419 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001420 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001421
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001422 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1423 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001424 try:
1425 t = tarfile.TarInfo()
1426 t.name = "\xe4\xf6\xfc" # non-ASCII
1427 t.uid = 8**8 # too large
1428 t.pax_headers = pax_headers
1429 tar.addfile(t)
1430 finally:
1431 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001432
1433 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001434 try:
1435 t = tar.getmembers()[0]
1436 self.assertEqual(t.pax_headers, pax_headers)
1437 self.assertEqual(t.name, "foo")
1438 self.assertEqual(t.uid, 123)
1439 finally:
1440 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001441
1442
1443class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001444
1445 format = tarfile.USTAR_FORMAT
1446
1447 def test_iso8859_1_filename(self):
1448 self._test_unicode_filename("iso8859-1")
1449
1450 def test_utf7_filename(self):
1451 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001452
1453 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001454 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001455
Guido van Rossumd8faa362007-04-27 19:54:29 +00001456 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001457 tar = tarfile.open(tmpname, "w", format=self.format,
1458 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001459 try:
1460 name = "\xe4\xf6\xfc"
1461 tar.addfile(tarfile.TarInfo(name))
1462 finally:
1463 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001464
1465 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001466 try:
1467 self.assertEqual(tar.getmembers()[0].name, name)
1468 finally:
1469 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001470
1471 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001472 tar = tarfile.open(tmpname, "w", format=self.format,
1473 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001474 try:
1475 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001476
Antoine Pitrou95f55602010-09-23 18:36:46 +00001477 tarinfo.name = "\xe4\xf6\xfc"
1478 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001479
Antoine Pitrou95f55602010-09-23 18:36:46 +00001480 tarinfo.name = "foo"
1481 tarinfo.uname = "\xe4\xf6\xfc"
1482 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1483 finally:
1484 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001485
1486 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001487 tar = tarfile.open(tarname, "r",
1488 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001489 try:
1490 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001491 self.assertIs(type(t.name), str)
1492 self.assertIs(type(t.linkname), str)
1493 self.assertIs(type(t.uname), str)
1494 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001495 finally:
1496 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001497
Guido van Rossume7ba4952007-06-06 23:52:48 +00001498 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001499 t = tarfile.TarInfo("foo")
1500 t.uname = "\xe4\xf6\xfc"
1501 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001502
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001503 tar = tarfile.open(tmpname, mode="w", format=self.format,
1504 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001505 try:
1506 tar.addfile(t)
1507 finally:
1508 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001509
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001510 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001511 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001512 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001513 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1514 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1515
1516 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001517 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001518 tar = tarfile.open(tmpname, encoding="ascii")
1519 t = tar.getmember("foo")
1520 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1521 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1522 finally:
1523 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001524
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001525
Guido van Rossume7ba4952007-06-06 23:52:48 +00001526class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001527
Guido van Rossume7ba4952007-06-06 23:52:48 +00001528 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001529
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001530 def test_bad_pax_header(self):
1531 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1532 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001533 for encoding, name in (
1534 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001535 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001536 with tarfile.open(tarname, encoding=encoding,
1537 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001538 try:
1539 t = tar.getmember(name)
1540 except KeyError:
1541 self.fail("unable to read bad GNU tar pax header")
1542
Guido van Rossumd8faa362007-04-27 19:54:29 +00001543
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001544class PAXUnicodeTest(UstarUnicodeTest):
1545
1546 format = tarfile.PAX_FORMAT
1547
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001548 # PAX_FORMAT ignores encoding in write mode.
1549 test_unicode_filename_error = None
1550
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001551 def test_binary_header(self):
1552 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001553 for encoding, name in (
1554 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001555 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001556 with tarfile.open(tarname, encoding=encoding,
1557 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001558 try:
1559 t = tar.getmember(name)
1560 except KeyError:
1561 self.fail("unable to read POSIX.1-2008 binary header")
1562
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001563
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001564class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001565 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001566
Guido van Rossumd8faa362007-04-27 19:54:29 +00001567 def setUp(self):
1568 self.tarname = tmpname
1569 if os.path.exists(self.tarname):
1570 os.remove(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001571
Guido van Rossumd8faa362007-04-27 19:54:29 +00001572 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001573 with tarfile.open(tarname, encoding="iso8859-1") as src:
1574 t = src.getmember("ustar/regtype")
1575 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001576 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001577 with tarfile.open(self.tarname, mode) as tar:
1578 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001579
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001580 def test_append_compressed(self):
1581 self._create_testtar("w:" + self.suffix)
1582 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1583
1584class AppendTest(AppendTestBase, unittest.TestCase):
1585 test_append_compressed = None
1586
1587 def _add_testfile(self, fileobj=None):
1588 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1589 tar.addfile(tarfile.TarInfo("bar"))
1590
Guido van Rossumd8faa362007-04-27 19:54:29 +00001591 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001592 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1593 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001594
1595 def test_non_existing(self):
1596 self._add_testfile()
1597 self._test()
1598
1599 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001600 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001601 self._add_testfile()
1602 self._test()
1603
1604 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001605 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001606 self._add_testfile(fobj)
1607 fobj.seek(0)
1608 self._test(fileobj=fobj)
1609
1610 def test_fileobj(self):
1611 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001612 with open(self.tarname, "rb") as fobj:
1613 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001614 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001615 self._add_testfile(fobj)
1616 fobj.seek(0)
1617 self._test(names=["foo", "bar"], fileobj=fobj)
1618
1619 def test_existing(self):
1620 self._create_testtar()
1621 self._add_testfile()
1622 self._test(names=["foo", "bar"])
1623
Lars Gustäbel9520a432009-11-22 18:48:49 +00001624 # Append mode is supposed to fail if the tarfile to append to
1625 # does not end with a zero block.
1626 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001627 with open(self.tarname, "wb") as fobj:
1628 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001629 self.assertRaises(tarfile.ReadError, self._add_testfile)
1630
1631 def test_null(self):
1632 self._test_error(b"")
1633
1634 def test_incomplete(self):
1635 self._test_error(b"\0" * 13)
1636
1637 def test_premature_eof(self):
1638 data = tarfile.TarInfo("foo").tobuf()
1639 self._test_error(data)
1640
1641 def test_trailing_garbage(self):
1642 data = tarfile.TarInfo("foo").tobuf()
1643 self._test_error(data + b"\0" * 13)
1644
1645 def test_invalid(self):
1646 self._test_error(b"a" * 512)
1647
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001648class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
1649 pass
1650
1651class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
1652 pass
1653
1654class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
1655 pass
1656
Guido van Rossumd8faa362007-04-27 19:54:29 +00001657
1658class LimitsTest(unittest.TestCase):
1659
1660 def test_ustar_limits(self):
1661 # 100 char name
1662 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001663 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001664
1665 # 101 char name that cannot be stored
1666 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001667 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001668
1669 # 256 char name with a slash at pos 156
1670 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001671 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001672
1673 # 256 char name that cannot be stored
1674 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001675 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001676
1677 # 512 char name
1678 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001679 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001680
1681 # 512 char linkname
1682 tarinfo = tarfile.TarInfo("longlink")
1683 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001684 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001685
1686 # uid > 8 digits
1687 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001688 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001689 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001690
1691 def test_gnu_limits(self):
1692 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001693 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001694
1695 tarinfo = tarfile.TarInfo("longlink")
1696 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001697 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001698
1699 # uid >= 256 ** 7
1700 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001701 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001702 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001703
1704 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001705 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001706 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001707
1708 tarinfo = tarfile.TarInfo("longlink")
1709 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001710 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001711
1712 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001713 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001714 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001715
1716
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001717class MiscTest(unittest.TestCase):
1718
1719 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001720 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
1721 b"foo\0\0\0\0\0")
1722 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
1723 b"foo")
1724 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
1725 "foo")
1726 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
1727 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001728
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001729 def test_read_number_fields(self):
1730 # Issue 13158: Test if GNU tar specific base-256 number fields
1731 # are decoded correctly.
1732 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1733 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001734 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
1735 0o10000000)
1736 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
1737 0xffffffff)
1738 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
1739 -1)
1740 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
1741 -100)
1742 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
1743 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001744
1745 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001746 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001747 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001748 self.assertEqual(tarfile.itn(0o10000000),
1749 b"\x80\x00\x00\x00\x00\x20\x00\x00")
1750 self.assertEqual(tarfile.itn(0xffffffff),
1751 b"\x80\x00\x00\x00\xff\xff\xff\xff")
1752 self.assertEqual(tarfile.itn(-1),
1753 b"\xff\xff\xff\xff\xff\xff\xff\xff")
1754 self.assertEqual(tarfile.itn(-100),
1755 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1756 self.assertEqual(tarfile.itn(-0x100000000000000),
1757 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001758
1759 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001760 with self.assertRaises(ValueError):
1761 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
1762 with self.assertRaises(ValueError):
1763 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
1764 with self.assertRaises(ValueError):
1765 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
1766 with self.assertRaises(ValueError):
1767 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001768
1769
Lars Gustäbel01385812010-03-03 12:08:54 +00001770class ContextManagerTest(unittest.TestCase):
1771
1772 def test_basic(self):
1773 with tarfile.open(tarname) as tar:
1774 self.assertFalse(tar.closed, "closed inside runtime context")
1775 self.assertTrue(tar.closed, "context manager failed")
1776
1777 def test_closed(self):
1778 # The __enter__() method is supposed to raise IOError
1779 # if the TarFile object is already closed.
1780 tar = tarfile.open(tarname)
1781 tar.close()
1782 with self.assertRaises(IOError):
1783 with tar:
1784 pass
1785
1786 def test_exception(self):
1787 # Test if the IOError exception is passed through properly.
1788 with self.assertRaises(Exception) as exc:
1789 with tarfile.open(tarname) as tar:
1790 raise IOError
1791 self.assertIsInstance(exc.exception, IOError,
1792 "wrong exception raised in context manager")
1793 self.assertTrue(tar.closed, "context manager failed")
1794
1795 def test_no_eof(self):
1796 # __exit__() must not write end-of-archive blocks if an
1797 # exception was raised.
1798 try:
1799 with tarfile.open(tmpname, "w") as tar:
1800 raise Exception
1801 except:
1802 pass
1803 self.assertEqual(os.path.getsize(tmpname), 0,
1804 "context manager wrote an end-of-archive block")
1805 self.assertTrue(tar.closed, "context manager failed")
1806
1807 def test_eof(self):
1808 # __exit__() must write end-of-archive blocks, i.e. call
1809 # TarFile.close() if there was no error.
1810 with tarfile.open(tmpname, "w"):
1811 pass
1812 self.assertNotEqual(os.path.getsize(tmpname), 0,
1813 "context manager wrote no end-of-archive block")
1814
1815 def test_fileobj(self):
1816 # Test that __exit__() did not close the external file
1817 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00001818 with open(tmpname, "wb") as fobj:
1819 try:
1820 with tarfile.open(fileobj=fobj, mode="w") as tar:
1821 raise Exception
1822 except:
1823 pass
1824 self.assertFalse(fobj.closed, "external file object was closed")
1825 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00001826
1827
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001828@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
1829class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00001830
1831 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001832 # symbolic or hard links tarfile tries to extract these types of members
1833 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00001834 def _test_link_extraction(self, name):
1835 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001836 with open(os.path.join(TEMPDIR, name), "rb") as f:
1837 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00001838 self.assertEqual(md5sum(data), md5_regtype)
1839
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001840 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00001841 @unittest.skipIf(hasattr(os.path, "islink"),
1842 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001843 def test_hardlink_extraction1(self):
1844 self._test_link_extraction("ustar/lnktype")
1845
Brian Curtind40e6f72010-07-08 21:39:08 +00001846 @unittest.skipIf(hasattr(os.path, "islink"),
1847 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001848 def test_hardlink_extraction2(self):
1849 self._test_link_extraction("./ustar/linktest2/lnktype")
1850
Brian Curtin74e45612010-07-09 15:58:59 +00001851 @unittest.skipIf(hasattr(os, "symlink"),
1852 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001853 def test_symlink_extraction1(self):
1854 self._test_link_extraction("ustar/symtype")
1855
Brian Curtin74e45612010-07-09 15:58:59 +00001856 @unittest.skipIf(hasattr(os, "symlink"),
1857 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00001858 def test_symlink_extraction2(self):
1859 self._test_link_extraction("./ustar/linktest2/symtype")
1860
1861
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001862class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00001863 # Issue5068: The _BZ2Proxy.read() method loops forever
1864 # on an empty or partial bzipped file.
1865
1866 def _test_partial_input(self, mode):
1867 class MyBytesIO(io.BytesIO):
1868 hit_eof = False
1869 def read(self, n):
1870 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001871 raise AssertionError("infinite loop detected in "
1872 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00001873 self.hit_eof = self.tell() == len(self.getvalue())
1874 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001875 def seek(self, *args):
1876 self.hit_eof = False
1877 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00001878
1879 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
1880 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001881 try:
1882 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
1883 except tarfile.ReadError:
1884 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00001885
1886 def test_partial_input(self):
1887 self._test_partial_input("r")
1888
1889 def test_partial_input_bz2(self):
1890 self._test_partial_input("r:bz2")
1891
1892
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001893def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00001894 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00001895 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001896
Antoine Pitrou95f55602010-09-23 18:36:46 +00001897 with open(tarname, "rb") as fobj:
1898 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00001899
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001900 # Create compressed tarfiles.
1901 for c in GzipTest, Bz2Test, LzmaTest:
1902 if c.open:
1903 support.unlink(c.tarname)
1904 with c.open(c.tarname, "wb") as tar:
1905 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001906
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001907def tearDownModule():
1908 if os.path.exists(TEMPDIR):
1909 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001910
Neal Norwitz996acf12003-02-17 14:51:41 +00001911if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001912 unittest.main()