blob: 030ace14f16d38edcf26252d6ef7ae7ab2944b92 [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 Storchakac45cd162017-03-08 10:32:44 +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 Storchakac45cd162017-03-08 10:32:44 +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 Storchakac45cd162017-03-08 10:32:44 +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 Storchakac45cd162017-03-08 10:32:44 +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
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001196 def test_filter(self):
1197 tempdir = os.path.join(TEMPDIR, "filter")
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)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001203
1204 def filter(tarinfo):
1205 if os.path.basename(tarinfo.name) == "bar":
1206 return
1207 tarinfo.uid = 123
1208 tarinfo.uname = "foo"
1209 return tarinfo
1210
1211 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001212 try:
1213 tar.add(tempdir, arcname="empty_dir", filter=filter)
1214 finally:
1215 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001216
Raymond Hettingera63a3122011-01-26 20:34:14 +00001217 # Verify that filter is a keyword-only argument
1218 with self.assertRaises(TypeError):
1219 tar.add(tempdir, "empty_dir", True, None, filter)
1220
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001221 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001222 try:
1223 for tarinfo in tar:
1224 self.assertEqual(tarinfo.uid, 123)
1225 self.assertEqual(tarinfo.uname, "foo")
1226 self.assertEqual(len(tar.getmembers()), 3)
1227 finally:
1228 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001229 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001230 support.rmtree(tempdir)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001231
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001232 # Guarantee that stored pathnames are not modified. Don't
1233 # remove ./ or ../ or double slashes. Still make absolute
1234 # pathnames relative.
1235 # For details see bug #6054.
1236 def _test_pathname(self, path, cmp_path=None, dir=False):
1237 # Create a tarfile with an empty member named path
1238 # and compare the stored name with the original.
1239 foo = os.path.join(TEMPDIR, "foo")
1240 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001241 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001242 else:
1243 os.mkdir(foo)
1244
1245 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001246 try:
1247 tar.add(foo, arcname=path)
1248 finally:
1249 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001250
1251 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001252 try:
1253 t = tar.next()
1254 finally:
1255 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001256
1257 if not dir:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001258 support.unlink(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001259 else:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001260 support.rmdir(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001261
1262 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1263
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001264
1265 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001266 def test_extractall_symlinks(self):
1267 # Test if extractall works properly when tarfile contains symlinks
1268 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1269 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1270 os.mkdir(tempdir)
1271 try:
1272 source_file = os.path.join(tempdir,'source')
1273 target_file = os.path.join(tempdir,'symlink')
1274 with open(source_file,'w') as f:
1275 f.write('something\n')
1276 os.symlink(source_file, target_file)
1277 tar = tarfile.open(temparchive,'w')
1278 tar.add(source_file)
1279 tar.add(target_file)
1280 tar.close()
1281 # Let's extract it to the location which contains the symlink
1282 tar = tarfile.open(temparchive,'r')
1283 # this should not raise OSError: [Errno 17] File exists
1284 try:
1285 tar.extractall(path=tempdir)
1286 except OSError:
1287 self.fail("extractall failed with symlinked files")
1288 finally:
1289 tar.close()
1290 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001291 support.unlink(temparchive)
1292 support.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001293
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001294 def test_pathnames(self):
1295 self._test_pathname("foo")
1296 self._test_pathname(os.path.join("foo", ".", "bar"))
1297 self._test_pathname(os.path.join("foo", "..", "bar"))
1298 self._test_pathname(os.path.join(".", "foo"))
1299 self._test_pathname(os.path.join(".", "foo", "."))
1300 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1301 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1302 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1303 self._test_pathname(os.path.join("..", "foo"))
1304 self._test_pathname(os.path.join("..", "foo", ".."))
1305 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1306 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1307
1308 self._test_pathname("foo" + os.sep + os.sep + "bar")
1309 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1310
1311 def test_abs_pathnames(self):
1312 if sys.platform == "win32":
1313 self._test_pathname("C:\\foo", "foo")
1314 else:
1315 self._test_pathname("/foo", "foo")
1316 self._test_pathname("///foo", "foo")
1317
1318 def test_cwd(self):
1319 # Test adding the current working directory.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001320 with support.change_cwd(TEMPDIR):
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001321 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001322 try:
1323 tar.add(".")
1324 finally:
1325 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001326
1327 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001328 try:
1329 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001330 if t.name != ".":
1331 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001332 finally:
1333 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001334
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001335 def test_open_nonwritable_fileobj(self):
1336 for exctype in OSError, EOFError, RuntimeError:
1337 class BadFile(io.BytesIO):
1338 first = True
1339 def write(self, data):
1340 if self.first:
1341 self.first = False
1342 raise exctype
1343
1344 f = BadFile()
1345 with self.assertRaises(exctype):
1346 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1347 format=tarfile.PAX_FORMAT,
1348 pax_headers={'non': 'empty'})
1349 self.assertFalse(f.closed)
1350
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001351class GzipWriteTest(GzipTest, WriteTest):
1352 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001353
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001354class Bz2WriteTest(Bz2Test, WriteTest):
1355 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001356
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001357class LzmaWriteTest(LzmaTest, WriteTest):
1358 pass
1359
1360
1361class StreamWriteTest(WriteTestBase, unittest.TestCase):
1362
1363 prefix = "w|"
1364 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001365
Guido van Rossumd8faa362007-04-27 19:54:29 +00001366 def test_stream_padding(self):
1367 # Test for bug #1543303.
1368 tar = tarfile.open(tmpname, self.mode)
1369 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001370 if self.decompressor:
1371 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001372 with open(tmpname, "rb") as fobj:
1373 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001374 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001375 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001376 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001377 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001378 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001379 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1380 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001381
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001382 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1383 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001384 def test_file_mode(self):
1385 # Test for issue #8464: Create files with correct
1386 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001387 if os.path.exists(tmpname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001388 support.unlink(tmpname)
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001389
1390 original_umask = os.umask(0o022)
1391 try:
1392 tar = tarfile.open(tmpname, self.mode)
1393 tar.close()
1394 mode = os.stat(tmpname).st_mode & 0o777
1395 self.assertEqual(mode, 0o644, "wrong file permissions")
1396 finally:
1397 os.umask(original_umask)
1398
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001399class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1400 pass
1401
1402class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1403 decompressor = bz2.BZ2Decompressor if bz2 else None
1404
1405class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1406 decompressor = lzma.LZMADecompressor if lzma else None
1407
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001408
Guido van Rossumd8faa362007-04-27 19:54:29 +00001409class GNUWriteTest(unittest.TestCase):
1410 # This testcase checks for correct creation of GNU Longname
1411 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001412
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001413 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001414 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001415 return blocks * 512
1416
1417 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001418 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001419 count = 512
1420
1421 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001422 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001423 count += 512
1424 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001425 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001426 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001427 count += 512
1428 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001429 return count
1430
1431 def _test(self, name, link=None):
1432 tarinfo = tarfile.TarInfo(name)
1433 if link:
1434 tarinfo.linkname = link
1435 tarinfo.type = tarfile.LNKTYPE
1436
Guido van Rossumd8faa362007-04-27 19:54:29 +00001437 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001438 try:
1439 tar.format = tarfile.GNU_FORMAT
1440 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001441
Antoine Pitrou95f55602010-09-23 18:36:46 +00001442 v1 = self._calc_size(name, link)
1443 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001444 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001445 finally:
1446 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001447
Guido van Rossumd8faa362007-04-27 19:54:29 +00001448 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001449 try:
1450 member = tar.next()
1451 self.assertIsNotNone(member,
1452 "unable to read longname member")
1453 self.assertEqual(tarinfo.name, member.name,
1454 "unable to read longname member")
1455 self.assertEqual(tarinfo.linkname, member.linkname,
1456 "unable to read longname member")
1457 finally:
1458 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001459
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001460 def test_longname_1023(self):
1461 self._test(("longnam/" * 127) + "longnam")
1462
1463 def test_longname_1024(self):
1464 self._test(("longnam/" * 127) + "longname")
1465
1466 def test_longname_1025(self):
1467 self._test(("longnam/" * 127) + "longname_")
1468
1469 def test_longlink_1023(self):
1470 self._test("name", ("longlnk/" * 127) + "longlnk")
1471
1472 def test_longlink_1024(self):
1473 self._test("name", ("longlnk/" * 127) + "longlink")
1474
1475 def test_longlink_1025(self):
1476 self._test("name", ("longlnk/" * 127) + "longlink_")
1477
1478 def test_longnamelink_1023(self):
1479 self._test(("longnam/" * 127) + "longnam",
1480 ("longlnk/" * 127) + "longlnk")
1481
1482 def test_longnamelink_1024(self):
1483 self._test(("longnam/" * 127) + "longname",
1484 ("longlnk/" * 127) + "longlink")
1485
1486 def test_longnamelink_1025(self):
1487 self._test(("longnam/" * 127) + "longname_",
1488 ("longlnk/" * 127) + "longlink_")
1489
Guido van Rossumd8faa362007-04-27 19:54:29 +00001490
Lars Gustäbel20703c62015-05-27 12:53:44 +02001491class CreateTest(WriteTestBase, unittest.TestCase):
Berker Peksag0fe63252015-02-13 21:02:12 +02001492
1493 prefix = "x:"
1494
1495 file_path = os.path.join(TEMPDIR, "spameggs42")
1496
1497 def setUp(self):
1498 support.unlink(tmpname)
1499
1500 @classmethod
1501 def setUpClass(cls):
1502 with open(cls.file_path, "wb") as fobj:
1503 fobj.write(b"aaa")
1504
1505 @classmethod
1506 def tearDownClass(cls):
1507 support.unlink(cls.file_path)
1508
1509 def test_create(self):
1510 with tarfile.open(tmpname, self.mode) as tobj:
1511 tobj.add(self.file_path)
1512
1513 with self.taropen(tmpname) as tobj:
1514 names = tobj.getnames()
1515 self.assertEqual(len(names), 1)
1516 self.assertIn('spameggs42', names[0])
1517
1518 def test_create_existing(self):
1519 with tarfile.open(tmpname, self.mode) as tobj:
1520 tobj.add(self.file_path)
1521
1522 with self.assertRaises(FileExistsError):
1523 tobj = tarfile.open(tmpname, self.mode)
1524
1525 with self.taropen(tmpname) as tobj:
1526 names = tobj.getnames()
1527 self.assertEqual(len(names), 1)
1528 self.assertIn('spameggs42', names[0])
1529
1530 def test_create_taropen(self):
1531 with self.taropen(tmpname, "x") as tobj:
1532 tobj.add(self.file_path)
1533
1534 with self.taropen(tmpname) as tobj:
1535 names = tobj.getnames()
1536 self.assertEqual(len(names), 1)
1537 self.assertIn('spameggs42', names[0])
1538
1539 def test_create_existing_taropen(self):
1540 with self.taropen(tmpname, "x") as tobj:
1541 tobj.add(self.file_path)
1542
1543 with self.assertRaises(FileExistsError):
1544 with self.taropen(tmpname, "x"):
1545 pass
1546
1547 with self.taropen(tmpname) as tobj:
1548 names = tobj.getnames()
1549 self.assertEqual(len(names), 1)
1550 self.assertIn("spameggs42", names[0])
1551
Serhiy Storchakac45cd162017-03-08 10:32:44 +02001552 def test_create_pathlike_name(self):
1553 with tarfile.open(pathlib.Path(tmpname), self.mode) as tobj:
1554 self.assertIsInstance(tobj.name, str)
1555 self.assertEqual(tobj.name, os.path.abspath(tmpname))
1556 tobj.add(pathlib.Path(self.file_path))
1557 names = tobj.getnames()
1558 self.assertEqual(len(names), 1)
1559 self.assertIn('spameggs42', names[0])
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_taropen_pathlike_name(self):
1567 with self.taropen(pathlib.Path(tmpname), "x") as tobj:
1568 self.assertIsInstance(tobj.name, str)
1569 self.assertEqual(tobj.name, os.path.abspath(tmpname))
1570 tobj.add(pathlib.Path(self.file_path))
1571 names = tobj.getnames()
1572 self.assertEqual(len(names), 1)
1573 self.assertIn('spameggs42', names[0])
1574
1575 with self.taropen(tmpname) as tobj:
1576 names = tobj.getnames()
1577 self.assertEqual(len(names), 1)
1578 self.assertIn('spameggs42', names[0])
1579
Berker Peksag0fe63252015-02-13 21:02:12 +02001580
1581class GzipCreateTest(GzipTest, CreateTest):
1582 pass
1583
1584
1585class Bz2CreateTest(Bz2Test, CreateTest):
1586 pass
1587
1588
1589class LzmaCreateTest(LzmaTest, CreateTest):
1590 pass
1591
1592
1593class CreateWithXModeTest(CreateTest):
1594
1595 prefix = "x"
1596
1597 test_create_taropen = None
1598 test_create_existing_taropen = None
1599
1600
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001601@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001602class HardlinkTest(unittest.TestCase):
1603 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001604
1605 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001606 self.foo = os.path.join(TEMPDIR, "foo")
1607 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001608
Antoine Pitrou95f55602010-09-23 18:36:46 +00001609 with open(self.foo, "wb") as fobj:
1610 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001611
Guido van Rossumd8faa362007-04-27 19:54:29 +00001612 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001613
Guido van Rossumd8faa362007-04-27 19:54:29 +00001614 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001615 self.tar.add(self.foo)
1616
Guido van Rossumd8faa362007-04-27 19:54:29 +00001617 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001618 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001619 support.unlink(self.foo)
1620 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001621
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001622 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001623 # The same name will be added as a REGTYPE every
1624 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001625 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001626 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001627 "add file as regular failed")
1628
1629 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001630 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001631 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001632 "add file as hardlink failed")
1633
1634 def test_dereference_hardlink(self):
1635 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001636 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001637 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001638 "dereferencing hardlink failed")
1639
Neal Norwitza4f651a2004-07-20 22:07:44 +00001640
Guido van Rossumd8faa362007-04-27 19:54:29 +00001641class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001642
Guido van Rossumd8faa362007-04-27 19:54:29 +00001643 def _test(self, name, link=None):
1644 # See GNUWriteTest.
1645 tarinfo = tarfile.TarInfo(name)
1646 if link:
1647 tarinfo.linkname = link
1648 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001649
Guido van Rossumd8faa362007-04-27 19:54:29 +00001650 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001651 try:
1652 tar.addfile(tarinfo)
1653 finally:
1654 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001655
Guido van Rossumd8faa362007-04-27 19:54:29 +00001656 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001657 try:
1658 if link:
1659 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001660 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001661 else:
1662 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001663 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001664 finally:
1665 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001666
Guido van Rossume7ba4952007-06-06 23:52:48 +00001667 def test_pax_global_header(self):
1668 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001669 "foo": "bar",
1670 "uid": "0",
1671 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001672 "test": "\xe4\xf6\xfc",
1673 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001674
Benjamin Peterson886af962010-03-21 23:13:07 +00001675 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001676 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001677 try:
1678 tar.addfile(tarfile.TarInfo("test"))
1679 finally:
1680 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001681
1682 # Test if the global header was written correctly.
1683 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001684 try:
1685 self.assertEqual(tar.pax_headers, pax_headers)
1686 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1687 # Test if all the fields are strings.
1688 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001689 self.assertIsNot(type(key), bytes)
1690 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001691 if key in tarfile.PAX_NUMBER_FIELDS:
1692 try:
1693 tarfile.PAX_NUMBER_FIELDS[key](val)
1694 except (TypeError, ValueError):
1695 self.fail("unable to convert pax header field")
1696 finally:
1697 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001698
1699 def test_pax_extended_header(self):
1700 # The fields from the pax header have priority over the
1701 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001702 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001703
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001704 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1705 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001706 try:
1707 t = tarfile.TarInfo()
1708 t.name = "\xe4\xf6\xfc" # non-ASCII
1709 t.uid = 8**8 # too large
1710 t.pax_headers = pax_headers
1711 tar.addfile(t)
1712 finally:
1713 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001714
1715 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001716 try:
1717 t = tar.getmembers()[0]
1718 self.assertEqual(t.pax_headers, pax_headers)
1719 self.assertEqual(t.name, "foo")
1720 self.assertEqual(t.uid, 123)
1721 finally:
1722 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001723
1724
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001725class UnicodeTest:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001726
1727 def test_iso8859_1_filename(self):
1728 self._test_unicode_filename("iso8859-1")
1729
1730 def test_utf7_filename(self):
1731 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001732
1733 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001734 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001735
Guido van Rossumd8faa362007-04-27 19:54:29 +00001736 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001737 tar = tarfile.open(tmpname, "w", format=self.format,
1738 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001739 try:
1740 name = "\xe4\xf6\xfc"
1741 tar.addfile(tarfile.TarInfo(name))
1742 finally:
1743 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001744
1745 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001746 try:
1747 self.assertEqual(tar.getmembers()[0].name, name)
1748 finally:
1749 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001750
1751 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001752 tar = tarfile.open(tmpname, "w", format=self.format,
1753 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001754 try:
1755 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001756
Antoine Pitrou95f55602010-09-23 18:36:46 +00001757 tarinfo.name = "\xe4\xf6\xfc"
1758 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001759
Antoine Pitrou95f55602010-09-23 18:36:46 +00001760 tarinfo.name = "foo"
1761 tarinfo.uname = "\xe4\xf6\xfc"
1762 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1763 finally:
1764 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001765
1766 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001767 tar = tarfile.open(tarname, "r",
1768 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001769 try:
1770 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001771 self.assertIs(type(t.name), str)
1772 self.assertIs(type(t.linkname), str)
1773 self.assertIs(type(t.uname), str)
1774 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001775 finally:
1776 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001777
Guido van Rossume7ba4952007-06-06 23:52:48 +00001778 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001779 t = tarfile.TarInfo("foo")
1780 t.uname = "\xe4\xf6\xfc"
1781 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001782
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001783 tar = tarfile.open(tmpname, mode="w", format=self.format,
1784 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001785 try:
1786 tar.addfile(t)
1787 finally:
1788 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001789
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001790 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001791 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001792 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001793 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1794 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1795
1796 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001797 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001798 tar = tarfile.open(tmpname, encoding="ascii")
1799 t = tar.getmember("foo")
1800 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1801 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1802 finally:
1803 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001804
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001805
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001806class UstarUnicodeTest(UnicodeTest, unittest.TestCase):
1807
1808 format = tarfile.USTAR_FORMAT
1809
1810 # Test whether the utf-8 encoded version of a filename exceeds the 100
1811 # bytes name field limit (every occurrence of '\xff' will be expanded to 2
1812 # bytes).
1813 def test_unicode_name1(self):
1814 self._test_ustar_name("0123456789" * 10)
1815 self._test_ustar_name("0123456789" * 10 + "0", ValueError)
1816 self._test_ustar_name("0123456789" * 9 + "01234567\xff")
1817 self._test_ustar_name("0123456789" * 9 + "012345678\xff", ValueError)
1818
1819 def test_unicode_name2(self):
1820 self._test_ustar_name("0123456789" * 9 + "012345\xff\xff")
1821 self._test_ustar_name("0123456789" * 9 + "0123456\xff\xff", ValueError)
1822
1823 # Test whether the utf-8 encoded version of a filename exceeds the 155
1824 # bytes prefix + '/' + 100 bytes name limit.
1825 def test_unicode_longname1(self):
1826 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 10)
1827 self._test_ustar_name("0123456789" * 15 + "0123/4" + "0123456789" * 10, ValueError)
1828 self._test_ustar_name("0123456789" * 15 + "012\xff/" + "0123456789" * 10)
1829 self._test_ustar_name("0123456789" * 15 + "0123\xff/" + "0123456789" * 10, ValueError)
1830
1831 def test_unicode_longname2(self):
1832 self._test_ustar_name("0123456789" * 15 + "01\xff/2" + "0123456789" * 10, ValueError)
1833 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/" + "0123456789" * 10, ValueError)
1834
1835 def test_unicode_longname3(self):
1836 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/2" + "0123456789" * 10, ValueError)
1837 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "01234567\xff")
1838 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345678\xff", ValueError)
1839
1840 def test_unicode_longname4(self):
1841 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345\xff\xff")
1842 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "0123456\xff\xff", ValueError)
1843
1844 def _test_ustar_name(self, name, exc=None):
1845 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1846 t = tarfile.TarInfo(name)
1847 if exc is None:
1848 tar.addfile(t)
1849 else:
1850 self.assertRaises(exc, tar.addfile, t)
1851
1852 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001853 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001854 for t in tar:
1855 self.assertEqual(name, t.name)
1856 break
1857
1858 # Test the same as above for the 100 bytes link field.
1859 def test_unicode_link1(self):
1860 self._test_ustar_link("0123456789" * 10)
1861 self._test_ustar_link("0123456789" * 10 + "0", ValueError)
1862 self._test_ustar_link("0123456789" * 9 + "01234567\xff")
1863 self._test_ustar_link("0123456789" * 9 + "012345678\xff", ValueError)
1864
1865 def test_unicode_link2(self):
1866 self._test_ustar_link("0123456789" * 9 + "012345\xff\xff")
1867 self._test_ustar_link("0123456789" * 9 + "0123456\xff\xff", ValueError)
1868
1869 def _test_ustar_link(self, name, exc=None):
1870 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1871 t = tarfile.TarInfo("foo")
1872 t.linkname = name
1873 if exc is None:
1874 tar.addfile(t)
1875 else:
1876 self.assertRaises(exc, tar.addfile, t)
1877
1878 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001879 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001880 for t in tar:
1881 self.assertEqual(name, t.linkname)
1882 break
1883
1884
1885class GNUUnicodeTest(UnicodeTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001886
Guido van Rossume7ba4952007-06-06 23:52:48 +00001887 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001888
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001889 def test_bad_pax_header(self):
1890 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1891 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001892 for encoding, name in (
1893 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001894 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001895 with tarfile.open(tarname, encoding=encoding,
1896 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001897 try:
1898 t = tar.getmember(name)
1899 except KeyError:
1900 self.fail("unable to read bad GNU tar pax header")
1901
Guido van Rossumd8faa362007-04-27 19:54:29 +00001902
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001903class PAXUnicodeTest(UnicodeTest, unittest.TestCase):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001904
1905 format = tarfile.PAX_FORMAT
1906
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001907 # PAX_FORMAT ignores encoding in write mode.
1908 test_unicode_filename_error = None
1909
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001910 def test_binary_header(self):
1911 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001912 for encoding, name in (
1913 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001914 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001915 with tarfile.open(tarname, encoding=encoding,
1916 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001917 try:
1918 t = tar.getmember(name)
1919 except KeyError:
1920 self.fail("unable to read POSIX.1-2008 binary header")
1921
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001922
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001923class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001924 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001925
Guido van Rossumd8faa362007-04-27 19:54:29 +00001926 def setUp(self):
1927 self.tarname = tmpname
1928 if os.path.exists(self.tarname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001929 support.unlink(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001930
Guido van Rossumd8faa362007-04-27 19:54:29 +00001931 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001932 with tarfile.open(tarname, encoding="iso8859-1") as src:
1933 t = src.getmember("ustar/regtype")
1934 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001935 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001936 with tarfile.open(self.tarname, mode) as tar:
1937 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001938
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001939 def test_append_compressed(self):
1940 self._create_testtar("w:" + self.suffix)
1941 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1942
1943class AppendTest(AppendTestBase, unittest.TestCase):
1944 test_append_compressed = None
1945
1946 def _add_testfile(self, fileobj=None):
1947 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1948 tar.addfile(tarfile.TarInfo("bar"))
1949
Guido van Rossumd8faa362007-04-27 19:54:29 +00001950 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001951 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1952 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001953
1954 def test_non_existing(self):
1955 self._add_testfile()
1956 self._test()
1957
1958 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001959 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001960 self._add_testfile()
1961 self._test()
1962
1963 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001964 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001965 self._add_testfile(fobj)
1966 fobj.seek(0)
1967 self._test(fileobj=fobj)
1968
1969 def test_fileobj(self):
1970 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001971 with open(self.tarname, "rb") as fobj:
1972 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001973 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001974 self._add_testfile(fobj)
1975 fobj.seek(0)
1976 self._test(names=["foo", "bar"], fileobj=fobj)
1977
1978 def test_existing(self):
1979 self._create_testtar()
1980 self._add_testfile()
1981 self._test(names=["foo", "bar"])
1982
Lars Gustäbel9520a432009-11-22 18:48:49 +00001983 # Append mode is supposed to fail if the tarfile to append to
1984 # does not end with a zero block.
1985 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001986 with open(self.tarname, "wb") as fobj:
1987 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001988 self.assertRaises(tarfile.ReadError, self._add_testfile)
1989
1990 def test_null(self):
1991 self._test_error(b"")
1992
1993 def test_incomplete(self):
1994 self._test_error(b"\0" * 13)
1995
1996 def test_premature_eof(self):
1997 data = tarfile.TarInfo("foo").tobuf()
1998 self._test_error(data)
1999
2000 def test_trailing_garbage(self):
2001 data = tarfile.TarInfo("foo").tobuf()
2002 self._test_error(data + b"\0" * 13)
2003
2004 def test_invalid(self):
2005 self._test_error(b"a" * 512)
2006
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002007class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
2008 pass
2009
2010class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
2011 pass
2012
2013class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
2014 pass
2015
Guido van Rossumd8faa362007-04-27 19:54:29 +00002016
2017class LimitsTest(unittest.TestCase):
2018
2019 def test_ustar_limits(self):
2020 # 100 char name
2021 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002022 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002023
2024 # 101 char name that cannot be stored
2025 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002026 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002027
2028 # 256 char name with a slash at pos 156
2029 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002030 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002031
2032 # 256 char name that cannot be stored
2033 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002034 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002035
2036 # 512 char name
2037 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002038 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002039
2040 # 512 char linkname
2041 tarinfo = tarfile.TarInfo("longlink")
2042 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002043 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002044
2045 # uid > 8 digits
2046 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002047 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002048 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002049
2050 def test_gnu_limits(self):
2051 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002052 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002053
2054 tarinfo = tarfile.TarInfo("longlink")
2055 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002056 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002057
2058 # uid >= 256 ** 7
2059 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002060 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002061 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002062
2063 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002064 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002065 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002066
2067 tarinfo = tarfile.TarInfo("longlink")
2068 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002069 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002070
2071 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002072 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002073 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002074
2075
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002076class MiscTest(unittest.TestCase):
2077
2078 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002079 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
2080 b"foo\0\0\0\0\0")
2081 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
2082 b"foo")
2083 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
2084 "foo")
2085 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
2086 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002087
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002088 def test_read_number_fields(self):
2089 # Issue 13158: Test if GNU tar specific base-256 number fields
2090 # are decoded correctly.
2091 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
2092 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002093 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
2094 0o10000000)
2095 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
2096 0xffffffff)
2097 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
2098 -1)
2099 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
2100 -100)
2101 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
2102 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002103
Lars Gustäbelb7a688b2015-07-02 19:38:38 +02002104 # Issue 24514: Test if empty number fields are converted to zero.
2105 self.assertEqual(tarfile.nti(b"\0"), 0)
2106 self.assertEqual(tarfile.nti(b" \0"), 0)
2107
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002108 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002109 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002110 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002111 self.assertEqual(tarfile.itn(0o10000000),
2112 b"\x80\x00\x00\x00\x00\x20\x00\x00")
2113 self.assertEqual(tarfile.itn(0xffffffff),
2114 b"\x80\x00\x00\x00\xff\xff\xff\xff")
2115 self.assertEqual(tarfile.itn(-1),
2116 b"\xff\xff\xff\xff\xff\xff\xff\xff")
2117 self.assertEqual(tarfile.itn(-100),
2118 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
2119 self.assertEqual(tarfile.itn(-0x100000000000000),
2120 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002121
2122 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002123 with self.assertRaises(ValueError):
2124 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
2125 with self.assertRaises(ValueError):
2126 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
2127 with self.assertRaises(ValueError):
2128 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
2129 with self.assertRaises(ValueError):
2130 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002131
Martin Panter104dcda2016-01-16 06:59:13 +00002132 def test__all__(self):
Martin Panter5318d102016-01-16 11:01:14 +00002133 blacklist = {'version', 'grp', 'pwd', 'symlink_exception',
Martin Panter104dcda2016-01-16 06:59:13 +00002134 'NUL', 'BLOCKSIZE', 'RECORDSIZE', 'GNU_MAGIC',
2135 'POSIX_MAGIC', 'LENGTH_NAME', 'LENGTH_LINK',
2136 'LENGTH_PREFIX', 'REGTYPE', 'AREGTYPE', 'LNKTYPE',
2137 'SYMTYPE', 'CHRTYPE', 'BLKTYPE', 'DIRTYPE', 'FIFOTYPE',
2138 'CONTTYPE', 'GNUTYPE_LONGNAME', 'GNUTYPE_LONGLINK',
2139 'GNUTYPE_SPARSE', 'XHDTYPE', 'XGLTYPE', 'SOLARIS_XHDTYPE',
2140 'SUPPORTED_TYPES', 'REGULAR_TYPES', 'GNU_TYPES',
2141 'PAX_FIELDS', 'PAX_NAME_FIELDS', 'PAX_NUMBER_FIELDS',
2142 'stn', 'nts', 'nti', 'itn', 'calc_chksums', 'copyfileobj',
2143 'filemode',
2144 'EmptyHeaderError', 'TruncatedHeaderError',
2145 'EOFHeaderError', 'InvalidHeaderError',
Serhiy Storchaka2c1d3e32016-01-16 11:05:11 +02002146 'SubsequentHeaderError', 'ExFileObject',
Martin Panter104dcda2016-01-16 06:59:13 +00002147 'main'}
2148 support.check__all__(self, tarfile, blacklist=blacklist)
2149
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002150
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002151class CommandLineTest(unittest.TestCase):
2152
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002153 def tarfilecmd(self, *args, **kwargs):
2154 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
2155 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01002156 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002157
2158 def tarfilecmd_failure(self, *args):
2159 return script_helper.assert_python_failure('-m', 'tarfile', *args)
2160
2161 def make_simple_tarfile(self, tar_name):
2162 files = [support.findfile('tokenize_tests.txt'),
2163 support.findfile('tokenize_tests-no-coding-cookie-'
2164 'and-utf8-bom-sig-only.txt')]
2165 self.addCleanup(support.unlink, tar_name)
2166 with tarfile.open(tar_name, 'w') as tf:
2167 for tardata in files:
2168 tf.add(tardata, arcname=os.path.basename(tardata))
2169
Serhiy Storchaka150cd192017-04-07 18:56:12 +03002170 def test_bad_use(self):
2171 rc, out, err = self.tarfilecmd_failure()
2172 self.assertEqual(out, b'')
2173 self.assertIn(b'usage', err.lower())
2174 self.assertIn(b'error', err.lower())
2175 self.assertIn(b'required', err.lower())
2176 rc, out, err = self.tarfilecmd_failure('-l', '')
2177 self.assertEqual(out, b'')
2178 self.assertNotEqual(err.strip(), b'')
2179
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002180 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002181 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002182 for opt in '-t', '--test':
2183 out = self.tarfilecmd(opt, tar_name)
2184 self.assertEqual(out, b'')
2185
2186 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002187 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002188 for opt in '-v', '--verbose':
2189 out = self.tarfilecmd(opt, '-t', tar_name)
2190 self.assertIn(b'is a tar archive.\n', out)
2191
2192 def test_test_command_invalid_file(self):
2193 zipname = support.findfile('zipdir.zip')
2194 rc, out, err = self.tarfilecmd_failure('-t', zipname)
2195 self.assertIn(b' is not a tar archive.', err)
2196 self.assertEqual(out, b'')
2197 self.assertEqual(rc, 1)
2198
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002199 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002200 with self.subTest(tar_name=tar_name):
2201 with open(tar_name, 'rb') as f:
2202 data = f.read()
2203 try:
2204 with open(tmpname, 'wb') as f:
2205 f.write(data[:511])
2206 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
2207 self.assertEqual(out, b'')
2208 self.assertEqual(rc, 1)
2209 finally:
2210 support.unlink(tmpname)
2211
2212 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002213 for tar_name in testtarnames:
2214 with support.captured_stdout() as t:
2215 with tarfile.open(tar_name, 'r') as tf:
2216 tf.list(verbose=False)
2217 expected = t.getvalue().encode('ascii', 'backslashreplace')
2218 for opt in '-l', '--list':
2219 out = self.tarfilecmd(opt, tar_name,
2220 PYTHONIOENCODING='ascii')
2221 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002222
2223 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002224 for tar_name in testtarnames:
2225 with support.captured_stdout() as t:
2226 with tarfile.open(tar_name, 'r') as tf:
2227 tf.list(verbose=True)
2228 expected = t.getvalue().encode('ascii', 'backslashreplace')
2229 for opt in '-v', '--verbose':
2230 out = self.tarfilecmd(opt, '-l', tar_name,
2231 PYTHONIOENCODING='ascii')
2232 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002233
2234 def test_list_command_invalid_file(self):
2235 zipname = support.findfile('zipdir.zip')
2236 rc, out, err = self.tarfilecmd_failure('-l', zipname)
2237 self.assertIn(b' is not a tar archive.', err)
2238 self.assertEqual(out, b'')
2239 self.assertEqual(rc, 1)
2240
2241 def test_create_command(self):
2242 files = [support.findfile('tokenize_tests.txt'),
2243 support.findfile('tokenize_tests-no-coding-cookie-'
2244 'and-utf8-bom-sig-only.txt')]
2245 for opt in '-c', '--create':
2246 try:
2247 out = self.tarfilecmd(opt, tmpname, *files)
2248 self.assertEqual(out, b'')
2249 with tarfile.open(tmpname) as tar:
2250 tar.getmembers()
2251 finally:
2252 support.unlink(tmpname)
2253
2254 def test_create_command_verbose(self):
2255 files = [support.findfile('tokenize_tests.txt'),
2256 support.findfile('tokenize_tests-no-coding-cookie-'
2257 'and-utf8-bom-sig-only.txt')]
2258 for opt in '-v', '--verbose':
2259 try:
2260 out = self.tarfilecmd(opt, '-c', tmpname, *files)
2261 self.assertIn(b' file created.', out)
2262 with tarfile.open(tmpname) as tar:
2263 tar.getmembers()
2264 finally:
2265 support.unlink(tmpname)
2266
2267 def test_create_command_dotless_filename(self):
2268 files = [support.findfile('tokenize_tests.txt')]
2269 try:
2270 out = self.tarfilecmd('-c', dotlessname, *files)
2271 self.assertEqual(out, b'')
2272 with tarfile.open(dotlessname) as tar:
2273 tar.getmembers()
2274 finally:
2275 support.unlink(dotlessname)
2276
2277 def test_create_command_dot_started_filename(self):
2278 tar_name = os.path.join(TEMPDIR, ".testtar")
2279 files = [support.findfile('tokenize_tests.txt')]
2280 try:
2281 out = self.tarfilecmd('-c', tar_name, *files)
2282 self.assertEqual(out, b'')
2283 with tarfile.open(tar_name) as tar:
2284 tar.getmembers()
2285 finally:
2286 support.unlink(tar_name)
2287
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002288 def test_create_command_compressed(self):
2289 files = [support.findfile('tokenize_tests.txt'),
2290 support.findfile('tokenize_tests-no-coding-cookie-'
2291 'and-utf8-bom-sig-only.txt')]
2292 for filetype in (GzipTest, Bz2Test, LzmaTest):
2293 if not filetype.open:
2294 continue
2295 try:
2296 tar_name = tmpname + '.' + filetype.suffix
2297 out = self.tarfilecmd('-c', tar_name, *files)
2298 with filetype.taropen(tar_name) as tar:
2299 tar.getmembers()
2300 finally:
2301 support.unlink(tar_name)
2302
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002303 def test_extract_command(self):
2304 self.make_simple_tarfile(tmpname)
2305 for opt in '-e', '--extract':
2306 try:
2307 with support.temp_cwd(tarextdir):
2308 out = self.tarfilecmd(opt, tmpname)
2309 self.assertEqual(out, b'')
2310 finally:
2311 support.rmtree(tarextdir)
2312
2313 def test_extract_command_verbose(self):
2314 self.make_simple_tarfile(tmpname)
2315 for opt in '-v', '--verbose':
2316 try:
2317 with support.temp_cwd(tarextdir):
2318 out = self.tarfilecmd(opt, '-e', tmpname)
2319 self.assertIn(b' file is extracted.', out)
2320 finally:
2321 support.rmtree(tarextdir)
2322
2323 def test_extract_command_different_directory(self):
2324 self.make_simple_tarfile(tmpname)
2325 try:
2326 with support.temp_cwd(tarextdir):
2327 out = self.tarfilecmd('-e', tmpname, 'spamdir')
2328 self.assertEqual(out, b'')
2329 finally:
2330 support.rmtree(tarextdir)
2331
2332 def test_extract_command_invalid_file(self):
2333 zipname = support.findfile('zipdir.zip')
2334 with support.temp_cwd(tarextdir):
2335 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2336 self.assertIn(b' is not a tar archive.', err)
2337 self.assertEqual(out, b'')
2338 self.assertEqual(rc, 1)
2339
2340
Lars Gustäbel01385812010-03-03 12:08:54 +00002341class ContextManagerTest(unittest.TestCase):
2342
2343 def test_basic(self):
2344 with tarfile.open(tarname) as tar:
2345 self.assertFalse(tar.closed, "closed inside runtime context")
2346 self.assertTrue(tar.closed, "context manager failed")
2347
2348 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002349 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002350 # if the TarFile object is already closed.
2351 tar = tarfile.open(tarname)
2352 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002353 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002354 with tar:
2355 pass
2356
2357 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002358 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002359 with self.assertRaises(Exception) as exc:
2360 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002361 raise OSError
2362 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002363 "wrong exception raised in context manager")
2364 self.assertTrue(tar.closed, "context manager failed")
2365
2366 def test_no_eof(self):
2367 # __exit__() must not write end-of-archive blocks if an
2368 # exception was raised.
2369 try:
2370 with tarfile.open(tmpname, "w") as tar:
2371 raise Exception
2372 except:
2373 pass
2374 self.assertEqual(os.path.getsize(tmpname), 0,
2375 "context manager wrote an end-of-archive block")
2376 self.assertTrue(tar.closed, "context manager failed")
2377
2378 def test_eof(self):
2379 # __exit__() must write end-of-archive blocks, i.e. call
2380 # TarFile.close() if there was no error.
2381 with tarfile.open(tmpname, "w"):
2382 pass
2383 self.assertNotEqual(os.path.getsize(tmpname), 0,
2384 "context manager wrote no end-of-archive block")
2385
2386 def test_fileobj(self):
2387 # Test that __exit__() did not close the external file
2388 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002389 with open(tmpname, "wb") as fobj:
2390 try:
2391 with tarfile.open(fileobj=fobj, mode="w") as tar:
2392 raise Exception
2393 except:
2394 pass
2395 self.assertFalse(fobj.closed, "external file object was closed")
2396 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002397
2398
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002399@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2400class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002401
2402 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002403 # symbolic or hard links tarfile tries to extract these types of members
2404 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002405 def _test_link_extraction(self, name):
2406 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002407 with open(os.path.join(TEMPDIR, name), "rb") as f:
2408 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002409 self.assertEqual(md5sum(data), md5_regtype)
2410
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002411 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002412 @unittest.skipIf(hasattr(os.path, "islink"),
2413 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002414 def test_hardlink_extraction1(self):
2415 self._test_link_extraction("ustar/lnktype")
2416
Brian Curtind40e6f72010-07-08 21:39:08 +00002417 @unittest.skipIf(hasattr(os.path, "islink"),
2418 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002419 def test_hardlink_extraction2(self):
2420 self._test_link_extraction("./ustar/linktest2/lnktype")
2421
Brian Curtin74e45612010-07-09 15:58:59 +00002422 @unittest.skipIf(hasattr(os, "symlink"),
2423 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002424 def test_symlink_extraction1(self):
2425 self._test_link_extraction("ustar/symtype")
2426
Brian Curtin74e45612010-07-09 15:58:59 +00002427 @unittest.skipIf(hasattr(os, "symlink"),
2428 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002429 def test_symlink_extraction2(self):
2430 self._test_link_extraction("./ustar/linktest2/symtype")
2431
2432
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002433class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002434 # Issue5068: The _BZ2Proxy.read() method loops forever
2435 # on an empty or partial bzipped file.
2436
2437 def _test_partial_input(self, mode):
2438 class MyBytesIO(io.BytesIO):
2439 hit_eof = False
2440 def read(self, n):
2441 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002442 raise AssertionError("infinite loop detected in "
2443 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002444 self.hit_eof = self.tell() == len(self.getvalue())
2445 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002446 def seek(self, *args):
2447 self.hit_eof = False
2448 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002449
2450 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2451 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002452 try:
2453 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2454 except tarfile.ReadError:
2455 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002456
2457 def test_partial_input(self):
2458 self._test_partial_input("r")
2459
2460 def test_partial_input_bz2(self):
2461 self._test_partial_input("r:bz2")
2462
2463
Eric V. Smith7a803892015-04-15 10:27:58 -04002464def root_is_uid_gid_0():
2465 try:
2466 import pwd, grp
2467 except ImportError:
2468 return False
2469 if pwd.getpwuid(0)[0] != 'root':
2470 return False
2471 if grp.getgrgid(0)[0] != 'root':
2472 return False
2473 return True
2474
2475
Zachary Waread3e27a2015-05-12 23:57:21 -05002476@unittest.skipUnless(hasattr(os, 'chown'), "missing os.chown")
2477@unittest.skipUnless(hasattr(os, 'geteuid'), "missing os.geteuid")
Eric V. Smith7a803892015-04-15 10:27:58 -04002478class NumericOwnerTest(unittest.TestCase):
2479 # mock the following:
2480 # os.chown: so we can test what's being called
2481 # os.chmod: so the modes are not actually changed. if they are, we can't
2482 # delete the files/directories
2483 # os.geteuid: so we can lie and say we're root (uid = 0)
2484
2485 @staticmethod
2486 def _make_test_archive(filename_1, dirname_1, filename_2):
2487 # the file contents to write
2488 fobj = io.BytesIO(b"content")
2489
2490 # create a tar file with a file, a directory, and a file within that
2491 # directory. Assign various .uid/.gid values to them
2492 items = [(filename_1, 99, 98, tarfile.REGTYPE, fobj),
2493 (dirname_1, 77, 76, tarfile.DIRTYPE, None),
2494 (filename_2, 88, 87, tarfile.REGTYPE, fobj),
2495 ]
2496 with tarfile.open(tmpname, 'w') as tarfl:
2497 for name, uid, gid, typ, contents in items:
2498 t = tarfile.TarInfo(name)
2499 t.uid = uid
2500 t.gid = gid
2501 t.uname = 'root'
2502 t.gname = 'root'
2503 t.type = typ
2504 tarfl.addfile(t, contents)
2505
2506 # return the full pathname to the tar file
2507 return tmpname
2508
2509 @staticmethod
2510 @contextmanager
2511 def _setup_test(mock_geteuid):
2512 mock_geteuid.return_value = 0 # lie and say we're root
2513 fname = 'numeric-owner-testfile'
2514 dirname = 'dir'
2515
2516 # the names we want stored in the tarfile
2517 filename_1 = fname
2518 dirname_1 = dirname
2519 filename_2 = os.path.join(dirname, fname)
2520
2521 # create the tarfile with the contents we're after
2522 tar_filename = NumericOwnerTest._make_test_archive(filename_1,
2523 dirname_1,
2524 filename_2)
2525
2526 # open the tarfile for reading. yield it and the names of the items
2527 # we stored into the file
2528 with tarfile.open(tar_filename) as tarfl:
2529 yield tarfl, filename_1, dirname_1, filename_2
2530
2531 @unittest.mock.patch('os.chown')
2532 @unittest.mock.patch('os.chmod')
2533 @unittest.mock.patch('os.geteuid')
2534 def test_extract_with_numeric_owner(self, mock_geteuid, mock_chmod,
2535 mock_chown):
2536 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _,
2537 filename_2):
2538 tarfl.extract(filename_1, TEMPDIR, numeric_owner=True)
2539 tarfl.extract(filename_2 , TEMPDIR, numeric_owner=True)
2540
2541 # convert to filesystem paths
2542 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2543 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2544
2545 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2546 unittest.mock.call(f_filename_2, 88, 87),
2547 ],
2548 any_order=True)
2549
2550 @unittest.mock.patch('os.chown')
2551 @unittest.mock.patch('os.chmod')
2552 @unittest.mock.patch('os.geteuid')
2553 def test_extractall_with_numeric_owner(self, mock_geteuid, mock_chmod,
2554 mock_chown):
2555 with self._setup_test(mock_geteuid) as (tarfl, filename_1, dirname_1,
2556 filename_2):
2557 tarfl.extractall(TEMPDIR, numeric_owner=True)
2558
2559 # convert to filesystem paths
2560 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2561 f_dirname_1 = os.path.join(TEMPDIR, dirname_1)
2562 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2563
2564 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2565 unittest.mock.call(f_dirname_1, 77, 76),
2566 unittest.mock.call(f_filename_2, 88, 87),
2567 ],
2568 any_order=True)
2569
2570 # this test requires that uid=0 and gid=0 really be named 'root'. that's
2571 # because the uname and gname in the test file are 'root', and extract()
2572 # will look them up using pwd and grp to find their uid and gid, which we
2573 # test here to be 0.
2574 @unittest.skipUnless(root_is_uid_gid_0(),
2575 'uid=0,gid=0 must be named "root"')
2576 @unittest.mock.patch('os.chown')
2577 @unittest.mock.patch('os.chmod')
2578 @unittest.mock.patch('os.geteuid')
2579 def test_extract_without_numeric_owner(self, mock_geteuid, mock_chmod,
2580 mock_chown):
2581 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2582 tarfl.extract(filename_1, TEMPDIR, numeric_owner=False)
2583
2584 # convert to filesystem paths
2585 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2586
2587 mock_chown.assert_called_with(f_filename_1, 0, 0)
2588
2589 @unittest.mock.patch('os.geteuid')
2590 def test_keyword_only(self, mock_geteuid):
2591 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2592 self.assertRaises(TypeError,
2593 tarfl.extract, filename_1, TEMPDIR, False, True)
2594
2595
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002596def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002597 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002598 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002599
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002600 global testtarnames
2601 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002602 with open(tarname, "rb") as fobj:
2603 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002604
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002605 # Create compressed tarfiles.
2606 for c in GzipTest, Bz2Test, LzmaTest:
2607 if c.open:
2608 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002609 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002610 with c.open(c.tarname, "wb") as tar:
2611 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002612
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002613def tearDownModule():
2614 if os.path.exists(TEMPDIR):
Tim Goldene0bd2c52014-05-06 13:24:26 +01002615 support.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002616
Neal Norwitz996acf12003-02-17 14:51:41 +00002617if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002618 unittest.main()