blob: fc79055421161c917fab9e4f3e6b70637d818444 [file] [log] [blame]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001import sys
2import os
Lars Gustäbelb506dc32007-08-07 18:36:16 +00003import io
Guido van Rossuma8add0e2007-05-14 22:03:55 +00004from hashlib import md5
Eric V. Smith7a803892015-04-15 10:27:58 -04005from contextlib import contextmanager
Serhiy Storchakaa89d22a2016-10-30 20:52:29 +02006from random import Random
Serhiy Storchaka666165f2017-03-08 12:29:33 +02007import pathlib
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00008
9import unittest
Eric V. Smith7a803892015-04-15 10:27:58 -040010import unittest.mock
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000011import tarfile
12
Berker Peksagce643912015-05-06 06:33:17 +030013from test import support
14from test.support import script_helper
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000015
16# Check for our compression modules.
17try:
18 import gzip
Brett Cannon260fbe82013-07-04 18:16:15 -040019except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000020 gzip = None
21try:
22 import bz2
Brett Cannon260fbe82013-07-04 18:16:15 -040023except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000024 bz2 = None
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010025try:
26 import lzma
Brett Cannon260fbe82013-07-04 18:16:15 -040027except ImportError:
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010028 lzma = None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000029
Guido van Rossumd8faa362007-04-27 19:54:29 +000030def md5sum(data):
Guido van Rossuma8add0e2007-05-14 22:03:55 +000031 return md5(data).hexdigest()
Guido van Rossumd8faa362007-04-27 19:54:29 +000032
Antoine Pitrouab58b5f2010-09-23 19:39:35 +000033TEMPDIR = os.path.abspath(support.TESTFN) + "-tardir"
Serhiy Storchakad27b4552013-11-24 01:53:29 +020034tarextdir = TEMPDIR + '-extract-test'
Antoine Pitrou941ee882009-11-11 20:59:38 +000035tarname = support.findfile("testtar.tar")
Guido van Rossumd8faa362007-04-27 19:54:29 +000036gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
37bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010038xzname = os.path.join(TEMPDIR, "testtar.tar.xz")
Guido van Rossumd8faa362007-04-27 19:54:29 +000039tmpname = os.path.join(TEMPDIR, "tmp.tar")
Serhiy Storchakad27b4552013-11-24 01:53:29 +020040dotlessname = os.path.join(TEMPDIR, "testtar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000041
Guido van Rossumd8faa362007-04-27 19:54:29 +000042md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
43md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000044
45
Serhiy Storchaka8b562922013-06-17 15:38:50 +030046class TarTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +000047 tarname = tarname
Serhiy Storchaka8b562922013-06-17 15:38:50 +030048 suffix = ''
49 open = io.FileIO
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020050 taropen = tarfile.TarFile.taropen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030051
52 @property
53 def mode(self):
54 return self.prefix + self.suffix
55
56@support.requires_gzip
57class GzipTest:
58 tarname = gzipname
59 suffix = 'gz'
60 open = gzip.GzipFile if gzip else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020061 taropen = tarfile.TarFile.gzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030062
63@support.requires_bz2
64class Bz2Test:
65 tarname = bz2name
66 suffix = 'bz2'
67 open = bz2.BZ2File if bz2 else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020068 taropen = tarfile.TarFile.bz2open
Serhiy Storchaka8b562922013-06-17 15:38:50 +030069
70@support.requires_lzma
71class LzmaTest:
72 tarname = xzname
73 suffix = 'xz'
74 open = lzma.LZMAFile if lzma else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020075 taropen = tarfile.TarFile.xzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030076
77
78class ReadTest(TarTest):
79
80 prefix = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000081
82 def setUp(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +030083 self.tar = tarfile.open(self.tarname, mode=self.mode,
84 encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000085
86 def tearDown(self):
87 self.tar.close()
88
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000089
Serhiy Storchaka8b562922013-06-17 15:38:50 +030090class UstarReadTest(ReadTest, unittest.TestCase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000091
Guido van Rossumd8faa362007-04-27 19:54:29 +000092 def test_fileobj_regular_file(self):
93 tarinfo = self.tar.getmember("ustar/regtype")
Lars Gustäbel7a919e92012-05-05 18:15:03 +020094 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000095 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +030096 self.assertEqual(len(data), tarinfo.size,
97 "regular file extraction failed")
98 self.assertEqual(md5sum(data), md5_regtype,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000099 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000100
Guido van Rossumd8faa362007-04-27 19:54:29 +0000101 def test_fileobj_readlines(self):
102 self.tar.extract("ustar/regtype", TEMPDIR)
103 tarinfo = self.tar.getmember("ustar/regtype")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000104 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
105 lines1 = fobj1.readlines()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000106
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200107 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000108 fobj2 = io.TextIOWrapper(fobj)
109 lines2 = fobj2.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300110 self.assertEqual(lines1, lines2,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000111 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300112 self.assertEqual(len(lines2), 114,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000113 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300114 self.assertEqual(lines2[83],
115 "I will gladly admit that Python is not the fastest "
116 "running scripting language.\n",
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000117 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000118
Guido van Rossumd8faa362007-04-27 19:54:29 +0000119 def test_fileobj_iter(self):
120 self.tar.extract("ustar/regtype", TEMPDIR)
121 tarinfo = self.tar.getmember("ustar/regtype")
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200122 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000123 lines1 = fobj1.readlines()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200124 with self.tar.extractfile(tarinfo) as fobj2:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000125 lines2 = list(io.TextIOWrapper(fobj2))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300126 self.assertEqual(lines1, lines2,
127 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +0000128
Guido van Rossumd8faa362007-04-27 19:54:29 +0000129 def test_fileobj_seek(self):
130 self.tar.extract("ustar/regtype", TEMPDIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000131 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
132 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +0000133
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134 tarinfo = self.tar.getmember("ustar/regtype")
135 fobj = self.tar.extractfile(tarinfo)
136
137 text = fobj.read()
138 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000139 self.assertEqual(0, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000140 "seek() to file's start failed")
141 fobj.seek(2048, 0)
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 absolute position failed")
144 fobj.seek(-1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000145 self.assertEqual(1024, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000146 "seek() to negative relative position failed")
147 fobj.seek(1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000148 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000149 "seek() to positive relative position failed")
150 s = fobj.read(10)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300151 self.assertEqual(s, data[2048:2058],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000152 "read() after seek failed")
153 fobj.seek(0, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000154 self.assertEqual(tarinfo.size, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155 "seek() to file's end failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300156 self.assertEqual(fobj.read(), b"",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000157 "read() at file's end did not return empty string")
158 fobj.seek(-tarinfo.size, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000159 self.assertEqual(0, fobj.tell(),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000160 "relative seek() to file's end failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161 fobj.seek(512)
162 s1 = fobj.readlines()
163 fobj.seek(512)
164 s2 = fobj.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300165 self.assertEqual(s1, s2,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000166 "readlines() after seek failed")
167 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000168 self.assertEqual(len(fobj.readline()), fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000169 "tell() after readline() failed")
170 fobj.seek(512)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300171 self.assertEqual(len(fobj.readline()) + 512, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000172 "tell() after seek() and readline() failed")
173 fobj.seek(0)
174 line = fobj.readline()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000175 self.assertEqual(fobj.read(), data[len(line):],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000176 "read() after readline() failed")
177 fobj.close()
178
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200179 def test_fileobj_text(self):
180 with self.tar.extractfile("ustar/regtype") as fobj:
181 fobj = io.TextIOWrapper(fobj)
182 data = fobj.read().encode("iso8859-1")
183 self.assertEqual(md5sum(data), md5_regtype)
184 try:
185 fobj.seek(100)
186 except AttributeError:
187 # Issue #13815: seek() complained about a missing
188 # flush() method.
189 self.fail("seeking failed in text mode")
190
Lars Gustäbel1b512722010-06-03 12:45:16 +0000191 # Test if symbolic and hard links are resolved by extractfile(). The
192 # test link members each point to a regular member whose data is
193 # supposed to be exported.
194 def _test_fileobj_link(self, lnktype, regtype):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300195 with self.tar.extractfile(lnktype) as a, \
196 self.tar.extractfile(regtype) as b:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000197 self.assertEqual(a.name, b.name)
Lars Gustäbel1b512722010-06-03 12:45:16 +0000198
199 def test_fileobj_link1(self):
200 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
201
202 def test_fileobj_link2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300203 self._test_fileobj_link("./ustar/linktest2/lnktype",
204 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000205
206 def test_fileobj_symlink1(self):
207 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
208
209 def test_fileobj_symlink2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300210 self._test_fileobj_link("./ustar/linktest2/symtype",
211 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000212
Lars Gustäbel1ef9eda2012-04-24 21:04:40 +0200213 def test_issue14160(self):
214 self._test_fileobj_link("symtype2", "ustar/regtype")
215
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300216class GzipUstarReadTest(GzipTest, UstarReadTest):
217 pass
218
219class Bz2UstarReadTest(Bz2Test, UstarReadTest):
220 pass
221
222class LzmaUstarReadTest(LzmaTest, UstarReadTest):
223 pass
224
Guido van Rossumd8faa362007-04-27 19:54:29 +0000225
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200226class ListTest(ReadTest, unittest.TestCase):
227
228 # Override setUp to use default encoding (UTF-8)
229 def setUp(self):
230 self.tar = tarfile.open(self.tarname, mode=self.mode)
231
232 def test_list(self):
233 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
234 with support.swap_attr(sys, 'stdout', tio):
235 self.tar.list(verbose=False)
236 out = tio.detach().getvalue()
237 self.assertIn(b'ustar/conttype', out)
238 self.assertIn(b'ustar/regtype', out)
239 self.assertIn(b'ustar/lnktype', out)
240 self.assertIn(b'ustar' + (b'/12345' * 40) + b'67/longname', out)
241 self.assertIn(b'./ustar/linktest2/symtype', out)
242 self.assertIn(b'./ustar/linktest2/lnktype', out)
243 # Make sure it puts trailing slash for directory
244 self.assertIn(b'ustar/dirtype/', out)
245 self.assertIn(b'ustar/dirtype-with-size/', out)
246 # Make sure it is able to print unencodable characters
Serhiy Storchaka162c4772014-02-19 18:44:12 +0200247 def conv(b):
248 s = b.decode(self.tar.encoding, 'surrogateescape')
249 return s.encode('ascii', 'backslashreplace')
250 self.assertIn(conv(b'ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
251 self.assertIn(conv(b'misc/regtype-hpux-signed-chksum-'
252 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
253 self.assertIn(conv(b'misc/regtype-old-v7-signed-chksum-'
254 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
255 self.assertIn(conv(b'pax/bad-pax-\xe4\xf6\xfc'), out)
256 self.assertIn(conv(b'pax/hdrcharset-\xe4\xf6\xfc'), out)
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200257 # Make sure it prints files separated by one newline without any
258 # 'ls -l'-like accessories if verbose flag is not being used
259 # ...
260 # ustar/conttype
261 # ustar/regtype
262 # ...
263 self.assertRegex(out, br'ustar/conttype ?\r?\n'
264 br'ustar/regtype ?\r?\n')
265 # Make sure it does not print the source of link without verbose flag
266 self.assertNotIn(b'link to', out)
267 self.assertNotIn(b'->', out)
268
269 def test_list_verbose(self):
270 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
271 with support.swap_attr(sys, 'stdout', tio):
272 self.tar.list(verbose=True)
273 out = tio.detach().getvalue()
274 # Make sure it prints files separated by one newline with 'ls -l'-like
275 # accessories if verbose flag is being used
276 # ...
277 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
278 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
279 # ...
Serhiy Storchaka255493c2014-02-05 20:54:43 +0200280 self.assertRegex(out, (br'\?rw-r--r-- tarfile/tarfile\s+7011 '
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200281 br'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
282 br'ustar/\w+type ?\r?\n') * 2)
283 # Make sure it prints the source of link with verbose flag
284 self.assertIn(b'ustar/symtype -> regtype', out)
285 self.assertIn(b'./ustar/linktest2/symtype -> ../linktest1/regtype', out)
286 self.assertIn(b'./ustar/linktest2/lnktype link to '
287 b'./ustar/linktest1/regtype', out)
288 self.assertIn(b'gnu' + (b'/123' * 125) + b'/longlink link to gnu' +
289 (b'/123' * 125) + b'/longname', out)
290 self.assertIn(b'pax' + (b'/123' * 125) + b'/longlink link to pax' +
291 (b'/123' * 125) + b'/longname', out)
292
Serhiy Storchakaa7eb7462014-08-21 10:01:16 +0300293 def test_list_members(self):
294 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
295 def members(tar):
296 for tarinfo in tar.getmembers():
297 if 'reg' in tarinfo.name:
298 yield tarinfo
299 with support.swap_attr(sys, 'stdout', tio):
300 self.tar.list(verbose=False, members=members(self.tar))
301 out = tio.detach().getvalue()
302 self.assertIn(b'ustar/regtype', out)
303 self.assertNotIn(b'ustar/conttype', out)
304
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200305
306class GzipListTest(GzipTest, ListTest):
307 pass
308
309
310class Bz2ListTest(Bz2Test, ListTest):
311 pass
312
313
314class LzmaListTest(LzmaTest, ListTest):
315 pass
316
317
Lars Gustäbel9520a432009-11-22 18:48:49 +0000318class CommonReadTest(ReadTest):
319
320 def test_empty_tarfile(self):
321 # Test for issue6123: Allow opening empty archives.
322 # This test checks if tarfile.open() is able to open an empty tar
323 # archive successfully. Note that an empty tar archive is not the
324 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000325 with tarfile.open(tmpname, self.mode.replace("r", "w")):
326 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000327 try:
328 tar = tarfile.open(tmpname, self.mode)
329 tar.getnames()
330 except tarfile.ReadError:
331 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000332 else:
333 self.assertListEqual(tar.getmembers(), [])
334 finally:
335 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000336
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200337 def test_non_existent_tarfile(self):
338 # Test for issue11513: prevent non-existent gzipped tarfiles raising
339 # multiple exceptions.
340 with self.assertRaisesRegex(FileNotFoundError, "xxx"):
341 tarfile.open("xxx", self.mode)
342
Lars Gustäbel9520a432009-11-22 18:48:49 +0000343 def test_null_tarfile(self):
344 # Test for issue6123: Allow opening empty archives.
345 # This test guarantees that tarfile.open() does not treat an empty
346 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000347 with open(tmpname, "wb"):
348 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000349 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
350 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
351
352 def test_ignore_zeros(self):
353 # Test TarFile's ignore_zeros option.
Serhiy Storchakaa89d22a2016-10-30 20:52:29 +0200354 # generate 512 pseudorandom bytes
355 data = Random(0).getrandbits(512*8).to_bytes(512, 'big')
Lars Gustäbel9520a432009-11-22 18:48:49 +0000356 for char in (b'\0', b'a'):
357 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
358 # are ignored correctly.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300359 with self.open(tmpname, "w") as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000360 fobj.write(char * 1024)
Serhiy Storchakaa89d22a2016-10-30 20:52:29 +0200361 tarinfo = tarfile.TarInfo("foo")
362 tarinfo.size = len(data)
363 fobj.write(tarinfo.tobuf())
364 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +0000365
366 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000367 try:
368 self.assertListEqual(tar.getnames(), ["foo"],
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300369 "ignore_zeros=True should have skipped the %r-blocks" %
370 char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000371 finally:
372 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000373
Lars Gustäbel03572682015-07-06 09:27:24 +0200374 def test_premature_end_of_archive(self):
375 for size in (512, 600, 1024, 1200):
376 with tarfile.open(tmpname, "w:") as tar:
377 t = tarfile.TarInfo("foo")
378 t.size = 1024
379 tar.addfile(t, io.BytesIO(b"a" * 1024))
380
381 with open(tmpname, "r+b") as fobj:
382 fobj.truncate(size)
383
384 with tarfile.open(tmpname) as tar:
385 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
386 for t in tar:
387 pass
388
389 with tarfile.open(tmpname) as tar:
390 t = tar.next()
391
392 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
393 tar.extract(t, TEMPDIR)
394
395 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
396 tar.extractfile(t).read()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000397
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300398class MiscReadTestBase(CommonReadTest):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300399 def requires_name_attribute(self):
400 pass
401
Thomas Woutersed03b412007-08-28 21:37:11 +0000402 def test_no_name_argument(self):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300403 self.requires_name_attribute()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000404 with open(self.tarname, "rb") as fobj:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300405 self.assertIsInstance(fobj.name, str)
406 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
407 self.assertIsInstance(tar.name, str)
408 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000409
Thomas Woutersed03b412007-08-28 21:37:11 +0000410 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000411 with open(self.tarname, "rb") as fobj:
412 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000413 fobj = io.BytesIO(data)
414 self.assertRaises(AttributeError, getattr, fobj, "name")
415 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300416 self.assertIsNone(tar.name)
Thomas Woutersed03b412007-08-28 21:37:11 +0000417
418 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000419 with open(self.tarname, "rb") as fobj:
420 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000421 fobj = io.BytesIO(data)
422 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000423 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300424 self.assertIsNone(tar.name)
425
426 def test_int_name_attribute(self):
427 # Issue 21044: tarfile.open() should handle fileobj with an integer
428 # 'name' attribute.
429 fd = os.open(self.tarname, os.O_RDONLY)
430 with open(fd, 'rb') as fobj:
431 self.assertIsInstance(fobj.name, int)
432 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
433 self.assertIsNone(tar.name)
434
435 def test_bytes_name_attribute(self):
436 self.requires_name_attribute()
437 tarname = os.fsencode(self.tarname)
438 with open(tarname, 'rb') as fobj:
439 self.assertIsInstance(fobj.name, bytes)
440 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
441 self.assertIsInstance(tar.name, bytes)
442 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Thomas Woutersed03b412007-08-28 21:37:11 +0000443
Serhiy Storchaka666165f2017-03-08 12:29:33 +0200444 def test_pathlike_name(self):
445 tarname = pathlib.Path(self.tarname)
446 with tarfile.open(tarname, mode=self.mode) as tar:
447 self.assertIsInstance(tar.name, str)
448 self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
449 with self.taropen(tarname) as tar:
450 self.assertIsInstance(tar.name, str)
451 self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
452 with tarfile.TarFile.open(tarname, mode=self.mode) as tar:
453 self.assertIsInstance(tar.name, str)
454 self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
455 if self.suffix == '':
456 with tarfile.TarFile(tarname, mode='r') as tar:
457 self.assertIsInstance(tar.name, str)
458 self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
459
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +0200460 def test_illegal_mode_arg(self):
461 with open(tmpname, 'wb'):
462 pass
463 with self.assertRaisesRegex(ValueError, 'mode must be '):
464 tar = self.taropen(tmpname, 'q')
465 with self.assertRaisesRegex(ValueError, 'mode must be '):
466 tar = self.taropen(tmpname, 'rw')
467 with self.assertRaisesRegex(ValueError, 'mode must be '):
468 tar = self.taropen(tmpname, '')
469
Christian Heimesd8654cf2007-12-02 15:22:16 +0000470 def test_fileobj_with_offset(self):
471 # Skip the first member and store values from the second member
472 # of the testtar.
473 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000474 try:
475 tar.next()
476 t = tar.next()
477 name = t.name
478 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200479 with tar.extractfile(t) as f:
480 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000481 finally:
482 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000483
484 # Open the testtar and seek to the offset of the second member.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300485 with self.open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000486 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000487
Antoine Pitrou95f55602010-09-23 18:36:46 +0000488 # Test if the tarfile starts with the second member.
489 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
490 t = tar.next()
491 self.assertEqual(t.name, name)
492 # Read to the end of fileobj and test if seeking back to the
493 # beginning works.
494 tar.getmembers()
495 self.assertEqual(tar.extractfile(t).read(), data,
496 "seek back did not work")
497 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000498
Guido van Rossumd8faa362007-04-27 19:54:29 +0000499 def test_fail_comp(self):
500 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000502 with open(tarname, "rb") as fobj:
503 self.assertRaises(tarfile.ReadError, tarfile.open,
504 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505
506 def test_v7_dirtype(self):
507 # Test old style dirtype member (bug #1336623):
508 # Old V7 tars create directory members using an AREGTYPE
509 # header with a "/" appended to the filename field.
510 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300511 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000512 "v7 dirtype failed")
513
Christian Heimes126d29a2008-02-11 22:57:17 +0000514 def test_xstar_type(self):
515 # The xstar format stores extra atime and ctime fields inside the
516 # space reserved for the prefix field. The prefix field must be
517 # ignored in this case, otherwise it will mess up the name.
518 try:
519 self.tar.getmember("misc/regtype-xstar")
520 except KeyError:
521 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
522
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523 def test_check_members(self):
524 for tarinfo in self.tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300525 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526 "wrong mtime for %s" % tarinfo.name)
527 if not tarinfo.name.startswith("ustar/"):
528 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300529 self.assertEqual(tarinfo.uname, "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000530 "wrong uname for %s" % tarinfo.name)
531
532 def test_find_members(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300533 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000534 "could not find all members")
535
Brian Curtin74e45612010-07-09 15:58:59 +0000536 @unittest.skipUnless(hasattr(os, "link"),
537 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000538 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000539 def test_extract_hardlink(self):
540 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200541 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000542 tar.extract("ustar/regtype", TEMPDIR)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100543 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000544
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200545 tar.extract("ustar/lnktype", TEMPDIR)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100546 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000547 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
548 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000549 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000550
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200551 tar.extract("ustar/symtype", TEMPDIR)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100552 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000553 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
554 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000555 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000556
Christian Heimesfaf2f632008-01-06 16:59:19 +0000557 def test_extractall(self):
558 # Test if extractall() correctly restores directory permissions
559 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000560 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000561 DIR = os.path.join(TEMPDIR, "extractall")
562 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000563 try:
564 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000565 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000566 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000567 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000568 if sys.platform != "win32":
569 # Win32 has no support for fine grained permissions.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300570 self.assertEqual(tarinfo.mode & 0o777,
571 os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000572 def format_mtime(mtime):
573 if isinstance(mtime, float):
574 return "{} ({})".format(mtime, mtime.hex())
575 else:
576 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000577 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000578 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
579 format_mtime(tarinfo.mtime),
580 format_mtime(file_mtime),
581 path)
582 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000583 finally:
584 tar.close()
Tim Goldene0bd2c52014-05-06 13:24:26 +0100585 support.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000586
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000587 def test_extract_directory(self):
588 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000589 DIR = os.path.join(TEMPDIR, "extractdir")
590 os.mkdir(DIR)
591 try:
592 with tarfile.open(tarname, encoding="iso8859-1") as tar:
593 tarinfo = tar.getmember(dirtype)
594 tar.extract(tarinfo, path=DIR)
595 extracted = os.path.join(DIR, dirtype)
596 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
597 if sys.platform != "win32":
598 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
599 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +0100600 support.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000601
Serhiy Storchaka666165f2017-03-08 12:29:33 +0200602 def test_extractall_pathlike_name(self):
603 DIR = pathlib.Path(TEMPDIR) / "extractall"
604 with support.temp_dir(DIR), \
605 tarfile.open(tarname, encoding="iso8859-1") as tar:
606 directories = [t for t in tar if t.isdir()]
607 tar.extractall(DIR, directories)
608 for tarinfo in directories:
609 path = DIR / tarinfo.name
610 self.assertEqual(os.path.getmtime(path), tarinfo.mtime)
611
612 def test_extract_pathlike_name(self):
613 dirtype = "ustar/dirtype"
614 DIR = pathlib.Path(TEMPDIR) / "extractall"
615 with support.temp_dir(DIR), \
616 tarfile.open(tarname, encoding="iso8859-1") as tar:
617 tarinfo = tar.getmember(dirtype)
618 tar.extract(tarinfo, path=DIR)
619 extracted = DIR / dirtype
620 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
621
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000622 def test_init_close_fobj(self):
623 # Issue #7341: Close the internal file object in the TarFile
624 # constructor in case of an error. For the test we rely on
625 # the fact that opening an empty file raises a ReadError.
626 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000627 with open(empty, "wb") as fobj:
628 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000629
630 try:
631 tar = object.__new__(tarfile.TarFile)
632 try:
633 tar.__init__(empty)
634 except tarfile.ReadError:
635 self.assertTrue(tar.fileobj.closed)
636 else:
637 self.fail("ReadError not raised")
638 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000639 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000640
Serhiy Storchaka263fab92013-05-09 14:22:26 +0300641 def test_parallel_iteration(self):
642 # Issue #16601: Restarting iteration over tarfile continued
643 # from where it left off.
644 with tarfile.open(self.tarname) as tar:
645 for m1, m2 in zip(tar, tar):
646 self.assertEqual(m1.offset, m2.offset)
647 self.assertEqual(m1.get_info(), m2.get_info())
648
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300649class MiscReadTest(MiscReadTestBase, unittest.TestCase):
650 test_fail_comp = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000651
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300652class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200653 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000654
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300655class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300656 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300657 self.skipTest("BZ2File have no name attribute")
658
659class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300660 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300661 self.skipTest("LZMAFile have no name attribute")
662
663
664class StreamReadTest(CommonReadTest, unittest.TestCase):
665
666 prefix="r|"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000667
Lars Gustäbeldd071042011-02-23 11:42:22 +0000668 def test_read_through(self):
669 # Issue #11224: A poorly designed _FileInFile.read() method
670 # caused seeking errors with stream tar files.
671 for tarinfo in self.tar:
672 if not tarinfo.isreg():
673 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200674 with self.tar.extractfile(tarinfo) as fobj:
675 while True:
676 try:
677 buf = fobj.read(512)
678 except tarfile.StreamError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300679 self.fail("simple read-through using "
680 "TarFile.extractfile() failed")
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200681 if not buf:
682 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000683
Guido van Rossumd8faa362007-04-27 19:54:29 +0000684 def test_fileobj_regular_file(self):
685 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200686 with self.tar.extractfile(tarinfo) as fobj:
687 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300688 self.assertEqual(len(data), tarinfo.size,
689 "regular file extraction failed")
690 self.assertEqual(md5sum(data), md5_regtype,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691 "regular file extraction failed")
692
693 def test_provoke_stream_error(self):
694 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200695 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
696 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000697
Guido van Rossumd8faa362007-04-27 19:54:29 +0000698 def test_compare_members(self):
699 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000700 try:
701 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000702
Antoine Pitrou95f55602010-09-23 18:36:46 +0000703 while True:
704 t1 = tar1.next()
705 t2 = tar2.next()
706 if t1 is None:
707 break
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300708 self.assertIsNotNone(t2, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000709
Antoine Pitrou95f55602010-09-23 18:36:46 +0000710 if t2.islnk() or t2.issym():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300711 with self.assertRaises(tarfile.StreamError):
712 tar2.extractfile(t2)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000713 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000714
Antoine Pitrou95f55602010-09-23 18:36:46 +0000715 v1 = tar1.extractfile(t1)
716 v2 = tar2.extractfile(t2)
717 if v1 is None:
718 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300719 self.assertIsNotNone(v2, "stream.extractfile() failed")
720 self.assertEqual(v1.read(), v2.read(),
721 "stream extraction failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000722 finally:
723 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000724
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300725class GzipStreamReadTest(GzipTest, StreamReadTest):
726 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000727
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300728class Bz2StreamReadTest(Bz2Test, StreamReadTest):
729 pass
Thomas Wouterscf297e42007-02-23 15:07:44 +0000730
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300731class LzmaStreamReadTest(LzmaTest, StreamReadTest):
732 pass
733
734
735class DetectReadTest(TarTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000736 def _testfunc_file(self, name, mode):
737 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000738 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000739 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000740 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000741 else:
742 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000743
Guido van Rossumd8faa362007-04-27 19:54:29 +0000744 def _testfunc_fileobj(self, name, mode):
745 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000746 with open(name, "rb") as f:
747 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000748 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000749 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000750 else:
751 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000752
753 def _test_modes(self, testfunc):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300754 if self.suffix:
755 with self.assertRaises(tarfile.ReadError):
756 tarfile.open(tarname, mode="r:" + self.suffix)
757 with self.assertRaises(tarfile.ReadError):
758 tarfile.open(tarname, mode="r|" + self.suffix)
759 with self.assertRaises(tarfile.ReadError):
760 tarfile.open(self.tarname, mode="r:")
761 with self.assertRaises(tarfile.ReadError):
762 tarfile.open(self.tarname, mode="r|")
763 testfunc(self.tarname, "r")
764 testfunc(self.tarname, "r:" + self.suffix)
765 testfunc(self.tarname, "r:*")
766 testfunc(self.tarname, "r|" + self.suffix)
767 testfunc(self.tarname, "r|*")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100768
Guido van Rossumd8faa362007-04-27 19:54:29 +0000769 def test_detect_file(self):
770 self._test_modes(self._testfunc_file)
771
772 def test_detect_fileobj(self):
773 self._test_modes(self._testfunc_fileobj)
774
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300775class GzipDetectReadTest(GzipTest, DetectReadTest):
776 pass
777
778class Bz2DetectReadTest(Bz2Test, DetectReadTest):
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100779 def test_detect_stream_bz2(self):
780 # Originally, tarfile's stream detection looked for the string
781 # "BZh91" at the start of the file. This is incorrect because
782 # the '9' represents the blocksize (900kB). If the file was
783 # compressed using another blocksize autodetection fails.
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100784 with open(tarname, "rb") as fobj:
785 data = fobj.read()
786
787 # Compress with blocksize 100kB, the file starts with "BZh11".
788 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
789 fobj.write(data)
790
791 self._testfunc_file(tmpname, "r|*")
792
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300793class LzmaDetectReadTest(LzmaTest, DetectReadTest):
794 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300796
797class MemberReadTest(ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000798
799 def _test_member(self, tarinfo, chksum=None, **kwargs):
800 if chksum is not None:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300801 with self.tar.extractfile(tarinfo) as f:
802 self.assertEqual(md5sum(f.read()), chksum,
803 "wrong md5sum for %s" % tarinfo.name)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000804
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000805 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000806 kwargs["uid"] = 1000
807 kwargs["gid"] = 100
808 if "old-v7" not in tarinfo.name:
809 # V7 tar can't handle alphabetic owners.
810 kwargs["uname"] = "tarfile"
811 kwargs["gname"] = "tarfile"
812 for k, v in kwargs.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300813 self.assertEqual(getattr(tarinfo, k), v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000814 "wrong value in %s field of %s" % (k, tarinfo.name))
815
816 def test_find_regtype(self):
817 tarinfo = self.tar.getmember("ustar/regtype")
818 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
819
820 def test_find_conttype(self):
821 tarinfo = self.tar.getmember("ustar/conttype")
822 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
823
824 def test_find_dirtype(self):
825 tarinfo = self.tar.getmember("ustar/dirtype")
826 self._test_member(tarinfo, size=0)
827
828 def test_find_dirtype_with_size(self):
829 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
830 self._test_member(tarinfo, size=255)
831
832 def test_find_lnktype(self):
833 tarinfo = self.tar.getmember("ustar/lnktype")
834 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
835
836 def test_find_symtype(self):
837 tarinfo = self.tar.getmember("ustar/symtype")
838 self._test_member(tarinfo, size=0, linkname="regtype")
839
840 def test_find_blktype(self):
841 tarinfo = self.tar.getmember("ustar/blktype")
842 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
843
844 def test_find_chrtype(self):
845 tarinfo = self.tar.getmember("ustar/chrtype")
846 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
847
848 def test_find_fifotype(self):
849 tarinfo = self.tar.getmember("ustar/fifotype")
850 self._test_member(tarinfo, size=0)
851
852 def test_find_sparse(self):
853 tarinfo = self.tar.getmember("ustar/sparse")
854 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
855
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000856 def test_find_gnusparse(self):
857 tarinfo = self.tar.getmember("gnu/sparse")
858 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
859
860 def test_find_gnusparse_00(self):
861 tarinfo = self.tar.getmember("gnu/sparse-0.0")
862 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
863
864 def test_find_gnusparse_01(self):
865 tarinfo = self.tar.getmember("gnu/sparse-0.1")
866 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
867
868 def test_find_gnusparse_10(self):
869 tarinfo = self.tar.getmember("gnu/sparse-1.0")
870 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
871
Guido van Rossumd8faa362007-04-27 19:54:29 +0000872 def test_find_umlauts(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300873 tarinfo = self.tar.getmember("ustar/umlauts-"
874 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000875 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
876
877 def test_find_ustar_longname(self):
878 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000879 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000880
881 def test_find_regtype_oldv7(self):
882 tarinfo = self.tar.getmember("misc/regtype-old-v7")
883 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
884
885 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000886 self.tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300887 self.tar = tarfile.open(self.tarname, mode=self.mode,
888 encoding="iso8859-1")
889 tarinfo = self.tar.getmember("pax/umlauts-"
890 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000891 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
892
893
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300894class LongnameTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000895
896 def test_read_longname(self):
897 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000898 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000899 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000900 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000901 except KeyError:
902 self.fail("longname not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300903 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
904 "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000905
906 def test_read_longlink(self):
907 longname = self.subdir + "/" + "123/" * 125 + "longname"
908 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
909 try:
910 tarinfo = self.tar.getmember(longlink)
911 except KeyError:
912 self.fail("longlink not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300913 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000914
915 def test_truncated_longname(self):
916 longname = self.subdir + "/" + "123/" * 125 + "longname"
917 tarinfo = self.tar.getmember(longname)
918 offset = tarinfo.offset
919 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000920 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300921 with self.assertRaises(tarfile.ReadError):
922 tarfile.open(name="foo.tar", fileobj=fobj)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000923
Guido van Rossume7ba4952007-06-06 23:52:48 +0000924 def test_header_offset(self):
925 # Test if the start offset of the TarInfo object includes
926 # the preceding extended header.
927 longname = self.subdir + "/" + "123/" * 125 + "longname"
928 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000929 with open(tarname, "rb") as fobj:
930 fobj.seek(offset)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300931 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
932 "iso8859-1", "strict")
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000933 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000934
Guido van Rossumd8faa362007-04-27 19:54:29 +0000935
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300936class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000937
938 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000939 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000940
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000941 # Since 3.2 tarfile is supposed to accurately restore sparse members and
942 # produce files with holes. This is what we actually want to test here.
943 # Unfortunately, not all platforms/filesystems support sparse files, and
944 # even on platforms that do it is non-trivial to make reliable assertions
945 # about holes in files. Therefore, we first do one basic test which works
946 # an all platforms, and after that a test that will work only on
947 # platforms/filesystems that prove to support sparse files.
948 def _test_sparse_file(self, name):
949 self.tar.extract(name, TEMPDIR)
950 filename = os.path.join(TEMPDIR, name)
951 with open(filename, "rb") as fobj:
952 data = fobj.read()
953 self.assertEqual(md5sum(data), md5_sparse,
954 "wrong md5sum for %s" % name)
955
956 if self._fs_supports_holes():
957 s = os.stat(filename)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300958 self.assertLess(s.st_blocks * 512, s.st_size)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000959
960 def test_sparse_file_old(self):
961 self._test_sparse_file("gnu/sparse")
962
963 def test_sparse_file_00(self):
964 self._test_sparse_file("gnu/sparse-0.0")
965
966 def test_sparse_file_01(self):
967 self._test_sparse_file("gnu/sparse-0.1")
968
969 def test_sparse_file_10(self):
970 self._test_sparse_file("gnu/sparse-1.0")
971
972 @staticmethod
973 def _fs_supports_holes():
974 # Return True if the platform knows the st_blocks stat attribute and
975 # uses st_blocks units of 512 bytes, and if the filesystem is able to
976 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200977 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000978 # Linux evidentially has 512 byte st_blocks units.
979 name = os.path.join(TEMPDIR, "sparse-test")
980 with open(name, "wb") as fobj:
981 fobj.seek(4096)
982 fobj.truncate()
983 s = os.stat(name)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100984 support.unlink(name)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000985 return s.st_blocks == 0
986 else:
987 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000988
989
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300990class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000991
992 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000993 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000994
Guido van Rossume7ba4952007-06-06 23:52:48 +0000995 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000996 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000997 try:
998 tarinfo = tar.getmember("pax/regtype1")
999 self.assertEqual(tarinfo.uname, "foo")
1000 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001001 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
1002 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001003
Antoine Pitrou95f55602010-09-23 18:36:46 +00001004 tarinfo = tar.getmember("pax/regtype2")
1005 self.assertEqual(tarinfo.uname, "")
1006 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001007 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
1008 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001009
Antoine Pitrou95f55602010-09-23 18:36:46 +00001010 tarinfo = tar.getmember("pax/regtype3")
1011 self.assertEqual(tarinfo.uname, "tarfile")
1012 self.assertEqual(tarinfo.gname, "tarfile")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001013 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
1014 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001015 finally:
1016 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001017
1018 def test_pax_number_fields(self):
1019 # All following number fields are read from the pax header.
1020 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001021 try:
1022 tarinfo = tar.getmember("pax/regtype4")
1023 self.assertEqual(tarinfo.size, 7011)
1024 self.assertEqual(tarinfo.uid, 123)
1025 self.assertEqual(tarinfo.gid, 123)
1026 self.assertEqual(tarinfo.mtime, 1041808783.0)
1027 self.assertEqual(type(tarinfo.mtime), float)
1028 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
1029 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
1030 finally:
1031 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001032
1033
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001034class WriteTestBase(TarTest):
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001035 # Put all write tests in here that are supposed to be tested
1036 # in all possible mode combinations.
1037
1038 def test_fileobj_no_close(self):
1039 fobj = io.BytesIO()
1040 tar = tarfile.open(fileobj=fobj, mode=self.mode)
1041 tar.addfile(tarfile.TarInfo("foo"))
1042 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001043 self.assertFalse(fobj.closed, "external fileobjs must never closed")
Serhiy Storchaka9fbec7a2014-01-18 15:53:05 +02001044 # Issue #20238: Incomplete gzip output with mode="w:gz"
1045 data = fobj.getvalue()
1046 del tar
1047 support.gc_collect()
1048 self.assertFalse(fobj.closed)
1049 self.assertEqual(data, fobj.getvalue())
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001050
Lars Gustäbel20703c62015-05-27 12:53:44 +02001051 def test_eof_marker(self):
1052 # Make sure an end of archive marker is written (two zero blocks).
1053 # tarfile insists on aligning archives to a 20 * 512 byte recordsize.
1054 # So, we create an archive that has exactly 10240 bytes without the
1055 # marker, and has 20480 bytes once the marker is written.
1056 with tarfile.open(tmpname, self.mode) as tar:
1057 t = tarfile.TarInfo("foo")
1058 t.size = tarfile.RECORDSIZE - tarfile.BLOCKSIZE
1059 tar.addfile(t, io.BytesIO(b"a" * t.size))
1060
1061 with self.open(tmpname, "rb") as fobj:
1062 self.assertEqual(len(fobj.read()), tarfile.RECORDSIZE * 2)
1063
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001064
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001065class WriteTest(WriteTestBase, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001066
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001067 prefix = "w:"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001068
1069 def test_100_char_name(self):
1070 # The name field in a tar header stores strings of at most 100 chars.
1071 # If a string is shorter than 100 chars it has to be padded with '\0',
1072 # which implies that a string of exactly 100 chars is stored without
1073 # a trailing '\0'.
1074 name = "0123456789" * 10
1075 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001076 try:
1077 t = tarfile.TarInfo(name)
1078 tar.addfile(t)
1079 finally:
1080 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +00001081
Guido van Rossumd8faa362007-04-27 19:54:29 +00001082 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001083 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001084 self.assertEqual(tar.getnames()[0], name,
Antoine Pitrou95f55602010-09-23 18:36:46 +00001085 "failed to store 100 char filename")
1086 finally:
1087 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001088
Guido van Rossumd8faa362007-04-27 19:54:29 +00001089 def test_tar_size(self):
1090 # Test for bug #1013882.
1091 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001092 try:
1093 path = os.path.join(TEMPDIR, "file")
1094 with open(path, "wb") as fobj:
1095 fobj.write(b"aaa")
1096 tar.add(path)
1097 finally:
1098 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001099 self.assertGreater(os.path.getsize(tmpname), 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001100 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001101
Guido van Rossumd8faa362007-04-27 19:54:29 +00001102 # The test_*_size tests test for bug #1167128.
1103 def test_file_size(self):
1104 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001105 try:
1106 path = os.path.join(TEMPDIR, "file")
1107 with open(path, "wb"):
1108 pass
1109 tarinfo = tar.gettarinfo(path)
1110 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001111
Antoine Pitrou95f55602010-09-23 18:36:46 +00001112 with open(path, "wb") as fobj:
1113 fobj.write(b"aaa")
1114 tarinfo = tar.gettarinfo(path)
1115 self.assertEqual(tarinfo.size, 3)
1116 finally:
1117 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001118
1119 def test_directory_size(self):
1120 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001121 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001122 try:
1123 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001124 try:
1125 tarinfo = tar.gettarinfo(path)
1126 self.assertEqual(tarinfo.size, 0)
1127 finally:
1128 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001130 support.rmdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001131
Serhiy Storchaka666165f2017-03-08 12:29:33 +02001132 def test_gettarinfo_pathlike_name(self):
1133 with tarfile.open(tmpname, self.mode) as tar:
1134 path = pathlib.Path(TEMPDIR) / "file"
1135 with open(path, "wb") as fobj:
1136 fobj.write(b"aaa")
1137 tarinfo = tar.gettarinfo(path)
1138 tarinfo2 = tar.gettarinfo(os.fspath(path))
1139 self.assertIsInstance(tarinfo.name, str)
1140 self.assertEqual(tarinfo.name, tarinfo2.name)
1141 self.assertEqual(tarinfo.size, 3)
1142
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001143 @unittest.skipUnless(hasattr(os, "link"),
1144 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001145 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001146 link = os.path.join(TEMPDIR, "link")
1147 target = os.path.join(TEMPDIR, "link_target")
1148 with open(target, "wb") as fobj:
1149 fobj.write(b"aaa")
1150 os.link(target, link)
1151 try:
1152 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001153 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001154 # Record the link target in the inodes list.
1155 tar.gettarinfo(target)
1156 tarinfo = tar.gettarinfo(link)
1157 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001158 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001159 tar.close()
1160 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001161 support.unlink(target)
1162 support.unlink(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001163
Brian Curtin3b4499c2010-12-28 14:31:47 +00001164 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +00001165 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +00001166 path = os.path.join(TEMPDIR, "symlink")
1167 os.symlink("link_target", path)
1168 try:
1169 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001170 try:
1171 tarinfo = tar.gettarinfo(path)
1172 self.assertEqual(tarinfo.size, 0)
1173 finally:
1174 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +00001175 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001176 support.unlink(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001177
1178 def test_add_self(self):
1179 # Test for #1257255.
1180 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001181 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001182 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001183 self.assertEqual(tar.name, dstname,
1184 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001185 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001186 self.assertEqual(tar.getnames(), [],
1187 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001189 with support.change_cwd(TEMPDIR):
1190 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001191 self.assertEqual(tar.getnames(), [],
1192 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001193 finally:
1194 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001195
Guido van Rossum486364b2007-06-30 05:01:58 +00001196 def test_exclude(self):
1197 tempdir = os.path.join(TEMPDIR, "exclude")
1198 os.mkdir(tempdir)
1199 try:
1200 for name in ("foo", "bar", "baz"):
1201 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001202 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +00001203
Benjamin Peterson886af962010-03-21 23:13:07 +00001204 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +00001205
1206 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001207 try:
1208 with support.check_warnings(("use the filter argument",
1209 DeprecationWarning)):
1210 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
1211 finally:
1212 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001213
1214 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001215 try:
1216 self.assertEqual(len(tar.getmembers()), 1)
1217 self.assertEqual(tar.getnames()[0], "empty_dir")
1218 finally:
1219 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001220 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001221 support.rmtree(tempdir)
Guido van Rossum486364b2007-06-30 05:01:58 +00001222
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001223 def test_filter(self):
1224 tempdir = os.path.join(TEMPDIR, "filter")
1225 os.mkdir(tempdir)
1226 try:
1227 for name in ("foo", "bar", "baz"):
1228 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001229 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001230
1231 def filter(tarinfo):
1232 if os.path.basename(tarinfo.name) == "bar":
1233 return
1234 tarinfo.uid = 123
1235 tarinfo.uname = "foo"
1236 return tarinfo
1237
1238 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001239 try:
1240 tar.add(tempdir, arcname="empty_dir", filter=filter)
1241 finally:
1242 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001243
Raymond Hettingera63a3122011-01-26 20:34:14 +00001244 # Verify that filter is a keyword-only argument
1245 with self.assertRaises(TypeError):
1246 tar.add(tempdir, "empty_dir", True, None, filter)
1247
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001248 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001249 try:
1250 for tarinfo in tar:
1251 self.assertEqual(tarinfo.uid, 123)
1252 self.assertEqual(tarinfo.uname, "foo")
1253 self.assertEqual(len(tar.getmembers()), 3)
1254 finally:
1255 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001256 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001257 support.rmtree(tempdir)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001258
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001259 # Guarantee that stored pathnames are not modified. Don't
1260 # remove ./ or ../ or double slashes. Still make absolute
1261 # pathnames relative.
1262 # For details see bug #6054.
1263 def _test_pathname(self, path, cmp_path=None, dir=False):
1264 # Create a tarfile with an empty member named path
1265 # and compare the stored name with the original.
1266 foo = os.path.join(TEMPDIR, "foo")
1267 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001268 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001269 else:
1270 os.mkdir(foo)
1271
1272 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001273 try:
1274 tar.add(foo, arcname=path)
1275 finally:
1276 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001277
1278 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001279 try:
1280 t = tar.next()
1281 finally:
1282 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001283
1284 if not dir:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001285 support.unlink(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001286 else:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001287 support.rmdir(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001288
1289 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1290
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001291
1292 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001293 def test_extractall_symlinks(self):
1294 # Test if extractall works properly when tarfile contains symlinks
1295 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1296 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1297 os.mkdir(tempdir)
1298 try:
1299 source_file = os.path.join(tempdir,'source')
1300 target_file = os.path.join(tempdir,'symlink')
1301 with open(source_file,'w') as f:
1302 f.write('something\n')
1303 os.symlink(source_file, target_file)
1304 tar = tarfile.open(temparchive,'w')
1305 tar.add(source_file)
1306 tar.add(target_file)
1307 tar.close()
1308 # Let's extract it to the location which contains the symlink
1309 tar = tarfile.open(temparchive,'r')
1310 # this should not raise OSError: [Errno 17] File exists
1311 try:
1312 tar.extractall(path=tempdir)
1313 except OSError:
1314 self.fail("extractall failed with symlinked files")
1315 finally:
1316 tar.close()
1317 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001318 support.unlink(temparchive)
1319 support.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001320
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001321 def test_pathnames(self):
1322 self._test_pathname("foo")
1323 self._test_pathname(os.path.join("foo", ".", "bar"))
1324 self._test_pathname(os.path.join("foo", "..", "bar"))
1325 self._test_pathname(os.path.join(".", "foo"))
1326 self._test_pathname(os.path.join(".", "foo", "."))
1327 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1328 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1329 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1330 self._test_pathname(os.path.join("..", "foo"))
1331 self._test_pathname(os.path.join("..", "foo", ".."))
1332 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1333 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1334
1335 self._test_pathname("foo" + os.sep + os.sep + "bar")
1336 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1337
1338 def test_abs_pathnames(self):
1339 if sys.platform == "win32":
1340 self._test_pathname("C:\\foo", "foo")
1341 else:
1342 self._test_pathname("/foo", "foo")
1343 self._test_pathname("///foo", "foo")
1344
1345 def test_cwd(self):
1346 # Test adding the current working directory.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001347 with support.change_cwd(TEMPDIR):
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001348 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001349 try:
1350 tar.add(".")
1351 finally:
1352 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001353
1354 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001355 try:
1356 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001357 if t.name != ".":
1358 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001359 finally:
1360 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001361
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001362 def test_open_nonwritable_fileobj(self):
1363 for exctype in OSError, EOFError, RuntimeError:
1364 class BadFile(io.BytesIO):
1365 first = True
1366 def write(self, data):
1367 if self.first:
1368 self.first = False
1369 raise exctype
1370
1371 f = BadFile()
1372 with self.assertRaises(exctype):
1373 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1374 format=tarfile.PAX_FORMAT,
1375 pax_headers={'non': 'empty'})
1376 self.assertFalse(f.closed)
1377
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001378class GzipWriteTest(GzipTest, WriteTest):
1379 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001380
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001381class Bz2WriteTest(Bz2Test, WriteTest):
1382 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001383
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001384class LzmaWriteTest(LzmaTest, WriteTest):
1385 pass
1386
1387
1388class StreamWriteTest(WriteTestBase, unittest.TestCase):
1389
1390 prefix = "w|"
1391 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001392
Guido van Rossumd8faa362007-04-27 19:54:29 +00001393 def test_stream_padding(self):
1394 # Test for bug #1543303.
1395 tar = tarfile.open(tmpname, self.mode)
1396 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001397 if self.decompressor:
1398 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001399 with open(tmpname, "rb") as fobj:
1400 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001401 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001402 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001403 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001404 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001405 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001406 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1407 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001408
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001409 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1410 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001411 def test_file_mode(self):
1412 # Test for issue #8464: Create files with correct
1413 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001414 if os.path.exists(tmpname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001415 support.unlink(tmpname)
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001416
1417 original_umask = os.umask(0o022)
1418 try:
1419 tar = tarfile.open(tmpname, self.mode)
1420 tar.close()
1421 mode = os.stat(tmpname).st_mode & 0o777
1422 self.assertEqual(mode, 0o644, "wrong file permissions")
1423 finally:
1424 os.umask(original_umask)
1425
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001426class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1427 pass
1428
1429class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1430 decompressor = bz2.BZ2Decompressor if bz2 else None
1431
1432class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1433 decompressor = lzma.LZMADecompressor if lzma else None
1434
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001435
Guido van Rossumd8faa362007-04-27 19:54:29 +00001436class GNUWriteTest(unittest.TestCase):
1437 # This testcase checks for correct creation of GNU Longname
1438 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001439
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001440 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001441 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001442 return blocks * 512
1443
1444 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001445 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001446 count = 512
1447
1448 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001449 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001450 count += 512
1451 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001452 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001453 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001454 count += 512
1455 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001456 return count
1457
1458 def _test(self, name, link=None):
1459 tarinfo = tarfile.TarInfo(name)
1460 if link:
1461 tarinfo.linkname = link
1462 tarinfo.type = tarfile.LNKTYPE
1463
Guido van Rossumd8faa362007-04-27 19:54:29 +00001464 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001465 try:
1466 tar.format = tarfile.GNU_FORMAT
1467 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001468
Antoine Pitrou95f55602010-09-23 18:36:46 +00001469 v1 = self._calc_size(name, link)
1470 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001471 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001472 finally:
1473 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001474
Guido van Rossumd8faa362007-04-27 19:54:29 +00001475 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001476 try:
1477 member = tar.next()
1478 self.assertIsNotNone(member,
1479 "unable to read longname member")
1480 self.assertEqual(tarinfo.name, member.name,
1481 "unable to read longname member")
1482 self.assertEqual(tarinfo.linkname, member.linkname,
1483 "unable to read longname member")
1484 finally:
1485 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001486
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001487 def test_longname_1023(self):
1488 self._test(("longnam/" * 127) + "longnam")
1489
1490 def test_longname_1024(self):
1491 self._test(("longnam/" * 127) + "longname")
1492
1493 def test_longname_1025(self):
1494 self._test(("longnam/" * 127) + "longname_")
1495
1496 def test_longlink_1023(self):
1497 self._test("name", ("longlnk/" * 127) + "longlnk")
1498
1499 def test_longlink_1024(self):
1500 self._test("name", ("longlnk/" * 127) + "longlink")
1501
1502 def test_longlink_1025(self):
1503 self._test("name", ("longlnk/" * 127) + "longlink_")
1504
1505 def test_longnamelink_1023(self):
1506 self._test(("longnam/" * 127) + "longnam",
1507 ("longlnk/" * 127) + "longlnk")
1508
1509 def test_longnamelink_1024(self):
1510 self._test(("longnam/" * 127) + "longname",
1511 ("longlnk/" * 127) + "longlink")
1512
1513 def test_longnamelink_1025(self):
1514 self._test(("longnam/" * 127) + "longname_",
1515 ("longlnk/" * 127) + "longlink_")
1516
Guido van Rossumd8faa362007-04-27 19:54:29 +00001517
Lars Gustäbel20703c62015-05-27 12:53:44 +02001518class CreateTest(WriteTestBase, unittest.TestCase):
Berker Peksag0fe63252015-02-13 21:02:12 +02001519
1520 prefix = "x:"
1521
1522 file_path = os.path.join(TEMPDIR, "spameggs42")
1523
1524 def setUp(self):
1525 support.unlink(tmpname)
1526
1527 @classmethod
1528 def setUpClass(cls):
1529 with open(cls.file_path, "wb") as fobj:
1530 fobj.write(b"aaa")
1531
1532 @classmethod
1533 def tearDownClass(cls):
1534 support.unlink(cls.file_path)
1535
1536 def test_create(self):
1537 with tarfile.open(tmpname, self.mode) as tobj:
1538 tobj.add(self.file_path)
1539
1540 with self.taropen(tmpname) as tobj:
1541 names = tobj.getnames()
1542 self.assertEqual(len(names), 1)
1543 self.assertIn('spameggs42', names[0])
1544
1545 def test_create_existing(self):
1546 with tarfile.open(tmpname, self.mode) as tobj:
1547 tobj.add(self.file_path)
1548
1549 with self.assertRaises(FileExistsError):
1550 tobj = tarfile.open(tmpname, self.mode)
1551
1552 with self.taropen(tmpname) as tobj:
1553 names = tobj.getnames()
1554 self.assertEqual(len(names), 1)
1555 self.assertIn('spameggs42', names[0])
1556
1557 def test_create_taropen(self):
1558 with self.taropen(tmpname, "x") as tobj:
1559 tobj.add(self.file_path)
1560
1561 with self.taropen(tmpname) as tobj:
1562 names = tobj.getnames()
1563 self.assertEqual(len(names), 1)
1564 self.assertIn('spameggs42', names[0])
1565
1566 def test_create_existing_taropen(self):
1567 with self.taropen(tmpname, "x") as tobj:
1568 tobj.add(self.file_path)
1569
1570 with self.assertRaises(FileExistsError):
1571 with self.taropen(tmpname, "x"):
1572 pass
1573
1574 with self.taropen(tmpname) as tobj:
1575 names = tobj.getnames()
1576 self.assertEqual(len(names), 1)
1577 self.assertIn("spameggs42", names[0])
1578
Serhiy Storchaka666165f2017-03-08 12:29:33 +02001579 def test_create_pathlike_name(self):
1580 with tarfile.open(pathlib.Path(tmpname), self.mode) as tobj:
1581 self.assertIsInstance(tobj.name, str)
1582 self.assertEqual(tobj.name, os.path.abspath(tmpname))
1583 tobj.add(pathlib.Path(self.file_path))
1584 names = tobj.getnames()
1585 self.assertEqual(len(names), 1)
1586 self.assertIn('spameggs42', names[0])
1587
1588 with self.taropen(tmpname) as tobj:
1589 names = tobj.getnames()
1590 self.assertEqual(len(names), 1)
1591 self.assertIn('spameggs42', names[0])
1592
1593 def test_create_taropen_pathlike_name(self):
1594 with self.taropen(pathlib.Path(tmpname), "x") as tobj:
1595 self.assertIsInstance(tobj.name, str)
1596 self.assertEqual(tobj.name, os.path.abspath(tmpname))
1597 tobj.add(pathlib.Path(self.file_path))
1598 names = tobj.getnames()
1599 self.assertEqual(len(names), 1)
1600 self.assertIn('spameggs42', names[0])
1601
1602 with self.taropen(tmpname) as tobj:
1603 names = tobj.getnames()
1604 self.assertEqual(len(names), 1)
1605 self.assertIn('spameggs42', names[0])
1606
Berker Peksag0fe63252015-02-13 21:02:12 +02001607
1608class GzipCreateTest(GzipTest, CreateTest):
1609 pass
1610
1611
1612class Bz2CreateTest(Bz2Test, CreateTest):
1613 pass
1614
1615
1616class LzmaCreateTest(LzmaTest, CreateTest):
1617 pass
1618
1619
1620class CreateWithXModeTest(CreateTest):
1621
1622 prefix = "x"
1623
1624 test_create_taropen = None
1625 test_create_existing_taropen = None
1626
1627
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001628@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001629class HardlinkTest(unittest.TestCase):
1630 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001631
1632 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001633 self.foo = os.path.join(TEMPDIR, "foo")
1634 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001635
Antoine Pitrou95f55602010-09-23 18:36:46 +00001636 with open(self.foo, "wb") as fobj:
1637 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001638
Guido van Rossumd8faa362007-04-27 19:54:29 +00001639 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001640
Guido van Rossumd8faa362007-04-27 19:54:29 +00001641 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001642 self.tar.add(self.foo)
1643
Guido van Rossumd8faa362007-04-27 19:54:29 +00001644 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001645 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001646 support.unlink(self.foo)
1647 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001648
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001649 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001650 # The same name will be added as a REGTYPE every
1651 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001652 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001653 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001654 "add file as regular failed")
1655
1656 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001657 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001658 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001659 "add file as hardlink failed")
1660
1661 def test_dereference_hardlink(self):
1662 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001663 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001664 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001665 "dereferencing hardlink failed")
1666
Neal Norwitza4f651a2004-07-20 22:07:44 +00001667
Guido van Rossumd8faa362007-04-27 19:54:29 +00001668class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001669
Guido van Rossumd8faa362007-04-27 19:54:29 +00001670 def _test(self, name, link=None):
1671 # See GNUWriteTest.
1672 tarinfo = tarfile.TarInfo(name)
1673 if link:
1674 tarinfo.linkname = link
1675 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001676
Guido van Rossumd8faa362007-04-27 19:54:29 +00001677 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001678 try:
1679 tar.addfile(tarinfo)
1680 finally:
1681 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001682
Guido van Rossumd8faa362007-04-27 19:54:29 +00001683 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001684 try:
1685 if link:
1686 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001687 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001688 else:
1689 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001690 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001691 finally:
1692 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001693
Guido van Rossume7ba4952007-06-06 23:52:48 +00001694 def test_pax_global_header(self):
1695 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001696 "foo": "bar",
1697 "uid": "0",
1698 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001699 "test": "\xe4\xf6\xfc",
1700 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001701
Benjamin Peterson886af962010-03-21 23:13:07 +00001702 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001703 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001704 try:
1705 tar.addfile(tarfile.TarInfo("test"))
1706 finally:
1707 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001708
1709 # Test if the global header was written correctly.
1710 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001711 try:
1712 self.assertEqual(tar.pax_headers, pax_headers)
1713 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1714 # Test if all the fields are strings.
1715 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001716 self.assertIsNot(type(key), bytes)
1717 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001718 if key in tarfile.PAX_NUMBER_FIELDS:
1719 try:
1720 tarfile.PAX_NUMBER_FIELDS[key](val)
1721 except (TypeError, ValueError):
1722 self.fail("unable to convert pax header field")
1723 finally:
1724 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001725
1726 def test_pax_extended_header(self):
1727 # The fields from the pax header have priority over the
1728 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001729 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001730
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001731 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1732 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001733 try:
1734 t = tarfile.TarInfo()
1735 t.name = "\xe4\xf6\xfc" # non-ASCII
1736 t.uid = 8**8 # too large
1737 t.pax_headers = pax_headers
1738 tar.addfile(t)
1739 finally:
1740 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001741
1742 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001743 try:
1744 t = tar.getmembers()[0]
1745 self.assertEqual(t.pax_headers, pax_headers)
1746 self.assertEqual(t.name, "foo")
1747 self.assertEqual(t.uid, 123)
1748 finally:
1749 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001750
1751
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001752class UnicodeTest:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001753
1754 def test_iso8859_1_filename(self):
1755 self._test_unicode_filename("iso8859-1")
1756
1757 def test_utf7_filename(self):
1758 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001759
1760 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001761 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001762
Guido van Rossumd8faa362007-04-27 19:54:29 +00001763 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001764 tar = tarfile.open(tmpname, "w", format=self.format,
1765 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001766 try:
1767 name = "\xe4\xf6\xfc"
1768 tar.addfile(tarfile.TarInfo(name))
1769 finally:
1770 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001771
1772 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001773 try:
1774 self.assertEqual(tar.getmembers()[0].name, name)
1775 finally:
1776 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001777
1778 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001779 tar = tarfile.open(tmpname, "w", format=self.format,
1780 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001781 try:
1782 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001783
Antoine Pitrou95f55602010-09-23 18:36:46 +00001784 tarinfo.name = "\xe4\xf6\xfc"
1785 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001786
Antoine Pitrou95f55602010-09-23 18:36:46 +00001787 tarinfo.name = "foo"
1788 tarinfo.uname = "\xe4\xf6\xfc"
1789 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1790 finally:
1791 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001792
1793 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001794 tar = tarfile.open(tarname, "r",
1795 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001796 try:
1797 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001798 self.assertIs(type(t.name), str)
1799 self.assertIs(type(t.linkname), str)
1800 self.assertIs(type(t.uname), str)
1801 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001802 finally:
1803 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001804
Guido van Rossume7ba4952007-06-06 23:52:48 +00001805 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001806 t = tarfile.TarInfo("foo")
1807 t.uname = "\xe4\xf6\xfc"
1808 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001809
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001810 tar = tarfile.open(tmpname, mode="w", format=self.format,
1811 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001812 try:
1813 tar.addfile(t)
1814 finally:
1815 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001816
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001817 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001818 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001819 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001820 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1821 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1822
1823 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001824 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001825 tar = tarfile.open(tmpname, encoding="ascii")
1826 t = tar.getmember("foo")
1827 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1828 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1829 finally:
1830 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001831
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001832
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001833class UstarUnicodeTest(UnicodeTest, unittest.TestCase):
1834
1835 format = tarfile.USTAR_FORMAT
1836
1837 # Test whether the utf-8 encoded version of a filename exceeds the 100
1838 # bytes name field limit (every occurrence of '\xff' will be expanded to 2
1839 # bytes).
1840 def test_unicode_name1(self):
1841 self._test_ustar_name("0123456789" * 10)
1842 self._test_ustar_name("0123456789" * 10 + "0", ValueError)
1843 self._test_ustar_name("0123456789" * 9 + "01234567\xff")
1844 self._test_ustar_name("0123456789" * 9 + "012345678\xff", ValueError)
1845
1846 def test_unicode_name2(self):
1847 self._test_ustar_name("0123456789" * 9 + "012345\xff\xff")
1848 self._test_ustar_name("0123456789" * 9 + "0123456\xff\xff", ValueError)
1849
1850 # Test whether the utf-8 encoded version of a filename exceeds the 155
1851 # bytes prefix + '/' + 100 bytes name limit.
1852 def test_unicode_longname1(self):
1853 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 10)
1854 self._test_ustar_name("0123456789" * 15 + "0123/4" + "0123456789" * 10, ValueError)
1855 self._test_ustar_name("0123456789" * 15 + "012\xff/" + "0123456789" * 10)
1856 self._test_ustar_name("0123456789" * 15 + "0123\xff/" + "0123456789" * 10, ValueError)
1857
1858 def test_unicode_longname2(self):
1859 self._test_ustar_name("0123456789" * 15 + "01\xff/2" + "0123456789" * 10, ValueError)
1860 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/" + "0123456789" * 10, ValueError)
1861
1862 def test_unicode_longname3(self):
1863 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/2" + "0123456789" * 10, ValueError)
1864 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "01234567\xff")
1865 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345678\xff", ValueError)
1866
1867 def test_unicode_longname4(self):
1868 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345\xff\xff")
1869 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "0123456\xff\xff", ValueError)
1870
1871 def _test_ustar_name(self, name, exc=None):
1872 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1873 t = tarfile.TarInfo(name)
1874 if exc is None:
1875 tar.addfile(t)
1876 else:
1877 self.assertRaises(exc, tar.addfile, t)
1878
1879 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001880 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001881 for t in tar:
1882 self.assertEqual(name, t.name)
1883 break
1884
1885 # Test the same as above for the 100 bytes link field.
1886 def test_unicode_link1(self):
1887 self._test_ustar_link("0123456789" * 10)
1888 self._test_ustar_link("0123456789" * 10 + "0", ValueError)
1889 self._test_ustar_link("0123456789" * 9 + "01234567\xff")
1890 self._test_ustar_link("0123456789" * 9 + "012345678\xff", ValueError)
1891
1892 def test_unicode_link2(self):
1893 self._test_ustar_link("0123456789" * 9 + "012345\xff\xff")
1894 self._test_ustar_link("0123456789" * 9 + "0123456\xff\xff", ValueError)
1895
1896 def _test_ustar_link(self, name, exc=None):
1897 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1898 t = tarfile.TarInfo("foo")
1899 t.linkname = name
1900 if exc is None:
1901 tar.addfile(t)
1902 else:
1903 self.assertRaises(exc, tar.addfile, t)
1904
1905 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001906 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001907 for t in tar:
1908 self.assertEqual(name, t.linkname)
1909 break
1910
1911
1912class GNUUnicodeTest(UnicodeTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001913
Guido van Rossume7ba4952007-06-06 23:52:48 +00001914 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001915
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001916 def test_bad_pax_header(self):
1917 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1918 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001919 for encoding, name in (
1920 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001921 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001922 with tarfile.open(tarname, encoding=encoding,
1923 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001924 try:
1925 t = tar.getmember(name)
1926 except KeyError:
1927 self.fail("unable to read bad GNU tar pax header")
1928
Guido van Rossumd8faa362007-04-27 19:54:29 +00001929
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001930class PAXUnicodeTest(UnicodeTest, unittest.TestCase):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001931
1932 format = tarfile.PAX_FORMAT
1933
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001934 # PAX_FORMAT ignores encoding in write mode.
1935 test_unicode_filename_error = None
1936
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001937 def test_binary_header(self):
1938 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001939 for encoding, name in (
1940 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001941 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001942 with tarfile.open(tarname, encoding=encoding,
1943 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001944 try:
1945 t = tar.getmember(name)
1946 except KeyError:
1947 self.fail("unable to read POSIX.1-2008 binary header")
1948
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001949
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001950class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001951 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001952
Guido van Rossumd8faa362007-04-27 19:54:29 +00001953 def setUp(self):
1954 self.tarname = tmpname
1955 if os.path.exists(self.tarname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001956 support.unlink(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001957
Guido van Rossumd8faa362007-04-27 19:54:29 +00001958 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001959 with tarfile.open(tarname, encoding="iso8859-1") as src:
1960 t = src.getmember("ustar/regtype")
1961 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001962 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001963 with tarfile.open(self.tarname, mode) as tar:
1964 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001965
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001966 def test_append_compressed(self):
1967 self._create_testtar("w:" + self.suffix)
1968 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1969
1970class AppendTest(AppendTestBase, unittest.TestCase):
1971 test_append_compressed = None
1972
1973 def _add_testfile(self, fileobj=None):
1974 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1975 tar.addfile(tarfile.TarInfo("bar"))
1976
Guido van Rossumd8faa362007-04-27 19:54:29 +00001977 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001978 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1979 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001980
1981 def test_non_existing(self):
1982 self._add_testfile()
1983 self._test()
1984
1985 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001986 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001987 self._add_testfile()
1988 self._test()
1989
1990 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001991 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001992 self._add_testfile(fobj)
1993 fobj.seek(0)
1994 self._test(fileobj=fobj)
1995
1996 def test_fileobj(self):
1997 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001998 with open(self.tarname, "rb") as fobj:
1999 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00002000 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002001 self._add_testfile(fobj)
2002 fobj.seek(0)
2003 self._test(names=["foo", "bar"], fileobj=fobj)
2004
2005 def test_existing(self):
2006 self._create_testtar()
2007 self._add_testfile()
2008 self._test(names=["foo", "bar"])
2009
Lars Gustäbel9520a432009-11-22 18:48:49 +00002010 # Append mode is supposed to fail if the tarfile to append to
2011 # does not end with a zero block.
2012 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00002013 with open(self.tarname, "wb") as fobj:
2014 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002015 self.assertRaises(tarfile.ReadError, self._add_testfile)
2016
2017 def test_null(self):
2018 self._test_error(b"")
2019
2020 def test_incomplete(self):
2021 self._test_error(b"\0" * 13)
2022
2023 def test_premature_eof(self):
2024 data = tarfile.TarInfo("foo").tobuf()
2025 self._test_error(data)
2026
2027 def test_trailing_garbage(self):
2028 data = tarfile.TarInfo("foo").tobuf()
2029 self._test_error(data + b"\0" * 13)
2030
2031 def test_invalid(self):
2032 self._test_error(b"a" * 512)
2033
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002034class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
2035 pass
2036
2037class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
2038 pass
2039
2040class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
2041 pass
2042
Guido van Rossumd8faa362007-04-27 19:54:29 +00002043
2044class LimitsTest(unittest.TestCase):
2045
2046 def test_ustar_limits(self):
2047 # 100 char name
2048 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002049 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002050
2051 # 101 char name that cannot be stored
2052 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002053 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002054
2055 # 256 char name with a slash at pos 156
2056 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002057 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002058
2059 # 256 char name that cannot be stored
2060 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002061 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002062
2063 # 512 char name
2064 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002065 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002066
2067 # 512 char linkname
2068 tarinfo = tarfile.TarInfo("longlink")
2069 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002070 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002071
2072 # uid > 8 digits
2073 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002074 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002075 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002076
2077 def test_gnu_limits(self):
2078 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002079 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002080
2081 tarinfo = tarfile.TarInfo("longlink")
2082 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002083 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002084
2085 # uid >= 256 ** 7
2086 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002087 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002088 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002089
2090 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002091 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002092 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002093
2094 tarinfo = tarfile.TarInfo("longlink")
2095 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002096 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002097
2098 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002099 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002100 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002101
2102
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002103class MiscTest(unittest.TestCase):
2104
2105 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002106 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
2107 b"foo\0\0\0\0\0")
2108 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
2109 b"foo")
2110 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
2111 "foo")
2112 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
2113 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002114
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002115 def test_read_number_fields(self):
2116 # Issue 13158: Test if GNU tar specific base-256 number fields
2117 # are decoded correctly.
2118 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
2119 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002120 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
2121 0o10000000)
2122 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
2123 0xffffffff)
2124 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
2125 -1)
2126 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
2127 -100)
2128 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
2129 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002130
Lars Gustäbelb7a688b2015-07-02 19:38:38 +02002131 # Issue 24514: Test if empty number fields are converted to zero.
2132 self.assertEqual(tarfile.nti(b"\0"), 0)
2133 self.assertEqual(tarfile.nti(b" \0"), 0)
2134
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002135 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002136 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002137 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002138 self.assertEqual(tarfile.itn(0o10000000),
2139 b"\x80\x00\x00\x00\x00\x20\x00\x00")
2140 self.assertEqual(tarfile.itn(0xffffffff),
2141 b"\x80\x00\x00\x00\xff\xff\xff\xff")
2142 self.assertEqual(tarfile.itn(-1),
2143 b"\xff\xff\xff\xff\xff\xff\xff\xff")
2144 self.assertEqual(tarfile.itn(-100),
2145 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
2146 self.assertEqual(tarfile.itn(-0x100000000000000),
2147 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002148
2149 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002150 with self.assertRaises(ValueError):
2151 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
2152 with self.assertRaises(ValueError):
2153 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
2154 with self.assertRaises(ValueError):
2155 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
2156 with self.assertRaises(ValueError):
2157 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002158
Martin Panter104dcda2016-01-16 06:59:13 +00002159 def test__all__(self):
Martin Panter5318d102016-01-16 11:01:14 +00002160 blacklist = {'version', 'grp', 'pwd', 'symlink_exception',
Martin Panter104dcda2016-01-16 06:59:13 +00002161 'NUL', 'BLOCKSIZE', 'RECORDSIZE', 'GNU_MAGIC',
2162 'POSIX_MAGIC', 'LENGTH_NAME', 'LENGTH_LINK',
2163 'LENGTH_PREFIX', 'REGTYPE', 'AREGTYPE', 'LNKTYPE',
2164 'SYMTYPE', 'CHRTYPE', 'BLKTYPE', 'DIRTYPE', 'FIFOTYPE',
2165 'CONTTYPE', 'GNUTYPE_LONGNAME', 'GNUTYPE_LONGLINK',
2166 'GNUTYPE_SPARSE', 'XHDTYPE', 'XGLTYPE', 'SOLARIS_XHDTYPE',
2167 'SUPPORTED_TYPES', 'REGULAR_TYPES', 'GNU_TYPES',
2168 'PAX_FIELDS', 'PAX_NAME_FIELDS', 'PAX_NUMBER_FIELDS',
2169 'stn', 'nts', 'nti', 'itn', 'calc_chksums', 'copyfileobj',
2170 'filemode',
2171 'EmptyHeaderError', 'TruncatedHeaderError',
2172 'EOFHeaderError', 'InvalidHeaderError',
Serhiy Storchaka2c1d3e32016-01-16 11:05:11 +02002173 'SubsequentHeaderError', 'ExFileObject',
Martin Panter104dcda2016-01-16 06:59:13 +00002174 'main'}
2175 support.check__all__(self, tarfile, blacklist=blacklist)
2176
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002177
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002178class CommandLineTest(unittest.TestCase):
2179
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002180 def tarfilecmd(self, *args, **kwargs):
2181 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
2182 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01002183 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002184
2185 def tarfilecmd_failure(self, *args):
2186 return script_helper.assert_python_failure('-m', 'tarfile', *args)
2187
2188 def make_simple_tarfile(self, tar_name):
2189 files = [support.findfile('tokenize_tests.txt'),
2190 support.findfile('tokenize_tests-no-coding-cookie-'
2191 'and-utf8-bom-sig-only.txt')]
2192 self.addCleanup(support.unlink, tar_name)
2193 with tarfile.open(tar_name, 'w') as tf:
2194 for tardata in files:
2195 tf.add(tardata, arcname=os.path.basename(tardata))
2196
2197 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002198 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002199 for opt in '-t', '--test':
2200 out = self.tarfilecmd(opt, tar_name)
2201 self.assertEqual(out, b'')
2202
2203 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002204 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002205 for opt in '-v', '--verbose':
2206 out = self.tarfilecmd(opt, '-t', tar_name)
2207 self.assertIn(b'is a tar archive.\n', out)
2208
2209 def test_test_command_invalid_file(self):
2210 zipname = support.findfile('zipdir.zip')
2211 rc, out, err = self.tarfilecmd_failure('-t', zipname)
2212 self.assertIn(b' is not a tar archive.', err)
2213 self.assertEqual(out, b'')
2214 self.assertEqual(rc, 1)
2215
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002216 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002217 with self.subTest(tar_name=tar_name):
2218 with open(tar_name, 'rb') as f:
2219 data = f.read()
2220 try:
2221 with open(tmpname, 'wb') as f:
2222 f.write(data[:511])
2223 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
2224 self.assertEqual(out, b'')
2225 self.assertEqual(rc, 1)
2226 finally:
2227 support.unlink(tmpname)
2228
2229 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002230 for tar_name in testtarnames:
2231 with support.captured_stdout() as t:
2232 with tarfile.open(tar_name, 'r') as tf:
2233 tf.list(verbose=False)
2234 expected = t.getvalue().encode('ascii', 'backslashreplace')
2235 for opt in '-l', '--list':
2236 out = self.tarfilecmd(opt, tar_name,
2237 PYTHONIOENCODING='ascii')
2238 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002239
2240 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002241 for tar_name in testtarnames:
2242 with support.captured_stdout() as t:
2243 with tarfile.open(tar_name, 'r') as tf:
2244 tf.list(verbose=True)
2245 expected = t.getvalue().encode('ascii', 'backslashreplace')
2246 for opt in '-v', '--verbose':
2247 out = self.tarfilecmd(opt, '-l', tar_name,
2248 PYTHONIOENCODING='ascii')
2249 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002250
2251 def test_list_command_invalid_file(self):
2252 zipname = support.findfile('zipdir.zip')
2253 rc, out, err = self.tarfilecmd_failure('-l', zipname)
2254 self.assertIn(b' is not a tar archive.', err)
2255 self.assertEqual(out, b'')
2256 self.assertEqual(rc, 1)
2257
2258 def test_create_command(self):
2259 files = [support.findfile('tokenize_tests.txt'),
2260 support.findfile('tokenize_tests-no-coding-cookie-'
2261 'and-utf8-bom-sig-only.txt')]
2262 for opt in '-c', '--create':
2263 try:
2264 out = self.tarfilecmd(opt, tmpname, *files)
2265 self.assertEqual(out, b'')
2266 with tarfile.open(tmpname) as tar:
2267 tar.getmembers()
2268 finally:
2269 support.unlink(tmpname)
2270
2271 def test_create_command_verbose(self):
2272 files = [support.findfile('tokenize_tests.txt'),
2273 support.findfile('tokenize_tests-no-coding-cookie-'
2274 'and-utf8-bom-sig-only.txt')]
2275 for opt in '-v', '--verbose':
2276 try:
2277 out = self.tarfilecmd(opt, '-c', tmpname, *files)
2278 self.assertIn(b' file created.', out)
2279 with tarfile.open(tmpname) as tar:
2280 tar.getmembers()
2281 finally:
2282 support.unlink(tmpname)
2283
2284 def test_create_command_dotless_filename(self):
2285 files = [support.findfile('tokenize_tests.txt')]
2286 try:
2287 out = self.tarfilecmd('-c', dotlessname, *files)
2288 self.assertEqual(out, b'')
2289 with tarfile.open(dotlessname) as tar:
2290 tar.getmembers()
2291 finally:
2292 support.unlink(dotlessname)
2293
2294 def test_create_command_dot_started_filename(self):
2295 tar_name = os.path.join(TEMPDIR, ".testtar")
2296 files = [support.findfile('tokenize_tests.txt')]
2297 try:
2298 out = self.tarfilecmd('-c', tar_name, *files)
2299 self.assertEqual(out, b'')
2300 with tarfile.open(tar_name) as tar:
2301 tar.getmembers()
2302 finally:
2303 support.unlink(tar_name)
2304
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002305 def test_create_command_compressed(self):
2306 files = [support.findfile('tokenize_tests.txt'),
2307 support.findfile('tokenize_tests-no-coding-cookie-'
2308 'and-utf8-bom-sig-only.txt')]
2309 for filetype in (GzipTest, Bz2Test, LzmaTest):
2310 if not filetype.open:
2311 continue
2312 try:
2313 tar_name = tmpname + '.' + filetype.suffix
2314 out = self.tarfilecmd('-c', tar_name, *files)
2315 with filetype.taropen(tar_name) as tar:
2316 tar.getmembers()
2317 finally:
2318 support.unlink(tar_name)
2319
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002320 def test_extract_command(self):
2321 self.make_simple_tarfile(tmpname)
2322 for opt in '-e', '--extract':
2323 try:
2324 with support.temp_cwd(tarextdir):
2325 out = self.tarfilecmd(opt, tmpname)
2326 self.assertEqual(out, b'')
2327 finally:
2328 support.rmtree(tarextdir)
2329
2330 def test_extract_command_verbose(self):
2331 self.make_simple_tarfile(tmpname)
2332 for opt in '-v', '--verbose':
2333 try:
2334 with support.temp_cwd(tarextdir):
2335 out = self.tarfilecmd(opt, '-e', tmpname)
2336 self.assertIn(b' file is extracted.', out)
2337 finally:
2338 support.rmtree(tarextdir)
2339
2340 def test_extract_command_different_directory(self):
2341 self.make_simple_tarfile(tmpname)
2342 try:
2343 with support.temp_cwd(tarextdir):
2344 out = self.tarfilecmd('-e', tmpname, 'spamdir')
2345 self.assertEqual(out, b'')
2346 finally:
2347 support.rmtree(tarextdir)
2348
2349 def test_extract_command_invalid_file(self):
2350 zipname = support.findfile('zipdir.zip')
2351 with support.temp_cwd(tarextdir):
2352 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2353 self.assertIn(b' is not a tar archive.', err)
2354 self.assertEqual(out, b'')
2355 self.assertEqual(rc, 1)
2356
2357
Lars Gustäbel01385812010-03-03 12:08:54 +00002358class ContextManagerTest(unittest.TestCase):
2359
2360 def test_basic(self):
2361 with tarfile.open(tarname) as tar:
2362 self.assertFalse(tar.closed, "closed inside runtime context")
2363 self.assertTrue(tar.closed, "context manager failed")
2364
2365 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002366 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002367 # if the TarFile object is already closed.
2368 tar = tarfile.open(tarname)
2369 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002370 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002371 with tar:
2372 pass
2373
2374 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002375 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002376 with self.assertRaises(Exception) as exc:
2377 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002378 raise OSError
2379 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002380 "wrong exception raised in context manager")
2381 self.assertTrue(tar.closed, "context manager failed")
2382
2383 def test_no_eof(self):
2384 # __exit__() must not write end-of-archive blocks if an
2385 # exception was raised.
2386 try:
2387 with tarfile.open(tmpname, "w") as tar:
2388 raise Exception
2389 except:
2390 pass
2391 self.assertEqual(os.path.getsize(tmpname), 0,
2392 "context manager wrote an end-of-archive block")
2393 self.assertTrue(tar.closed, "context manager failed")
2394
2395 def test_eof(self):
2396 # __exit__() must write end-of-archive blocks, i.e. call
2397 # TarFile.close() if there was no error.
2398 with tarfile.open(tmpname, "w"):
2399 pass
2400 self.assertNotEqual(os.path.getsize(tmpname), 0,
2401 "context manager wrote no end-of-archive block")
2402
2403 def test_fileobj(self):
2404 # Test that __exit__() did not close the external file
2405 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002406 with open(tmpname, "wb") as fobj:
2407 try:
2408 with tarfile.open(fileobj=fobj, mode="w") as tar:
2409 raise Exception
2410 except:
2411 pass
2412 self.assertFalse(fobj.closed, "external file object was closed")
2413 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002414
2415
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002416@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2417class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002418
2419 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002420 # symbolic or hard links tarfile tries to extract these types of members
2421 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002422 def _test_link_extraction(self, name):
2423 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002424 with open(os.path.join(TEMPDIR, name), "rb") as f:
2425 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002426 self.assertEqual(md5sum(data), md5_regtype)
2427
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002428 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002429 @unittest.skipIf(hasattr(os.path, "islink"),
2430 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002431 def test_hardlink_extraction1(self):
2432 self._test_link_extraction("ustar/lnktype")
2433
Brian Curtind40e6f72010-07-08 21:39:08 +00002434 @unittest.skipIf(hasattr(os.path, "islink"),
2435 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002436 def test_hardlink_extraction2(self):
2437 self._test_link_extraction("./ustar/linktest2/lnktype")
2438
Brian Curtin74e45612010-07-09 15:58:59 +00002439 @unittest.skipIf(hasattr(os, "symlink"),
2440 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002441 def test_symlink_extraction1(self):
2442 self._test_link_extraction("ustar/symtype")
2443
Brian Curtin74e45612010-07-09 15:58:59 +00002444 @unittest.skipIf(hasattr(os, "symlink"),
2445 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002446 def test_symlink_extraction2(self):
2447 self._test_link_extraction("./ustar/linktest2/symtype")
2448
2449
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002450class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002451 # Issue5068: The _BZ2Proxy.read() method loops forever
2452 # on an empty or partial bzipped file.
2453
2454 def _test_partial_input(self, mode):
2455 class MyBytesIO(io.BytesIO):
2456 hit_eof = False
2457 def read(self, n):
2458 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002459 raise AssertionError("infinite loop detected in "
2460 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002461 self.hit_eof = self.tell() == len(self.getvalue())
2462 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002463 def seek(self, *args):
2464 self.hit_eof = False
2465 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002466
2467 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2468 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002469 try:
2470 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2471 except tarfile.ReadError:
2472 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002473
2474 def test_partial_input(self):
2475 self._test_partial_input("r")
2476
2477 def test_partial_input_bz2(self):
2478 self._test_partial_input("r:bz2")
2479
2480
Eric V. Smith7a803892015-04-15 10:27:58 -04002481def root_is_uid_gid_0():
2482 try:
2483 import pwd, grp
2484 except ImportError:
2485 return False
2486 if pwd.getpwuid(0)[0] != 'root':
2487 return False
2488 if grp.getgrgid(0)[0] != 'root':
2489 return False
2490 return True
2491
2492
Zachary Waread3e27a2015-05-12 23:57:21 -05002493@unittest.skipUnless(hasattr(os, 'chown'), "missing os.chown")
2494@unittest.skipUnless(hasattr(os, 'geteuid'), "missing os.geteuid")
Eric V. Smith7a803892015-04-15 10:27:58 -04002495class NumericOwnerTest(unittest.TestCase):
2496 # mock the following:
2497 # os.chown: so we can test what's being called
2498 # os.chmod: so the modes are not actually changed. if they are, we can't
2499 # delete the files/directories
2500 # os.geteuid: so we can lie and say we're root (uid = 0)
2501
2502 @staticmethod
2503 def _make_test_archive(filename_1, dirname_1, filename_2):
2504 # the file contents to write
2505 fobj = io.BytesIO(b"content")
2506
2507 # create a tar file with a file, a directory, and a file within that
2508 # directory. Assign various .uid/.gid values to them
2509 items = [(filename_1, 99, 98, tarfile.REGTYPE, fobj),
2510 (dirname_1, 77, 76, tarfile.DIRTYPE, None),
2511 (filename_2, 88, 87, tarfile.REGTYPE, fobj),
2512 ]
2513 with tarfile.open(tmpname, 'w') as tarfl:
2514 for name, uid, gid, typ, contents in items:
2515 t = tarfile.TarInfo(name)
2516 t.uid = uid
2517 t.gid = gid
2518 t.uname = 'root'
2519 t.gname = 'root'
2520 t.type = typ
2521 tarfl.addfile(t, contents)
2522
2523 # return the full pathname to the tar file
2524 return tmpname
2525
2526 @staticmethod
2527 @contextmanager
2528 def _setup_test(mock_geteuid):
2529 mock_geteuid.return_value = 0 # lie and say we're root
2530 fname = 'numeric-owner-testfile'
2531 dirname = 'dir'
2532
2533 # the names we want stored in the tarfile
2534 filename_1 = fname
2535 dirname_1 = dirname
2536 filename_2 = os.path.join(dirname, fname)
2537
2538 # create the tarfile with the contents we're after
2539 tar_filename = NumericOwnerTest._make_test_archive(filename_1,
2540 dirname_1,
2541 filename_2)
2542
2543 # open the tarfile for reading. yield it and the names of the items
2544 # we stored into the file
2545 with tarfile.open(tar_filename) as tarfl:
2546 yield tarfl, filename_1, dirname_1, filename_2
2547
2548 @unittest.mock.patch('os.chown')
2549 @unittest.mock.patch('os.chmod')
2550 @unittest.mock.patch('os.geteuid')
2551 def test_extract_with_numeric_owner(self, mock_geteuid, mock_chmod,
2552 mock_chown):
2553 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _,
2554 filename_2):
2555 tarfl.extract(filename_1, TEMPDIR, numeric_owner=True)
2556 tarfl.extract(filename_2 , TEMPDIR, numeric_owner=True)
2557
2558 # convert to filesystem paths
2559 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2560 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2561
2562 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2563 unittest.mock.call(f_filename_2, 88, 87),
2564 ],
2565 any_order=True)
2566
2567 @unittest.mock.patch('os.chown')
2568 @unittest.mock.patch('os.chmod')
2569 @unittest.mock.patch('os.geteuid')
2570 def test_extractall_with_numeric_owner(self, mock_geteuid, mock_chmod,
2571 mock_chown):
2572 with self._setup_test(mock_geteuid) as (tarfl, filename_1, dirname_1,
2573 filename_2):
2574 tarfl.extractall(TEMPDIR, numeric_owner=True)
2575
2576 # convert to filesystem paths
2577 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2578 f_dirname_1 = os.path.join(TEMPDIR, dirname_1)
2579 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2580
2581 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2582 unittest.mock.call(f_dirname_1, 77, 76),
2583 unittest.mock.call(f_filename_2, 88, 87),
2584 ],
2585 any_order=True)
2586
2587 # this test requires that uid=0 and gid=0 really be named 'root'. that's
2588 # because the uname and gname in the test file are 'root', and extract()
2589 # will look them up using pwd and grp to find their uid and gid, which we
2590 # test here to be 0.
2591 @unittest.skipUnless(root_is_uid_gid_0(),
2592 'uid=0,gid=0 must be named "root"')
2593 @unittest.mock.patch('os.chown')
2594 @unittest.mock.patch('os.chmod')
2595 @unittest.mock.patch('os.geteuid')
2596 def test_extract_without_numeric_owner(self, mock_geteuid, mock_chmod,
2597 mock_chown):
2598 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2599 tarfl.extract(filename_1, TEMPDIR, numeric_owner=False)
2600
2601 # convert to filesystem paths
2602 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2603
2604 mock_chown.assert_called_with(f_filename_1, 0, 0)
2605
2606 @unittest.mock.patch('os.geteuid')
2607 def test_keyword_only(self, mock_geteuid):
2608 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2609 self.assertRaises(TypeError,
2610 tarfl.extract, filename_1, TEMPDIR, False, True)
2611
2612
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002613def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002614 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002615 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002616
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002617 global testtarnames
2618 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002619 with open(tarname, "rb") as fobj:
2620 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002621
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002622 # Create compressed tarfiles.
2623 for c in GzipTest, Bz2Test, LzmaTest:
2624 if c.open:
2625 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002626 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002627 with c.open(c.tarname, "wb") as tar:
2628 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002629
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002630def tearDownModule():
2631 if os.path.exists(TEMPDIR):
Tim Goldene0bd2c52014-05-06 13:24:26 +01002632 support.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002633
Neal Norwitz996acf12003-02-17 14:51:41 +00002634if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002635 unittest.main()