blob: 7d2eec8a7ccfaa7a0d475e3461e775c8b02ca6eb [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
Victor Stinner8c663fd2017-11-08 14:44:44 -0800782 # the '9' represents the blocksize (900,000 bytes). If the file was
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100783 # 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
Victor Stinner8c663fd2017-11-08 14:44:44 -0800787 # Compress with blocksize 100,000 bytes, the file starts with "BZh11".
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100788 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
Bernhard M. Wiedemann84521042018-01-31 11:17:10 +01001132 # mock the following:
1133 # os.listdir: so we know that files are in the wrong order
Bernhard M. Wiedemann4ad703b2018-02-06 19:08:53 +01001134 def test_ordered_recursion(self):
Bernhard M. Wiedemann84521042018-01-31 11:17:10 +01001135 path = os.path.join(TEMPDIR, "directory")
1136 os.mkdir(path)
1137 open(os.path.join(path, "1"), "a").close()
1138 open(os.path.join(path, "2"), "a").close()
Bernhard M. Wiedemann84521042018-01-31 11:17:10 +01001139 try:
1140 tar = tarfile.open(tmpname, self.mode)
1141 try:
Bernhard M. Wiedemann4ad703b2018-02-06 19:08:53 +01001142 with unittest.mock.patch('os.listdir') as mock_listdir:
1143 mock_listdir.return_value = ["2", "1"]
1144 tar.add(path)
Bernhard M. Wiedemann84521042018-01-31 11:17:10 +01001145 paths = []
1146 for m in tar.getmembers():
1147 paths.append(os.path.split(m.name)[-1])
1148 self.assertEqual(paths, ["directory", "1", "2"]);
1149 finally:
1150 tar.close()
1151 finally:
1152 support.unlink(os.path.join(path, "1"))
1153 support.unlink(os.path.join(path, "2"))
1154 support.rmdir(path)
1155
Serhiy Storchakac45cd162017-03-08 10:32:44 +02001156 def test_gettarinfo_pathlike_name(self):
1157 with tarfile.open(tmpname, self.mode) as tar:
1158 path = pathlib.Path(TEMPDIR) / "file"
1159 with open(path, "wb") as fobj:
1160 fobj.write(b"aaa")
1161 tarinfo = tar.gettarinfo(path)
1162 tarinfo2 = tar.gettarinfo(os.fspath(path))
1163 self.assertIsInstance(tarinfo.name, str)
1164 self.assertEqual(tarinfo.name, tarinfo2.name)
1165 self.assertEqual(tarinfo.size, 3)
1166
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001167 @unittest.skipUnless(hasattr(os, "link"),
1168 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001169 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001170 link = os.path.join(TEMPDIR, "link")
1171 target = os.path.join(TEMPDIR, "link_target")
1172 with open(target, "wb") as fobj:
1173 fobj.write(b"aaa")
xdegayed7d4fea2017-11-12 18:02:06 +01001174 try:
1175 os.link(target, link)
1176 except PermissionError as e:
1177 self.skipTest('os.link(): %s' % e)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001178 try:
1179 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001180 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001181 # Record the link target in the inodes list.
1182 tar.gettarinfo(target)
1183 tarinfo = tar.gettarinfo(link)
1184 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001185 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001186 tar.close()
1187 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001188 support.unlink(target)
1189 support.unlink(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001190
Brian Curtin3b4499c2010-12-28 14:31:47 +00001191 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +00001192 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +00001193 path = os.path.join(TEMPDIR, "symlink")
1194 os.symlink("link_target", path)
1195 try:
1196 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001197 try:
1198 tarinfo = tar.gettarinfo(path)
1199 self.assertEqual(tarinfo.size, 0)
1200 finally:
1201 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +00001202 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001203 support.unlink(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001204
1205 def test_add_self(self):
1206 # Test for #1257255.
1207 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001208 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001209 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001210 self.assertEqual(tar.name, dstname,
1211 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001212 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001213 self.assertEqual(tar.getnames(), [],
1214 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001216 with support.change_cwd(TEMPDIR):
1217 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001218 self.assertEqual(tar.getnames(), [],
1219 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001220 finally:
1221 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001222
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001223 def test_filter(self):
1224 tempdir = os.path.join(TEMPDIR, "filter")
1225 os.mkdir(tempdir)
1226 try:
1227 for name in ("foo", "bar", "baz"):
1228 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001229 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001230
1231 def filter(tarinfo):
1232 if os.path.basename(tarinfo.name) == "bar":
1233 return
1234 tarinfo.uid = 123
1235 tarinfo.uname = "foo"
1236 return tarinfo
1237
1238 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001239 try:
1240 tar.add(tempdir, arcname="empty_dir", filter=filter)
1241 finally:
1242 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001243
Raymond Hettingera63a3122011-01-26 20:34:14 +00001244 # Verify that filter is a keyword-only argument
1245 with self.assertRaises(TypeError):
1246 tar.add(tempdir, "empty_dir", True, None, filter)
1247
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001248 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001249 try:
1250 for tarinfo in tar:
1251 self.assertEqual(tarinfo.uid, 123)
1252 self.assertEqual(tarinfo.uname, "foo")
1253 self.assertEqual(len(tar.getmembers()), 3)
1254 finally:
1255 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001256 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001257 support.rmtree(tempdir)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001258
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001259 # Guarantee that stored pathnames are not modified. Don't
1260 # remove ./ or ../ or double slashes. Still make absolute
1261 # pathnames relative.
1262 # For details see bug #6054.
1263 def _test_pathname(self, path, cmp_path=None, dir=False):
1264 # Create a tarfile with an empty member named path
1265 # and compare the stored name with the original.
1266 foo = os.path.join(TEMPDIR, "foo")
1267 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001268 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001269 else:
1270 os.mkdir(foo)
1271
1272 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001273 try:
1274 tar.add(foo, arcname=path)
1275 finally:
1276 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001277
1278 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001279 try:
1280 t = tar.next()
1281 finally:
1282 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001283
1284 if not dir:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001285 support.unlink(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001286 else:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001287 support.rmdir(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001288
1289 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1290
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001291
1292 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001293 def test_extractall_symlinks(self):
1294 # Test if extractall works properly when tarfile contains symlinks
1295 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1296 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1297 os.mkdir(tempdir)
1298 try:
1299 source_file = os.path.join(tempdir,'source')
1300 target_file = os.path.join(tempdir,'symlink')
1301 with open(source_file,'w') as f:
1302 f.write('something\n')
1303 os.symlink(source_file, target_file)
1304 tar = tarfile.open(temparchive,'w')
1305 tar.add(source_file)
1306 tar.add(target_file)
1307 tar.close()
1308 # Let's extract it to the location which contains the symlink
1309 tar = tarfile.open(temparchive,'r')
1310 # this should not raise OSError: [Errno 17] File exists
1311 try:
1312 tar.extractall(path=tempdir)
1313 except OSError:
1314 self.fail("extractall failed with symlinked files")
1315 finally:
1316 tar.close()
1317 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001318 support.unlink(temparchive)
1319 support.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001320
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001321 def test_pathnames(self):
1322 self._test_pathname("foo")
1323 self._test_pathname(os.path.join("foo", ".", "bar"))
1324 self._test_pathname(os.path.join("foo", "..", "bar"))
1325 self._test_pathname(os.path.join(".", "foo"))
1326 self._test_pathname(os.path.join(".", "foo", "."))
1327 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1328 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1329 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1330 self._test_pathname(os.path.join("..", "foo"))
1331 self._test_pathname(os.path.join("..", "foo", ".."))
1332 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1333 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1334
1335 self._test_pathname("foo" + os.sep + os.sep + "bar")
1336 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1337
1338 def test_abs_pathnames(self):
1339 if sys.platform == "win32":
1340 self._test_pathname("C:\\foo", "foo")
1341 else:
1342 self._test_pathname("/foo", "foo")
1343 self._test_pathname("///foo", "foo")
1344
1345 def test_cwd(self):
1346 # Test adding the current working directory.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001347 with support.change_cwd(TEMPDIR):
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001348 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001349 try:
1350 tar.add(".")
1351 finally:
1352 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001353
1354 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001355 try:
1356 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001357 if t.name != ".":
1358 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001359 finally:
1360 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001361
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001362 def test_open_nonwritable_fileobj(self):
1363 for exctype in OSError, EOFError, RuntimeError:
1364 class BadFile(io.BytesIO):
1365 first = True
1366 def write(self, data):
1367 if self.first:
1368 self.first = False
1369 raise exctype
1370
1371 f = BadFile()
1372 with self.assertRaises(exctype):
1373 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1374 format=tarfile.PAX_FORMAT,
1375 pax_headers={'non': 'empty'})
1376 self.assertFalse(f.closed)
1377
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001378class GzipWriteTest(GzipTest, WriteTest):
1379 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001380
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001381class Bz2WriteTest(Bz2Test, WriteTest):
1382 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001383
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001384class LzmaWriteTest(LzmaTest, WriteTest):
1385 pass
1386
1387
1388class StreamWriteTest(WriteTestBase, unittest.TestCase):
1389
1390 prefix = "w|"
1391 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001392
Guido van Rossumd8faa362007-04-27 19:54:29 +00001393 def test_stream_padding(self):
1394 # Test for bug #1543303.
1395 tar = tarfile.open(tmpname, self.mode)
1396 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001397 if self.decompressor:
1398 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001399 with open(tmpname, "rb") as fobj:
1400 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001401 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001402 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001403 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001404 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001405 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001406 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1407 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001408
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001409 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1410 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001411 def test_file_mode(self):
1412 # Test for issue #8464: Create files with correct
1413 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001414 if os.path.exists(tmpname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001415 support.unlink(tmpname)
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001416
1417 original_umask = os.umask(0o022)
1418 try:
1419 tar = tarfile.open(tmpname, self.mode)
1420 tar.close()
1421 mode = os.stat(tmpname).st_mode & 0o777
1422 self.assertEqual(mode, 0o644, "wrong file permissions")
1423 finally:
1424 os.umask(original_umask)
1425
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001426class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1427 pass
1428
1429class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1430 decompressor = bz2.BZ2Decompressor if bz2 else None
1431
1432class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1433 decompressor = lzma.LZMADecompressor if lzma else None
1434
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001435
Guido van Rossumd8faa362007-04-27 19:54:29 +00001436class GNUWriteTest(unittest.TestCase):
1437 # This testcase checks for correct creation of GNU Longname
1438 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001439
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001440 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001441 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001442 return blocks * 512
1443
1444 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001445 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001446 count = 512
1447
1448 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001449 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001450 count += 512
1451 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001452 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001453 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001454 count += 512
1455 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001456 return count
1457
1458 def _test(self, name, link=None):
1459 tarinfo = tarfile.TarInfo(name)
1460 if link:
1461 tarinfo.linkname = link
1462 tarinfo.type = tarfile.LNKTYPE
1463
Guido van Rossumd8faa362007-04-27 19:54:29 +00001464 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001465 try:
1466 tar.format = tarfile.GNU_FORMAT
1467 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001468
Antoine Pitrou95f55602010-09-23 18:36:46 +00001469 v1 = self._calc_size(name, link)
1470 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001471 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001472 finally:
1473 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001474
Guido van Rossumd8faa362007-04-27 19:54:29 +00001475 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001476 try:
1477 member = tar.next()
1478 self.assertIsNotNone(member,
1479 "unable to read longname member")
1480 self.assertEqual(tarinfo.name, member.name,
1481 "unable to read longname member")
1482 self.assertEqual(tarinfo.linkname, member.linkname,
1483 "unable to read longname member")
1484 finally:
1485 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001486
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001487 def test_longname_1023(self):
1488 self._test(("longnam/" * 127) + "longnam")
1489
1490 def test_longname_1024(self):
1491 self._test(("longnam/" * 127) + "longname")
1492
1493 def test_longname_1025(self):
1494 self._test(("longnam/" * 127) + "longname_")
1495
1496 def test_longlink_1023(self):
1497 self._test("name", ("longlnk/" * 127) + "longlnk")
1498
1499 def test_longlink_1024(self):
1500 self._test("name", ("longlnk/" * 127) + "longlink")
1501
1502 def test_longlink_1025(self):
1503 self._test("name", ("longlnk/" * 127) + "longlink_")
1504
1505 def test_longnamelink_1023(self):
1506 self._test(("longnam/" * 127) + "longnam",
1507 ("longlnk/" * 127) + "longlnk")
1508
1509 def test_longnamelink_1024(self):
1510 self._test(("longnam/" * 127) + "longname",
1511 ("longlnk/" * 127) + "longlink")
1512
1513 def test_longnamelink_1025(self):
1514 self._test(("longnam/" * 127) + "longname_",
1515 ("longlnk/" * 127) + "longlink_")
1516
Guido van Rossumd8faa362007-04-27 19:54:29 +00001517
Lars Gustäbel20703c62015-05-27 12:53:44 +02001518class CreateTest(WriteTestBase, unittest.TestCase):
Berker Peksag0fe63252015-02-13 21:02:12 +02001519
1520 prefix = "x:"
1521
1522 file_path = os.path.join(TEMPDIR, "spameggs42")
1523
1524 def setUp(self):
1525 support.unlink(tmpname)
1526
1527 @classmethod
1528 def setUpClass(cls):
1529 with open(cls.file_path, "wb") as fobj:
1530 fobj.write(b"aaa")
1531
1532 @classmethod
1533 def tearDownClass(cls):
1534 support.unlink(cls.file_path)
1535
1536 def test_create(self):
1537 with tarfile.open(tmpname, self.mode) as tobj:
1538 tobj.add(self.file_path)
1539
1540 with self.taropen(tmpname) as tobj:
1541 names = tobj.getnames()
1542 self.assertEqual(len(names), 1)
1543 self.assertIn('spameggs42', names[0])
1544
1545 def test_create_existing(self):
1546 with tarfile.open(tmpname, self.mode) as tobj:
1547 tobj.add(self.file_path)
1548
1549 with self.assertRaises(FileExistsError):
1550 tobj = tarfile.open(tmpname, self.mode)
1551
1552 with self.taropen(tmpname) as tobj:
1553 names = tobj.getnames()
1554 self.assertEqual(len(names), 1)
1555 self.assertIn('spameggs42', names[0])
1556
1557 def test_create_taropen(self):
1558 with self.taropen(tmpname, "x") as tobj:
1559 tobj.add(self.file_path)
1560
1561 with self.taropen(tmpname) as tobj:
1562 names = tobj.getnames()
1563 self.assertEqual(len(names), 1)
1564 self.assertIn('spameggs42', names[0])
1565
1566 def test_create_existing_taropen(self):
1567 with self.taropen(tmpname, "x") as tobj:
1568 tobj.add(self.file_path)
1569
1570 with self.assertRaises(FileExistsError):
1571 with self.taropen(tmpname, "x"):
1572 pass
1573
1574 with self.taropen(tmpname) as tobj:
1575 names = tobj.getnames()
1576 self.assertEqual(len(names), 1)
1577 self.assertIn("spameggs42", names[0])
1578
Serhiy Storchakac45cd162017-03-08 10:32:44 +02001579 def test_create_pathlike_name(self):
1580 with tarfile.open(pathlib.Path(tmpname), self.mode) as tobj:
1581 self.assertIsInstance(tobj.name, str)
1582 self.assertEqual(tobj.name, os.path.abspath(tmpname))
1583 tobj.add(pathlib.Path(self.file_path))
1584 names = tobj.getnames()
1585 self.assertEqual(len(names), 1)
1586 self.assertIn('spameggs42', names[0])
1587
1588 with self.taropen(tmpname) as tobj:
1589 names = tobj.getnames()
1590 self.assertEqual(len(names), 1)
1591 self.assertIn('spameggs42', names[0])
1592
1593 def test_create_taropen_pathlike_name(self):
1594 with self.taropen(pathlib.Path(tmpname), "x") as tobj:
1595 self.assertIsInstance(tobj.name, str)
1596 self.assertEqual(tobj.name, os.path.abspath(tmpname))
1597 tobj.add(pathlib.Path(self.file_path))
1598 names = tobj.getnames()
1599 self.assertEqual(len(names), 1)
1600 self.assertIn('spameggs42', names[0])
1601
1602 with self.taropen(tmpname) as tobj:
1603 names = tobj.getnames()
1604 self.assertEqual(len(names), 1)
1605 self.assertIn('spameggs42', names[0])
1606
Berker Peksag0fe63252015-02-13 21:02:12 +02001607
1608class GzipCreateTest(GzipTest, CreateTest):
1609 pass
1610
1611
1612class Bz2CreateTest(Bz2Test, CreateTest):
1613 pass
1614
1615
1616class LzmaCreateTest(LzmaTest, CreateTest):
1617 pass
1618
1619
1620class CreateWithXModeTest(CreateTest):
1621
1622 prefix = "x"
1623
1624 test_create_taropen = None
1625 test_create_existing_taropen = None
1626
1627
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001628@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001629class HardlinkTest(unittest.TestCase):
1630 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001631
1632 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001633 self.foo = os.path.join(TEMPDIR, "foo")
1634 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001635
Antoine Pitrou95f55602010-09-23 18:36:46 +00001636 with open(self.foo, "wb") as fobj:
1637 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001638
xdegayed7d4fea2017-11-12 18:02:06 +01001639 try:
1640 os.link(self.foo, self.bar)
1641 except PermissionError as e:
1642 self.skipTest('os.link(): %s' % e)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001643
Guido van Rossumd8faa362007-04-27 19:54:29 +00001644 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001645 self.tar.add(self.foo)
1646
Guido van Rossumd8faa362007-04-27 19:54:29 +00001647 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001648 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001649 support.unlink(self.foo)
1650 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001651
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001652 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001653 # The same name will be added as a REGTYPE every
1654 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001655 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001656 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001657 "add file as regular failed")
1658
1659 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001660 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001661 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001662 "add file as hardlink failed")
1663
1664 def test_dereference_hardlink(self):
1665 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001666 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001667 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001668 "dereferencing hardlink failed")
1669
Neal Norwitza4f651a2004-07-20 22:07:44 +00001670
Guido van Rossumd8faa362007-04-27 19:54:29 +00001671class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001672
Guido van Rossumd8faa362007-04-27 19:54:29 +00001673 def _test(self, name, link=None):
1674 # See GNUWriteTest.
1675 tarinfo = tarfile.TarInfo(name)
1676 if link:
1677 tarinfo.linkname = link
1678 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001679
Guido van Rossumd8faa362007-04-27 19:54:29 +00001680 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001681 try:
1682 tar.addfile(tarinfo)
1683 finally:
1684 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001685
Guido van Rossumd8faa362007-04-27 19:54:29 +00001686 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001687 try:
1688 if link:
1689 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001690 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001691 else:
1692 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001693 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001694 finally:
1695 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001696
Guido van Rossume7ba4952007-06-06 23:52:48 +00001697 def test_pax_global_header(self):
1698 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001699 "foo": "bar",
1700 "uid": "0",
1701 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001702 "test": "\xe4\xf6\xfc",
1703 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001704
Benjamin Peterson886af962010-03-21 23:13:07 +00001705 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001706 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001707 try:
1708 tar.addfile(tarfile.TarInfo("test"))
1709 finally:
1710 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001711
1712 # Test if the global header was written correctly.
1713 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001714 try:
1715 self.assertEqual(tar.pax_headers, pax_headers)
1716 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1717 # Test if all the fields are strings.
1718 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001719 self.assertIsNot(type(key), bytes)
1720 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001721 if key in tarfile.PAX_NUMBER_FIELDS:
1722 try:
1723 tarfile.PAX_NUMBER_FIELDS[key](val)
1724 except (TypeError, ValueError):
1725 self.fail("unable to convert pax header field")
1726 finally:
1727 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001728
1729 def test_pax_extended_header(self):
1730 # The fields from the pax header have priority over the
1731 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001732 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001733
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001734 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1735 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001736 try:
1737 t = tarfile.TarInfo()
1738 t.name = "\xe4\xf6\xfc" # non-ASCII
1739 t.uid = 8**8 # too large
1740 t.pax_headers = pax_headers
1741 tar.addfile(t)
1742 finally:
1743 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001744
1745 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001746 try:
1747 t = tar.getmembers()[0]
1748 self.assertEqual(t.pax_headers, pax_headers)
1749 self.assertEqual(t.name, "foo")
1750 self.assertEqual(t.uid, 123)
1751 finally:
1752 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001753
1754
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001755class UnicodeTest:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001756
1757 def test_iso8859_1_filename(self):
1758 self._test_unicode_filename("iso8859-1")
1759
1760 def test_utf7_filename(self):
1761 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001762
1763 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001764 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001765
Guido van Rossumd8faa362007-04-27 19:54:29 +00001766 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001767 tar = tarfile.open(tmpname, "w", format=self.format,
1768 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001769 try:
1770 name = "\xe4\xf6\xfc"
1771 tar.addfile(tarfile.TarInfo(name))
1772 finally:
1773 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001774
1775 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001776 try:
1777 self.assertEqual(tar.getmembers()[0].name, name)
1778 finally:
1779 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001780
1781 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001782 tar = tarfile.open(tmpname, "w", format=self.format,
1783 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001784 try:
1785 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001786
Antoine Pitrou95f55602010-09-23 18:36:46 +00001787 tarinfo.name = "\xe4\xf6\xfc"
1788 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001789
Antoine Pitrou95f55602010-09-23 18:36:46 +00001790 tarinfo.name = "foo"
1791 tarinfo.uname = "\xe4\xf6\xfc"
1792 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1793 finally:
1794 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001795
1796 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001797 tar = tarfile.open(tarname, "r",
1798 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001799 try:
1800 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001801 self.assertIs(type(t.name), str)
1802 self.assertIs(type(t.linkname), str)
1803 self.assertIs(type(t.uname), str)
1804 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001805 finally:
1806 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001807
Guido van Rossume7ba4952007-06-06 23:52:48 +00001808 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001809 t = tarfile.TarInfo("foo")
1810 t.uname = "\xe4\xf6\xfc"
1811 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001812
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001813 tar = tarfile.open(tmpname, mode="w", format=self.format,
1814 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001815 try:
1816 tar.addfile(t)
1817 finally:
1818 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001819
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001820 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001821 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001822 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001823 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1824 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1825
1826 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001827 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001828 tar = tarfile.open(tmpname, encoding="ascii")
1829 t = tar.getmember("foo")
1830 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1831 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1832 finally:
1833 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001834
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001835
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001836class UstarUnicodeTest(UnicodeTest, unittest.TestCase):
1837
1838 format = tarfile.USTAR_FORMAT
1839
1840 # Test whether the utf-8 encoded version of a filename exceeds the 100
1841 # bytes name field limit (every occurrence of '\xff' will be expanded to 2
1842 # bytes).
1843 def test_unicode_name1(self):
1844 self._test_ustar_name("0123456789" * 10)
1845 self._test_ustar_name("0123456789" * 10 + "0", ValueError)
1846 self._test_ustar_name("0123456789" * 9 + "01234567\xff")
1847 self._test_ustar_name("0123456789" * 9 + "012345678\xff", ValueError)
1848
1849 def test_unicode_name2(self):
1850 self._test_ustar_name("0123456789" * 9 + "012345\xff\xff")
1851 self._test_ustar_name("0123456789" * 9 + "0123456\xff\xff", ValueError)
1852
1853 # Test whether the utf-8 encoded version of a filename exceeds the 155
1854 # bytes prefix + '/' + 100 bytes name limit.
1855 def test_unicode_longname1(self):
1856 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 10)
1857 self._test_ustar_name("0123456789" * 15 + "0123/4" + "0123456789" * 10, ValueError)
1858 self._test_ustar_name("0123456789" * 15 + "012\xff/" + "0123456789" * 10)
1859 self._test_ustar_name("0123456789" * 15 + "0123\xff/" + "0123456789" * 10, ValueError)
1860
1861 def test_unicode_longname2(self):
1862 self._test_ustar_name("0123456789" * 15 + "01\xff/2" + "0123456789" * 10, ValueError)
1863 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/" + "0123456789" * 10, ValueError)
1864
1865 def test_unicode_longname3(self):
1866 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/2" + "0123456789" * 10, ValueError)
1867 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "01234567\xff")
1868 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345678\xff", ValueError)
1869
1870 def test_unicode_longname4(self):
1871 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345\xff\xff")
1872 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "0123456\xff\xff", ValueError)
1873
1874 def _test_ustar_name(self, name, exc=None):
1875 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1876 t = tarfile.TarInfo(name)
1877 if exc is None:
1878 tar.addfile(t)
1879 else:
1880 self.assertRaises(exc, tar.addfile, t)
1881
1882 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001883 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001884 for t in tar:
1885 self.assertEqual(name, t.name)
1886 break
1887
1888 # Test the same as above for the 100 bytes link field.
1889 def test_unicode_link1(self):
1890 self._test_ustar_link("0123456789" * 10)
1891 self._test_ustar_link("0123456789" * 10 + "0", ValueError)
1892 self._test_ustar_link("0123456789" * 9 + "01234567\xff")
1893 self._test_ustar_link("0123456789" * 9 + "012345678\xff", ValueError)
1894
1895 def test_unicode_link2(self):
1896 self._test_ustar_link("0123456789" * 9 + "012345\xff\xff")
1897 self._test_ustar_link("0123456789" * 9 + "0123456\xff\xff", ValueError)
1898
1899 def _test_ustar_link(self, name, exc=None):
1900 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1901 t = tarfile.TarInfo("foo")
1902 t.linkname = name
1903 if exc is None:
1904 tar.addfile(t)
1905 else:
1906 self.assertRaises(exc, tar.addfile, t)
1907
1908 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001909 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001910 for t in tar:
1911 self.assertEqual(name, t.linkname)
1912 break
1913
1914
1915class GNUUnicodeTest(UnicodeTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001916
Guido van Rossume7ba4952007-06-06 23:52:48 +00001917 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001918
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001919 def test_bad_pax_header(self):
1920 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1921 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001922 for encoding, name in (
1923 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001924 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001925 with tarfile.open(tarname, encoding=encoding,
1926 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001927 try:
1928 t = tar.getmember(name)
1929 except KeyError:
1930 self.fail("unable to read bad GNU tar pax header")
1931
Guido van Rossumd8faa362007-04-27 19:54:29 +00001932
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001933class PAXUnicodeTest(UnicodeTest, unittest.TestCase):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001934
1935 format = tarfile.PAX_FORMAT
1936
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001937 # PAX_FORMAT ignores encoding in write mode.
1938 test_unicode_filename_error = None
1939
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001940 def test_binary_header(self):
1941 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001942 for encoding, name in (
1943 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001944 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001945 with tarfile.open(tarname, encoding=encoding,
1946 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001947 try:
1948 t = tar.getmember(name)
1949 except KeyError:
1950 self.fail("unable to read POSIX.1-2008 binary header")
1951
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001952
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001953class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001954 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001955
Guido van Rossumd8faa362007-04-27 19:54:29 +00001956 def setUp(self):
1957 self.tarname = tmpname
1958 if os.path.exists(self.tarname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001959 support.unlink(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001960
Guido van Rossumd8faa362007-04-27 19:54:29 +00001961 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001962 with tarfile.open(tarname, encoding="iso8859-1") as src:
1963 t = src.getmember("ustar/regtype")
1964 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001965 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001966 with tarfile.open(self.tarname, mode) as tar:
1967 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001968
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001969 def test_append_compressed(self):
1970 self._create_testtar("w:" + self.suffix)
1971 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1972
1973class AppendTest(AppendTestBase, unittest.TestCase):
1974 test_append_compressed = None
1975
1976 def _add_testfile(self, fileobj=None):
1977 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1978 tar.addfile(tarfile.TarInfo("bar"))
1979
Guido van Rossumd8faa362007-04-27 19:54:29 +00001980 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001981 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1982 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001983
1984 def test_non_existing(self):
1985 self._add_testfile()
1986 self._test()
1987
1988 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001989 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001990 self._add_testfile()
1991 self._test()
1992
1993 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001994 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001995 self._add_testfile(fobj)
1996 fobj.seek(0)
1997 self._test(fileobj=fobj)
1998
1999 def test_fileobj(self):
2000 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00002001 with open(self.tarname, "rb") as fobj:
2002 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00002003 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002004 self._add_testfile(fobj)
2005 fobj.seek(0)
2006 self._test(names=["foo", "bar"], fileobj=fobj)
2007
2008 def test_existing(self):
2009 self._create_testtar()
2010 self._add_testfile()
2011 self._test(names=["foo", "bar"])
2012
Lars Gustäbel9520a432009-11-22 18:48:49 +00002013 # Append mode is supposed to fail if the tarfile to append to
2014 # does not end with a zero block.
2015 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00002016 with open(self.tarname, "wb") as fobj:
2017 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002018 self.assertRaises(tarfile.ReadError, self._add_testfile)
2019
2020 def test_null(self):
2021 self._test_error(b"")
2022
2023 def test_incomplete(self):
2024 self._test_error(b"\0" * 13)
2025
2026 def test_premature_eof(self):
2027 data = tarfile.TarInfo("foo").tobuf()
2028 self._test_error(data)
2029
2030 def test_trailing_garbage(self):
2031 data = tarfile.TarInfo("foo").tobuf()
2032 self._test_error(data + b"\0" * 13)
2033
2034 def test_invalid(self):
2035 self._test_error(b"a" * 512)
2036
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002037class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
2038 pass
2039
2040class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
2041 pass
2042
2043class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
2044 pass
2045
Guido van Rossumd8faa362007-04-27 19:54:29 +00002046
2047class LimitsTest(unittest.TestCase):
2048
2049 def test_ustar_limits(self):
2050 # 100 char name
2051 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002052 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002053
2054 # 101 char name that cannot be stored
2055 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002056 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002057
2058 # 256 char name with a slash at pos 156
2059 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002060 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002061
2062 # 256 char name that cannot be stored
2063 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002064 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002065
2066 # 512 char name
2067 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002068 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002069
2070 # 512 char linkname
2071 tarinfo = tarfile.TarInfo("longlink")
2072 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002073 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002074
2075 # uid > 8 digits
2076 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002077 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002078 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002079
2080 def test_gnu_limits(self):
2081 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002082 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002083
2084 tarinfo = tarfile.TarInfo("longlink")
2085 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002086 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002087
2088 # uid >= 256 ** 7
2089 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002090 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002091 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002092
2093 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002094 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002095 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002096
2097 tarinfo = tarfile.TarInfo("longlink")
2098 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002099 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002100
2101 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002102 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002103 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002104
2105
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002106class MiscTest(unittest.TestCase):
2107
2108 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002109 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
2110 b"foo\0\0\0\0\0")
2111 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
2112 b"foo")
2113 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
2114 "foo")
2115 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
2116 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002117
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002118 def test_read_number_fields(self):
2119 # Issue 13158: Test if GNU tar specific base-256 number fields
2120 # are decoded correctly.
2121 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
2122 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002123 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
2124 0o10000000)
2125 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
2126 0xffffffff)
2127 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
2128 -1)
2129 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
2130 -100)
2131 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
2132 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002133
Lars Gustäbelb7a688b2015-07-02 19:38:38 +02002134 # Issue 24514: Test if empty number fields are converted to zero.
2135 self.assertEqual(tarfile.nti(b"\0"), 0)
2136 self.assertEqual(tarfile.nti(b" \0"), 0)
2137
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002138 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002139 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002140 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002141 self.assertEqual(tarfile.itn(0o10000000),
2142 b"\x80\x00\x00\x00\x00\x20\x00\x00")
2143 self.assertEqual(tarfile.itn(0xffffffff),
2144 b"\x80\x00\x00\x00\xff\xff\xff\xff")
2145 self.assertEqual(tarfile.itn(-1),
2146 b"\xff\xff\xff\xff\xff\xff\xff\xff")
2147 self.assertEqual(tarfile.itn(-100),
2148 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
2149 self.assertEqual(tarfile.itn(-0x100000000000000),
2150 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002151
Joffrey F72d9b2b2018-02-26 16:02:21 -08002152 # Issue 32713: Test if itn() supports float values outside the
2153 # non-GNU format range
2154 self.assertEqual(tarfile.itn(-100.0, format=tarfile.GNU_FORMAT),
2155 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
2156 self.assertEqual(tarfile.itn(8 ** 12 + 0.0, format=tarfile.GNU_FORMAT),
2157 b"\x80\x00\x00\x10\x00\x00\x00\x00")
2158 self.assertEqual(tarfile.nti(tarfile.itn(-0.1, format=tarfile.GNU_FORMAT)), 0)
2159
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002160 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002161 with self.assertRaises(ValueError):
2162 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
2163 with self.assertRaises(ValueError):
2164 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
2165 with self.assertRaises(ValueError):
2166 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
2167 with self.assertRaises(ValueError):
2168 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002169
Martin Panter104dcda2016-01-16 06:59:13 +00002170 def test__all__(self):
Martin Panter5318d102016-01-16 11:01:14 +00002171 blacklist = {'version', 'grp', 'pwd', 'symlink_exception',
Martin Panter104dcda2016-01-16 06:59:13 +00002172 'NUL', 'BLOCKSIZE', 'RECORDSIZE', 'GNU_MAGIC',
2173 'POSIX_MAGIC', 'LENGTH_NAME', 'LENGTH_LINK',
2174 'LENGTH_PREFIX', 'REGTYPE', 'AREGTYPE', 'LNKTYPE',
2175 'SYMTYPE', 'CHRTYPE', 'BLKTYPE', 'DIRTYPE', 'FIFOTYPE',
2176 'CONTTYPE', 'GNUTYPE_LONGNAME', 'GNUTYPE_LONGLINK',
2177 'GNUTYPE_SPARSE', 'XHDTYPE', 'XGLTYPE', 'SOLARIS_XHDTYPE',
2178 'SUPPORTED_TYPES', 'REGULAR_TYPES', 'GNU_TYPES',
2179 'PAX_FIELDS', 'PAX_NAME_FIELDS', 'PAX_NUMBER_FIELDS',
2180 'stn', 'nts', 'nti', 'itn', 'calc_chksums', 'copyfileobj',
2181 'filemode',
2182 'EmptyHeaderError', 'TruncatedHeaderError',
2183 'EOFHeaderError', 'InvalidHeaderError',
Serhiy Storchaka2c1d3e32016-01-16 11:05:11 +02002184 'SubsequentHeaderError', 'ExFileObject',
Martin Panter104dcda2016-01-16 06:59:13 +00002185 'main'}
2186 support.check__all__(self, tarfile, blacklist=blacklist)
2187
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002188
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002189class CommandLineTest(unittest.TestCase):
2190
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002191 def tarfilecmd(self, *args, **kwargs):
2192 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
2193 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01002194 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002195
2196 def tarfilecmd_failure(self, *args):
2197 return script_helper.assert_python_failure('-m', 'tarfile', *args)
2198
2199 def make_simple_tarfile(self, tar_name):
2200 files = [support.findfile('tokenize_tests.txt'),
2201 support.findfile('tokenize_tests-no-coding-cookie-'
2202 'and-utf8-bom-sig-only.txt')]
2203 self.addCleanup(support.unlink, tar_name)
2204 with tarfile.open(tar_name, 'w') as tf:
2205 for tardata in files:
2206 tf.add(tardata, arcname=os.path.basename(tardata))
2207
Serhiy Storchaka150cd192017-04-07 18:56:12 +03002208 def test_bad_use(self):
2209 rc, out, err = self.tarfilecmd_failure()
2210 self.assertEqual(out, b'')
2211 self.assertIn(b'usage', err.lower())
2212 self.assertIn(b'error', err.lower())
2213 self.assertIn(b'required', err.lower())
2214 rc, out, err = self.tarfilecmd_failure('-l', '')
2215 self.assertEqual(out, b'')
2216 self.assertNotEqual(err.strip(), b'')
2217
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002218 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002219 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002220 for opt in '-t', '--test':
2221 out = self.tarfilecmd(opt, tar_name)
2222 self.assertEqual(out, b'')
2223
2224 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002225 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002226 for opt in '-v', '--verbose':
2227 out = self.tarfilecmd(opt, '-t', tar_name)
2228 self.assertIn(b'is a tar archive.\n', out)
2229
2230 def test_test_command_invalid_file(self):
2231 zipname = support.findfile('zipdir.zip')
2232 rc, out, err = self.tarfilecmd_failure('-t', zipname)
2233 self.assertIn(b' is not a tar archive.', err)
2234 self.assertEqual(out, b'')
2235 self.assertEqual(rc, 1)
2236
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002237 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002238 with self.subTest(tar_name=tar_name):
2239 with open(tar_name, 'rb') as f:
2240 data = f.read()
2241 try:
2242 with open(tmpname, 'wb') as f:
2243 f.write(data[:511])
2244 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
2245 self.assertEqual(out, b'')
2246 self.assertEqual(rc, 1)
2247 finally:
2248 support.unlink(tmpname)
2249
2250 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002251 for tar_name in testtarnames:
2252 with support.captured_stdout() as t:
2253 with tarfile.open(tar_name, 'r') as tf:
2254 tf.list(verbose=False)
2255 expected = t.getvalue().encode('ascii', 'backslashreplace')
2256 for opt in '-l', '--list':
2257 out = self.tarfilecmd(opt, tar_name,
2258 PYTHONIOENCODING='ascii')
2259 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002260
2261 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002262 for tar_name in testtarnames:
2263 with support.captured_stdout() as t:
2264 with tarfile.open(tar_name, 'r') as tf:
2265 tf.list(verbose=True)
2266 expected = t.getvalue().encode('ascii', 'backslashreplace')
2267 for opt in '-v', '--verbose':
2268 out = self.tarfilecmd(opt, '-l', tar_name,
2269 PYTHONIOENCODING='ascii')
2270 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002271
2272 def test_list_command_invalid_file(self):
2273 zipname = support.findfile('zipdir.zip')
2274 rc, out, err = self.tarfilecmd_failure('-l', zipname)
2275 self.assertIn(b' is not a tar archive.', err)
2276 self.assertEqual(out, b'')
2277 self.assertEqual(rc, 1)
2278
2279 def test_create_command(self):
2280 files = [support.findfile('tokenize_tests.txt'),
2281 support.findfile('tokenize_tests-no-coding-cookie-'
2282 'and-utf8-bom-sig-only.txt')]
2283 for opt in '-c', '--create':
2284 try:
2285 out = self.tarfilecmd(opt, tmpname, *files)
2286 self.assertEqual(out, b'')
2287 with tarfile.open(tmpname) as tar:
2288 tar.getmembers()
2289 finally:
2290 support.unlink(tmpname)
2291
2292 def test_create_command_verbose(self):
2293 files = [support.findfile('tokenize_tests.txt'),
2294 support.findfile('tokenize_tests-no-coding-cookie-'
2295 'and-utf8-bom-sig-only.txt')]
2296 for opt in '-v', '--verbose':
2297 try:
2298 out = self.tarfilecmd(opt, '-c', tmpname, *files)
2299 self.assertIn(b' file created.', out)
2300 with tarfile.open(tmpname) as tar:
2301 tar.getmembers()
2302 finally:
2303 support.unlink(tmpname)
2304
2305 def test_create_command_dotless_filename(self):
2306 files = [support.findfile('tokenize_tests.txt')]
2307 try:
2308 out = self.tarfilecmd('-c', dotlessname, *files)
2309 self.assertEqual(out, b'')
2310 with tarfile.open(dotlessname) as tar:
2311 tar.getmembers()
2312 finally:
2313 support.unlink(dotlessname)
2314
2315 def test_create_command_dot_started_filename(self):
2316 tar_name = os.path.join(TEMPDIR, ".testtar")
2317 files = [support.findfile('tokenize_tests.txt')]
2318 try:
2319 out = self.tarfilecmd('-c', tar_name, *files)
2320 self.assertEqual(out, b'')
2321 with tarfile.open(tar_name) as tar:
2322 tar.getmembers()
2323 finally:
2324 support.unlink(tar_name)
2325
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002326 def test_create_command_compressed(self):
2327 files = [support.findfile('tokenize_tests.txt'),
2328 support.findfile('tokenize_tests-no-coding-cookie-'
2329 'and-utf8-bom-sig-only.txt')]
2330 for filetype in (GzipTest, Bz2Test, LzmaTest):
2331 if not filetype.open:
2332 continue
2333 try:
2334 tar_name = tmpname + '.' + filetype.suffix
2335 out = self.tarfilecmd('-c', tar_name, *files)
2336 with filetype.taropen(tar_name) as tar:
2337 tar.getmembers()
2338 finally:
2339 support.unlink(tar_name)
2340
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002341 def test_extract_command(self):
2342 self.make_simple_tarfile(tmpname)
2343 for opt in '-e', '--extract':
2344 try:
2345 with support.temp_cwd(tarextdir):
2346 out = self.tarfilecmd(opt, tmpname)
2347 self.assertEqual(out, b'')
2348 finally:
2349 support.rmtree(tarextdir)
2350
2351 def test_extract_command_verbose(self):
2352 self.make_simple_tarfile(tmpname)
2353 for opt in '-v', '--verbose':
2354 try:
2355 with support.temp_cwd(tarextdir):
2356 out = self.tarfilecmd(opt, '-e', tmpname)
2357 self.assertIn(b' file is extracted.', out)
2358 finally:
2359 support.rmtree(tarextdir)
2360
2361 def test_extract_command_different_directory(self):
2362 self.make_simple_tarfile(tmpname)
2363 try:
2364 with support.temp_cwd(tarextdir):
2365 out = self.tarfilecmd('-e', tmpname, 'spamdir')
2366 self.assertEqual(out, b'')
2367 finally:
2368 support.rmtree(tarextdir)
2369
2370 def test_extract_command_invalid_file(self):
2371 zipname = support.findfile('zipdir.zip')
2372 with support.temp_cwd(tarextdir):
2373 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2374 self.assertIn(b' is not a tar archive.', err)
2375 self.assertEqual(out, b'')
2376 self.assertEqual(rc, 1)
2377
2378
Lars Gustäbel01385812010-03-03 12:08:54 +00002379class ContextManagerTest(unittest.TestCase):
2380
2381 def test_basic(self):
2382 with tarfile.open(tarname) as tar:
2383 self.assertFalse(tar.closed, "closed inside runtime context")
2384 self.assertTrue(tar.closed, "context manager failed")
2385
2386 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002387 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002388 # if the TarFile object is already closed.
2389 tar = tarfile.open(tarname)
2390 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002391 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002392 with tar:
2393 pass
2394
2395 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002396 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002397 with self.assertRaises(Exception) as exc:
2398 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002399 raise OSError
2400 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002401 "wrong exception raised in context manager")
2402 self.assertTrue(tar.closed, "context manager failed")
2403
2404 def test_no_eof(self):
2405 # __exit__() must not write end-of-archive blocks if an
2406 # exception was raised.
2407 try:
2408 with tarfile.open(tmpname, "w") as tar:
2409 raise Exception
2410 except:
2411 pass
2412 self.assertEqual(os.path.getsize(tmpname), 0,
2413 "context manager wrote an end-of-archive block")
2414 self.assertTrue(tar.closed, "context manager failed")
2415
2416 def test_eof(self):
2417 # __exit__() must write end-of-archive blocks, i.e. call
2418 # TarFile.close() if there was no error.
2419 with tarfile.open(tmpname, "w"):
2420 pass
2421 self.assertNotEqual(os.path.getsize(tmpname), 0,
2422 "context manager wrote no end-of-archive block")
2423
2424 def test_fileobj(self):
2425 # Test that __exit__() did not close the external file
2426 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002427 with open(tmpname, "wb") as fobj:
2428 try:
2429 with tarfile.open(fileobj=fobj, mode="w") as tar:
2430 raise Exception
2431 except:
2432 pass
2433 self.assertFalse(fobj.closed, "external file object was closed")
2434 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002435
2436
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002437@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2438class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002439
2440 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002441 # symbolic or hard links tarfile tries to extract these types of members
2442 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002443 def _test_link_extraction(self, name):
2444 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002445 with open(os.path.join(TEMPDIR, name), "rb") as f:
2446 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002447 self.assertEqual(md5sum(data), md5_regtype)
2448
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002449 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002450 @unittest.skipIf(hasattr(os.path, "islink"),
2451 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002452 def test_hardlink_extraction1(self):
2453 self._test_link_extraction("ustar/lnktype")
2454
Brian Curtind40e6f72010-07-08 21:39:08 +00002455 @unittest.skipIf(hasattr(os.path, "islink"),
2456 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002457 def test_hardlink_extraction2(self):
2458 self._test_link_extraction("./ustar/linktest2/lnktype")
2459
Brian Curtin74e45612010-07-09 15:58:59 +00002460 @unittest.skipIf(hasattr(os, "symlink"),
2461 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002462 def test_symlink_extraction1(self):
2463 self._test_link_extraction("ustar/symtype")
2464
Brian Curtin74e45612010-07-09 15:58:59 +00002465 @unittest.skipIf(hasattr(os, "symlink"),
2466 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002467 def test_symlink_extraction2(self):
2468 self._test_link_extraction("./ustar/linktest2/symtype")
2469
2470
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002471class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002472 # Issue5068: The _BZ2Proxy.read() method loops forever
2473 # on an empty or partial bzipped file.
2474
2475 def _test_partial_input(self, mode):
2476 class MyBytesIO(io.BytesIO):
2477 hit_eof = False
2478 def read(self, n):
2479 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002480 raise AssertionError("infinite loop detected in "
2481 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002482 self.hit_eof = self.tell() == len(self.getvalue())
2483 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002484 def seek(self, *args):
2485 self.hit_eof = False
2486 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002487
2488 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2489 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002490 try:
2491 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2492 except tarfile.ReadError:
2493 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002494
2495 def test_partial_input(self):
2496 self._test_partial_input("r")
2497
2498 def test_partial_input_bz2(self):
2499 self._test_partial_input("r:bz2")
2500
2501
Eric V. Smith7a803892015-04-15 10:27:58 -04002502def root_is_uid_gid_0():
2503 try:
2504 import pwd, grp
2505 except ImportError:
2506 return False
2507 if pwd.getpwuid(0)[0] != 'root':
2508 return False
2509 if grp.getgrgid(0)[0] != 'root':
2510 return False
2511 return True
2512
2513
Zachary Waread3e27a2015-05-12 23:57:21 -05002514@unittest.skipUnless(hasattr(os, 'chown'), "missing os.chown")
2515@unittest.skipUnless(hasattr(os, 'geteuid'), "missing os.geteuid")
Eric V. Smith7a803892015-04-15 10:27:58 -04002516class NumericOwnerTest(unittest.TestCase):
2517 # mock the following:
2518 # os.chown: so we can test what's being called
2519 # os.chmod: so the modes are not actually changed. if they are, we can't
2520 # delete the files/directories
2521 # os.geteuid: so we can lie and say we're root (uid = 0)
2522
2523 @staticmethod
2524 def _make_test_archive(filename_1, dirname_1, filename_2):
2525 # the file contents to write
2526 fobj = io.BytesIO(b"content")
2527
2528 # create a tar file with a file, a directory, and a file within that
2529 # directory. Assign various .uid/.gid values to them
2530 items = [(filename_1, 99, 98, tarfile.REGTYPE, fobj),
2531 (dirname_1, 77, 76, tarfile.DIRTYPE, None),
2532 (filename_2, 88, 87, tarfile.REGTYPE, fobj),
2533 ]
2534 with tarfile.open(tmpname, 'w') as tarfl:
2535 for name, uid, gid, typ, contents in items:
2536 t = tarfile.TarInfo(name)
2537 t.uid = uid
2538 t.gid = gid
2539 t.uname = 'root'
2540 t.gname = 'root'
2541 t.type = typ
2542 tarfl.addfile(t, contents)
2543
2544 # return the full pathname to the tar file
2545 return tmpname
2546
2547 @staticmethod
2548 @contextmanager
2549 def _setup_test(mock_geteuid):
2550 mock_geteuid.return_value = 0 # lie and say we're root
2551 fname = 'numeric-owner-testfile'
2552 dirname = 'dir'
2553
2554 # the names we want stored in the tarfile
2555 filename_1 = fname
2556 dirname_1 = dirname
2557 filename_2 = os.path.join(dirname, fname)
2558
2559 # create the tarfile with the contents we're after
2560 tar_filename = NumericOwnerTest._make_test_archive(filename_1,
2561 dirname_1,
2562 filename_2)
2563
2564 # open the tarfile for reading. yield it and the names of the items
2565 # we stored into the file
2566 with tarfile.open(tar_filename) as tarfl:
2567 yield tarfl, filename_1, dirname_1, filename_2
2568
2569 @unittest.mock.patch('os.chown')
2570 @unittest.mock.patch('os.chmod')
2571 @unittest.mock.patch('os.geteuid')
2572 def test_extract_with_numeric_owner(self, mock_geteuid, mock_chmod,
2573 mock_chown):
2574 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _,
2575 filename_2):
2576 tarfl.extract(filename_1, TEMPDIR, numeric_owner=True)
2577 tarfl.extract(filename_2 , TEMPDIR, numeric_owner=True)
2578
2579 # convert to filesystem paths
2580 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2581 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2582
2583 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2584 unittest.mock.call(f_filename_2, 88, 87),
2585 ],
2586 any_order=True)
2587
2588 @unittest.mock.patch('os.chown')
2589 @unittest.mock.patch('os.chmod')
2590 @unittest.mock.patch('os.geteuid')
2591 def test_extractall_with_numeric_owner(self, mock_geteuid, mock_chmod,
2592 mock_chown):
2593 with self._setup_test(mock_geteuid) as (tarfl, filename_1, dirname_1,
2594 filename_2):
2595 tarfl.extractall(TEMPDIR, numeric_owner=True)
2596
2597 # convert to filesystem paths
2598 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2599 f_dirname_1 = os.path.join(TEMPDIR, dirname_1)
2600 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2601
2602 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2603 unittest.mock.call(f_dirname_1, 77, 76),
2604 unittest.mock.call(f_filename_2, 88, 87),
2605 ],
2606 any_order=True)
2607
2608 # this test requires that uid=0 and gid=0 really be named 'root'. that's
2609 # because the uname and gname in the test file are 'root', and extract()
2610 # will look them up using pwd and grp to find their uid and gid, which we
2611 # test here to be 0.
2612 @unittest.skipUnless(root_is_uid_gid_0(),
2613 'uid=0,gid=0 must be named "root"')
2614 @unittest.mock.patch('os.chown')
2615 @unittest.mock.patch('os.chmod')
2616 @unittest.mock.patch('os.geteuid')
2617 def test_extract_without_numeric_owner(self, mock_geteuid, mock_chmod,
2618 mock_chown):
2619 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2620 tarfl.extract(filename_1, TEMPDIR, numeric_owner=False)
2621
2622 # convert to filesystem paths
2623 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2624
2625 mock_chown.assert_called_with(f_filename_1, 0, 0)
2626
2627 @unittest.mock.patch('os.geteuid')
2628 def test_keyword_only(self, mock_geteuid):
2629 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2630 self.assertRaises(TypeError,
2631 tarfl.extract, filename_1, TEMPDIR, False, True)
2632
2633
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002634def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002635 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002636 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002637
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002638 global testtarnames
2639 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002640 with open(tarname, "rb") as fobj:
2641 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002642
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002643 # Create compressed tarfiles.
2644 for c in GzipTest, Bz2Test, LzmaTest:
2645 if c.open:
2646 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002647 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002648 with c.open(c.tarname, "wb") as tar:
2649 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002650
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002651def tearDownModule():
2652 if os.path.exists(TEMPDIR):
Tim Goldene0bd2c52014-05-06 13:24:26 +01002653 support.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002654
Neal Norwitz996acf12003-02-17 14:51:41 +00002655if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002656 unittest.main()