blob: 179cbc6dfffca757ed473d5fdeec03843ca4ec30 [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
Serhiy Storchakac45cd162017-03-08 10:32:44 +02001132 def test_gettarinfo_pathlike_name(self):
1133 with tarfile.open(tmpname, self.mode) as tar:
1134 path = pathlib.Path(TEMPDIR) / "file"
1135 with open(path, "wb") as fobj:
1136 fobj.write(b"aaa")
1137 tarinfo = tar.gettarinfo(path)
1138 tarinfo2 = tar.gettarinfo(os.fspath(path))
1139 self.assertIsInstance(tarinfo.name, str)
1140 self.assertEqual(tarinfo.name, tarinfo2.name)
1141 self.assertEqual(tarinfo.size, 3)
1142
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001143 @unittest.skipUnless(hasattr(os, "link"),
1144 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001145 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001146 link = os.path.join(TEMPDIR, "link")
1147 target = os.path.join(TEMPDIR, "link_target")
1148 with open(target, "wb") as fobj:
1149 fobj.write(b"aaa")
xdegayed7d4fea2017-11-12 18:02:06 +01001150 try:
1151 os.link(target, link)
1152 except PermissionError as e:
1153 self.skipTest('os.link(): %s' % e)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001154 try:
1155 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001156 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001157 # Record the link target in the inodes list.
1158 tar.gettarinfo(target)
1159 tarinfo = tar.gettarinfo(link)
1160 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001161 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001162 tar.close()
1163 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001164 support.unlink(target)
1165 support.unlink(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001166
Brian Curtin3b4499c2010-12-28 14:31:47 +00001167 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +00001168 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +00001169 path = os.path.join(TEMPDIR, "symlink")
1170 os.symlink("link_target", path)
1171 try:
1172 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001173 try:
1174 tarinfo = tar.gettarinfo(path)
1175 self.assertEqual(tarinfo.size, 0)
1176 finally:
1177 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +00001178 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001179 support.unlink(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001180
1181 def test_add_self(self):
1182 # Test for #1257255.
1183 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001184 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001185 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001186 self.assertEqual(tar.name, dstname,
1187 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001188 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001189 self.assertEqual(tar.getnames(), [],
1190 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001191
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001192 with support.change_cwd(TEMPDIR):
1193 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001194 self.assertEqual(tar.getnames(), [],
1195 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001196 finally:
1197 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001198
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001199 def test_filter(self):
1200 tempdir = os.path.join(TEMPDIR, "filter")
1201 os.mkdir(tempdir)
1202 try:
1203 for name in ("foo", "bar", "baz"):
1204 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001205 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001206
1207 def filter(tarinfo):
1208 if os.path.basename(tarinfo.name) == "bar":
1209 return
1210 tarinfo.uid = 123
1211 tarinfo.uname = "foo"
1212 return tarinfo
1213
1214 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001215 try:
1216 tar.add(tempdir, arcname="empty_dir", filter=filter)
1217 finally:
1218 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001219
Raymond Hettingera63a3122011-01-26 20:34:14 +00001220 # Verify that filter is a keyword-only argument
1221 with self.assertRaises(TypeError):
1222 tar.add(tempdir, "empty_dir", True, None, filter)
1223
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001224 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001225 try:
1226 for tarinfo in tar:
1227 self.assertEqual(tarinfo.uid, 123)
1228 self.assertEqual(tarinfo.uname, "foo")
1229 self.assertEqual(len(tar.getmembers()), 3)
1230 finally:
1231 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001232 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001233 support.rmtree(tempdir)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001234
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001235 # Guarantee that stored pathnames are not modified. Don't
1236 # remove ./ or ../ or double slashes. Still make absolute
1237 # pathnames relative.
1238 # For details see bug #6054.
1239 def _test_pathname(self, path, cmp_path=None, dir=False):
1240 # Create a tarfile with an empty member named path
1241 # and compare the stored name with the original.
1242 foo = os.path.join(TEMPDIR, "foo")
1243 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001244 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001245 else:
1246 os.mkdir(foo)
1247
1248 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001249 try:
1250 tar.add(foo, arcname=path)
1251 finally:
1252 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001253
1254 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001255 try:
1256 t = tar.next()
1257 finally:
1258 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001259
1260 if not dir:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001261 support.unlink(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001262 else:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001263 support.rmdir(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001264
1265 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1266
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001267
1268 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001269 def test_extractall_symlinks(self):
1270 # Test if extractall works properly when tarfile contains symlinks
1271 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1272 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1273 os.mkdir(tempdir)
1274 try:
1275 source_file = os.path.join(tempdir,'source')
1276 target_file = os.path.join(tempdir,'symlink')
1277 with open(source_file,'w') as f:
1278 f.write('something\n')
1279 os.symlink(source_file, target_file)
1280 tar = tarfile.open(temparchive,'w')
1281 tar.add(source_file)
1282 tar.add(target_file)
1283 tar.close()
1284 # Let's extract it to the location which contains the symlink
1285 tar = tarfile.open(temparchive,'r')
1286 # this should not raise OSError: [Errno 17] File exists
1287 try:
1288 tar.extractall(path=tempdir)
1289 except OSError:
1290 self.fail("extractall failed with symlinked files")
1291 finally:
1292 tar.close()
1293 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001294 support.unlink(temparchive)
1295 support.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001296
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001297 def test_pathnames(self):
1298 self._test_pathname("foo")
1299 self._test_pathname(os.path.join("foo", ".", "bar"))
1300 self._test_pathname(os.path.join("foo", "..", "bar"))
1301 self._test_pathname(os.path.join(".", "foo"))
1302 self._test_pathname(os.path.join(".", "foo", "."))
1303 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1304 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1305 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1306 self._test_pathname(os.path.join("..", "foo"))
1307 self._test_pathname(os.path.join("..", "foo", ".."))
1308 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1309 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1310
1311 self._test_pathname("foo" + os.sep + os.sep + "bar")
1312 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1313
1314 def test_abs_pathnames(self):
1315 if sys.platform == "win32":
1316 self._test_pathname("C:\\foo", "foo")
1317 else:
1318 self._test_pathname("/foo", "foo")
1319 self._test_pathname("///foo", "foo")
1320
1321 def test_cwd(self):
1322 # Test adding the current working directory.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001323 with support.change_cwd(TEMPDIR):
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001324 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001325 try:
1326 tar.add(".")
1327 finally:
1328 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001329
1330 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001331 try:
1332 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001333 if t.name != ".":
1334 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001335 finally:
1336 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001337
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001338 def test_open_nonwritable_fileobj(self):
1339 for exctype in OSError, EOFError, RuntimeError:
1340 class BadFile(io.BytesIO):
1341 first = True
1342 def write(self, data):
1343 if self.first:
1344 self.first = False
1345 raise exctype
1346
1347 f = BadFile()
1348 with self.assertRaises(exctype):
1349 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1350 format=tarfile.PAX_FORMAT,
1351 pax_headers={'non': 'empty'})
1352 self.assertFalse(f.closed)
1353
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001354class GzipWriteTest(GzipTest, WriteTest):
1355 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001356
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001357class Bz2WriteTest(Bz2Test, WriteTest):
1358 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001359
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001360class LzmaWriteTest(LzmaTest, WriteTest):
1361 pass
1362
1363
1364class StreamWriteTest(WriteTestBase, unittest.TestCase):
1365
1366 prefix = "w|"
1367 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001368
Guido van Rossumd8faa362007-04-27 19:54:29 +00001369 def test_stream_padding(self):
1370 # Test for bug #1543303.
1371 tar = tarfile.open(tmpname, self.mode)
1372 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001373 if self.decompressor:
1374 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001375 with open(tmpname, "rb") as fobj:
1376 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001377 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001378 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001379 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001380 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001381 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001382 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1383 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001384
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001385 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1386 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001387 def test_file_mode(self):
1388 # Test for issue #8464: Create files with correct
1389 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001390 if os.path.exists(tmpname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001391 support.unlink(tmpname)
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001392
1393 original_umask = os.umask(0o022)
1394 try:
1395 tar = tarfile.open(tmpname, self.mode)
1396 tar.close()
1397 mode = os.stat(tmpname).st_mode & 0o777
1398 self.assertEqual(mode, 0o644, "wrong file permissions")
1399 finally:
1400 os.umask(original_umask)
1401
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001402class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1403 pass
1404
1405class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1406 decompressor = bz2.BZ2Decompressor if bz2 else None
1407
1408class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1409 decompressor = lzma.LZMADecompressor if lzma else None
1410
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001411
Guido van Rossumd8faa362007-04-27 19:54:29 +00001412class GNUWriteTest(unittest.TestCase):
1413 # This testcase checks for correct creation of GNU Longname
1414 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001415
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001416 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001417 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001418 return blocks * 512
1419
1420 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001421 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001422 count = 512
1423
1424 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001425 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001426 count += 512
1427 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001428 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001429 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001430 count += 512
1431 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001432 return count
1433
1434 def _test(self, name, link=None):
1435 tarinfo = tarfile.TarInfo(name)
1436 if link:
1437 tarinfo.linkname = link
1438 tarinfo.type = tarfile.LNKTYPE
1439
Guido van Rossumd8faa362007-04-27 19:54:29 +00001440 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001441 try:
1442 tar.format = tarfile.GNU_FORMAT
1443 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001444
Antoine Pitrou95f55602010-09-23 18:36:46 +00001445 v1 = self._calc_size(name, link)
1446 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001447 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001448 finally:
1449 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001450
Guido van Rossumd8faa362007-04-27 19:54:29 +00001451 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001452 try:
1453 member = tar.next()
1454 self.assertIsNotNone(member,
1455 "unable to read longname member")
1456 self.assertEqual(tarinfo.name, member.name,
1457 "unable to read longname member")
1458 self.assertEqual(tarinfo.linkname, member.linkname,
1459 "unable to read longname member")
1460 finally:
1461 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001462
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001463 def test_longname_1023(self):
1464 self._test(("longnam/" * 127) + "longnam")
1465
1466 def test_longname_1024(self):
1467 self._test(("longnam/" * 127) + "longname")
1468
1469 def test_longname_1025(self):
1470 self._test(("longnam/" * 127) + "longname_")
1471
1472 def test_longlink_1023(self):
1473 self._test("name", ("longlnk/" * 127) + "longlnk")
1474
1475 def test_longlink_1024(self):
1476 self._test("name", ("longlnk/" * 127) + "longlink")
1477
1478 def test_longlink_1025(self):
1479 self._test("name", ("longlnk/" * 127) + "longlink_")
1480
1481 def test_longnamelink_1023(self):
1482 self._test(("longnam/" * 127) + "longnam",
1483 ("longlnk/" * 127) + "longlnk")
1484
1485 def test_longnamelink_1024(self):
1486 self._test(("longnam/" * 127) + "longname",
1487 ("longlnk/" * 127) + "longlink")
1488
1489 def test_longnamelink_1025(self):
1490 self._test(("longnam/" * 127) + "longname_",
1491 ("longlnk/" * 127) + "longlink_")
1492
Guido van Rossumd8faa362007-04-27 19:54:29 +00001493
Lars Gustäbel20703c62015-05-27 12:53:44 +02001494class CreateTest(WriteTestBase, unittest.TestCase):
Berker Peksag0fe63252015-02-13 21:02:12 +02001495
1496 prefix = "x:"
1497
1498 file_path = os.path.join(TEMPDIR, "spameggs42")
1499
1500 def setUp(self):
1501 support.unlink(tmpname)
1502
1503 @classmethod
1504 def setUpClass(cls):
1505 with open(cls.file_path, "wb") as fobj:
1506 fobj.write(b"aaa")
1507
1508 @classmethod
1509 def tearDownClass(cls):
1510 support.unlink(cls.file_path)
1511
1512 def test_create(self):
1513 with tarfile.open(tmpname, self.mode) as tobj:
1514 tobj.add(self.file_path)
1515
1516 with self.taropen(tmpname) as tobj:
1517 names = tobj.getnames()
1518 self.assertEqual(len(names), 1)
1519 self.assertIn('spameggs42', names[0])
1520
1521 def test_create_existing(self):
1522 with tarfile.open(tmpname, self.mode) as tobj:
1523 tobj.add(self.file_path)
1524
1525 with self.assertRaises(FileExistsError):
1526 tobj = tarfile.open(tmpname, self.mode)
1527
1528 with self.taropen(tmpname) as tobj:
1529 names = tobj.getnames()
1530 self.assertEqual(len(names), 1)
1531 self.assertIn('spameggs42', names[0])
1532
1533 def test_create_taropen(self):
1534 with self.taropen(tmpname, "x") as tobj:
1535 tobj.add(self.file_path)
1536
1537 with self.taropen(tmpname) as tobj:
1538 names = tobj.getnames()
1539 self.assertEqual(len(names), 1)
1540 self.assertIn('spameggs42', names[0])
1541
1542 def test_create_existing_taropen(self):
1543 with self.taropen(tmpname, "x") as tobj:
1544 tobj.add(self.file_path)
1545
1546 with self.assertRaises(FileExistsError):
1547 with self.taropen(tmpname, "x"):
1548 pass
1549
1550 with self.taropen(tmpname) as tobj:
1551 names = tobj.getnames()
1552 self.assertEqual(len(names), 1)
1553 self.assertIn("spameggs42", names[0])
1554
Serhiy Storchakac45cd162017-03-08 10:32:44 +02001555 def test_create_pathlike_name(self):
1556 with tarfile.open(pathlib.Path(tmpname), self.mode) as tobj:
1557 self.assertIsInstance(tobj.name, str)
1558 self.assertEqual(tobj.name, os.path.abspath(tmpname))
1559 tobj.add(pathlib.Path(self.file_path))
1560 names = tobj.getnames()
1561 self.assertEqual(len(names), 1)
1562 self.assertIn('spameggs42', names[0])
1563
1564 with self.taropen(tmpname) as tobj:
1565 names = tobj.getnames()
1566 self.assertEqual(len(names), 1)
1567 self.assertIn('spameggs42', names[0])
1568
1569 def test_create_taropen_pathlike_name(self):
1570 with self.taropen(pathlib.Path(tmpname), "x") as tobj:
1571 self.assertIsInstance(tobj.name, str)
1572 self.assertEqual(tobj.name, os.path.abspath(tmpname))
1573 tobj.add(pathlib.Path(self.file_path))
1574 names = tobj.getnames()
1575 self.assertEqual(len(names), 1)
1576 self.assertIn('spameggs42', names[0])
1577
1578 with self.taropen(tmpname) as tobj:
1579 names = tobj.getnames()
1580 self.assertEqual(len(names), 1)
1581 self.assertIn('spameggs42', names[0])
1582
Berker Peksag0fe63252015-02-13 21:02:12 +02001583
1584class GzipCreateTest(GzipTest, CreateTest):
1585 pass
1586
1587
1588class Bz2CreateTest(Bz2Test, CreateTest):
1589 pass
1590
1591
1592class LzmaCreateTest(LzmaTest, CreateTest):
1593 pass
1594
1595
1596class CreateWithXModeTest(CreateTest):
1597
1598 prefix = "x"
1599
1600 test_create_taropen = None
1601 test_create_existing_taropen = None
1602
1603
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001604@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001605class HardlinkTest(unittest.TestCase):
1606 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001607
1608 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001609 self.foo = os.path.join(TEMPDIR, "foo")
1610 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001611
Antoine Pitrou95f55602010-09-23 18:36:46 +00001612 with open(self.foo, "wb") as fobj:
1613 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001614
xdegayed7d4fea2017-11-12 18:02:06 +01001615 try:
1616 os.link(self.foo, self.bar)
1617 except PermissionError as e:
1618 self.skipTest('os.link(): %s' % e)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001619
Guido van Rossumd8faa362007-04-27 19:54:29 +00001620 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001621 self.tar.add(self.foo)
1622
Guido van Rossumd8faa362007-04-27 19:54:29 +00001623 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001624 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001625 support.unlink(self.foo)
1626 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001627
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001628 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001629 # The same name will be added as a REGTYPE every
1630 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001631 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001632 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001633 "add file as regular failed")
1634
1635 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001636 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001637 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001638 "add file as hardlink failed")
1639
1640 def test_dereference_hardlink(self):
1641 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001642 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001643 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001644 "dereferencing hardlink failed")
1645
Neal Norwitza4f651a2004-07-20 22:07:44 +00001646
Guido van Rossumd8faa362007-04-27 19:54:29 +00001647class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001648
Guido van Rossumd8faa362007-04-27 19:54:29 +00001649 def _test(self, name, link=None):
1650 # See GNUWriteTest.
1651 tarinfo = tarfile.TarInfo(name)
1652 if link:
1653 tarinfo.linkname = link
1654 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001655
Guido van Rossumd8faa362007-04-27 19:54:29 +00001656 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001657 try:
1658 tar.addfile(tarinfo)
1659 finally:
1660 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001661
Guido van Rossumd8faa362007-04-27 19:54:29 +00001662 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001663 try:
1664 if link:
1665 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001666 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001667 else:
1668 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001669 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001670 finally:
1671 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001672
Guido van Rossume7ba4952007-06-06 23:52:48 +00001673 def test_pax_global_header(self):
1674 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001675 "foo": "bar",
1676 "uid": "0",
1677 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001678 "test": "\xe4\xf6\xfc",
1679 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001680
Benjamin Peterson886af962010-03-21 23:13:07 +00001681 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001682 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001683 try:
1684 tar.addfile(tarfile.TarInfo("test"))
1685 finally:
1686 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001687
1688 # Test if the global header was written correctly.
1689 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001690 try:
1691 self.assertEqual(tar.pax_headers, pax_headers)
1692 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1693 # Test if all the fields are strings.
1694 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001695 self.assertIsNot(type(key), bytes)
1696 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001697 if key in tarfile.PAX_NUMBER_FIELDS:
1698 try:
1699 tarfile.PAX_NUMBER_FIELDS[key](val)
1700 except (TypeError, ValueError):
1701 self.fail("unable to convert pax header field")
1702 finally:
1703 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001704
1705 def test_pax_extended_header(self):
1706 # The fields from the pax header have priority over the
1707 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001708 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001709
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001710 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1711 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001712 try:
1713 t = tarfile.TarInfo()
1714 t.name = "\xe4\xf6\xfc" # non-ASCII
1715 t.uid = 8**8 # too large
1716 t.pax_headers = pax_headers
1717 tar.addfile(t)
1718 finally:
1719 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001720
1721 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001722 try:
1723 t = tar.getmembers()[0]
1724 self.assertEqual(t.pax_headers, pax_headers)
1725 self.assertEqual(t.name, "foo")
1726 self.assertEqual(t.uid, 123)
1727 finally:
1728 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001729
1730
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001731class UnicodeTest:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001732
1733 def test_iso8859_1_filename(self):
1734 self._test_unicode_filename("iso8859-1")
1735
1736 def test_utf7_filename(self):
1737 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001738
1739 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001740 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001741
Guido van Rossumd8faa362007-04-27 19:54:29 +00001742 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001743 tar = tarfile.open(tmpname, "w", format=self.format,
1744 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001745 try:
1746 name = "\xe4\xf6\xfc"
1747 tar.addfile(tarfile.TarInfo(name))
1748 finally:
1749 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001750
1751 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001752 try:
1753 self.assertEqual(tar.getmembers()[0].name, name)
1754 finally:
1755 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001756
1757 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001758 tar = tarfile.open(tmpname, "w", format=self.format,
1759 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001760 try:
1761 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001762
Antoine Pitrou95f55602010-09-23 18:36:46 +00001763 tarinfo.name = "\xe4\xf6\xfc"
1764 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001765
Antoine Pitrou95f55602010-09-23 18:36:46 +00001766 tarinfo.name = "foo"
1767 tarinfo.uname = "\xe4\xf6\xfc"
1768 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1769 finally:
1770 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001771
1772 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001773 tar = tarfile.open(tarname, "r",
1774 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001775 try:
1776 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001777 self.assertIs(type(t.name), str)
1778 self.assertIs(type(t.linkname), str)
1779 self.assertIs(type(t.uname), str)
1780 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001781 finally:
1782 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001783
Guido van Rossume7ba4952007-06-06 23:52:48 +00001784 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001785 t = tarfile.TarInfo("foo")
1786 t.uname = "\xe4\xf6\xfc"
1787 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001788
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001789 tar = tarfile.open(tmpname, mode="w", format=self.format,
1790 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001791 try:
1792 tar.addfile(t)
1793 finally:
1794 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001795
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001796 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001797 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001798 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001799 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1800 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1801
1802 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001803 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001804 tar = tarfile.open(tmpname, encoding="ascii")
1805 t = tar.getmember("foo")
1806 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1807 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1808 finally:
1809 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001810
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001811
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001812class UstarUnicodeTest(UnicodeTest, unittest.TestCase):
1813
1814 format = tarfile.USTAR_FORMAT
1815
1816 # Test whether the utf-8 encoded version of a filename exceeds the 100
1817 # bytes name field limit (every occurrence of '\xff' will be expanded to 2
1818 # bytes).
1819 def test_unicode_name1(self):
1820 self._test_ustar_name("0123456789" * 10)
1821 self._test_ustar_name("0123456789" * 10 + "0", ValueError)
1822 self._test_ustar_name("0123456789" * 9 + "01234567\xff")
1823 self._test_ustar_name("0123456789" * 9 + "012345678\xff", ValueError)
1824
1825 def test_unicode_name2(self):
1826 self._test_ustar_name("0123456789" * 9 + "012345\xff\xff")
1827 self._test_ustar_name("0123456789" * 9 + "0123456\xff\xff", ValueError)
1828
1829 # Test whether the utf-8 encoded version of a filename exceeds the 155
1830 # bytes prefix + '/' + 100 bytes name limit.
1831 def test_unicode_longname1(self):
1832 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 10)
1833 self._test_ustar_name("0123456789" * 15 + "0123/4" + "0123456789" * 10, ValueError)
1834 self._test_ustar_name("0123456789" * 15 + "012\xff/" + "0123456789" * 10)
1835 self._test_ustar_name("0123456789" * 15 + "0123\xff/" + "0123456789" * 10, ValueError)
1836
1837 def test_unicode_longname2(self):
1838 self._test_ustar_name("0123456789" * 15 + "01\xff/2" + "0123456789" * 10, ValueError)
1839 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/" + "0123456789" * 10, ValueError)
1840
1841 def test_unicode_longname3(self):
1842 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/2" + "0123456789" * 10, ValueError)
1843 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "01234567\xff")
1844 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345678\xff", ValueError)
1845
1846 def test_unicode_longname4(self):
1847 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345\xff\xff")
1848 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "0123456\xff\xff", ValueError)
1849
1850 def _test_ustar_name(self, name, exc=None):
1851 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1852 t = tarfile.TarInfo(name)
1853 if exc is None:
1854 tar.addfile(t)
1855 else:
1856 self.assertRaises(exc, tar.addfile, t)
1857
1858 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001859 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001860 for t in tar:
1861 self.assertEqual(name, t.name)
1862 break
1863
1864 # Test the same as above for the 100 bytes link field.
1865 def test_unicode_link1(self):
1866 self._test_ustar_link("0123456789" * 10)
1867 self._test_ustar_link("0123456789" * 10 + "0", ValueError)
1868 self._test_ustar_link("0123456789" * 9 + "01234567\xff")
1869 self._test_ustar_link("0123456789" * 9 + "012345678\xff", ValueError)
1870
1871 def test_unicode_link2(self):
1872 self._test_ustar_link("0123456789" * 9 + "012345\xff\xff")
1873 self._test_ustar_link("0123456789" * 9 + "0123456\xff\xff", ValueError)
1874
1875 def _test_ustar_link(self, name, exc=None):
1876 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1877 t = tarfile.TarInfo("foo")
1878 t.linkname = name
1879 if exc is None:
1880 tar.addfile(t)
1881 else:
1882 self.assertRaises(exc, tar.addfile, t)
1883
1884 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001885 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001886 for t in tar:
1887 self.assertEqual(name, t.linkname)
1888 break
1889
1890
1891class GNUUnicodeTest(UnicodeTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001892
Guido van Rossume7ba4952007-06-06 23:52:48 +00001893 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001894
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001895 def test_bad_pax_header(self):
1896 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1897 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001898 for encoding, name in (
1899 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001900 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001901 with tarfile.open(tarname, encoding=encoding,
1902 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001903 try:
1904 t = tar.getmember(name)
1905 except KeyError:
1906 self.fail("unable to read bad GNU tar pax header")
1907
Guido van Rossumd8faa362007-04-27 19:54:29 +00001908
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001909class PAXUnicodeTest(UnicodeTest, unittest.TestCase):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001910
1911 format = tarfile.PAX_FORMAT
1912
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001913 # PAX_FORMAT ignores encoding in write mode.
1914 test_unicode_filename_error = None
1915
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001916 def test_binary_header(self):
1917 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001918 for encoding, name in (
1919 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001920 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001921 with tarfile.open(tarname, encoding=encoding,
1922 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001923 try:
1924 t = tar.getmember(name)
1925 except KeyError:
1926 self.fail("unable to read POSIX.1-2008 binary header")
1927
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001928
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001929class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001930 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001931
Guido van Rossumd8faa362007-04-27 19:54:29 +00001932 def setUp(self):
1933 self.tarname = tmpname
1934 if os.path.exists(self.tarname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001935 support.unlink(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001936
Guido van Rossumd8faa362007-04-27 19:54:29 +00001937 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001938 with tarfile.open(tarname, encoding="iso8859-1") as src:
1939 t = src.getmember("ustar/regtype")
1940 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001941 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001942 with tarfile.open(self.tarname, mode) as tar:
1943 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001944
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001945 def test_append_compressed(self):
1946 self._create_testtar("w:" + self.suffix)
1947 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1948
1949class AppendTest(AppendTestBase, unittest.TestCase):
1950 test_append_compressed = None
1951
1952 def _add_testfile(self, fileobj=None):
1953 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1954 tar.addfile(tarfile.TarInfo("bar"))
1955
Guido van Rossumd8faa362007-04-27 19:54:29 +00001956 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001957 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1958 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001959
1960 def test_non_existing(self):
1961 self._add_testfile()
1962 self._test()
1963
1964 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001965 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001966 self._add_testfile()
1967 self._test()
1968
1969 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001970 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001971 self._add_testfile(fobj)
1972 fobj.seek(0)
1973 self._test(fileobj=fobj)
1974
1975 def test_fileobj(self):
1976 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001977 with open(self.tarname, "rb") as fobj:
1978 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001979 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001980 self._add_testfile(fobj)
1981 fobj.seek(0)
1982 self._test(names=["foo", "bar"], fileobj=fobj)
1983
1984 def test_existing(self):
1985 self._create_testtar()
1986 self._add_testfile()
1987 self._test(names=["foo", "bar"])
1988
Lars Gustäbel9520a432009-11-22 18:48:49 +00001989 # Append mode is supposed to fail if the tarfile to append to
1990 # does not end with a zero block.
1991 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001992 with open(self.tarname, "wb") as fobj:
1993 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001994 self.assertRaises(tarfile.ReadError, self._add_testfile)
1995
1996 def test_null(self):
1997 self._test_error(b"")
1998
1999 def test_incomplete(self):
2000 self._test_error(b"\0" * 13)
2001
2002 def test_premature_eof(self):
2003 data = tarfile.TarInfo("foo").tobuf()
2004 self._test_error(data)
2005
2006 def test_trailing_garbage(self):
2007 data = tarfile.TarInfo("foo").tobuf()
2008 self._test_error(data + b"\0" * 13)
2009
2010 def test_invalid(self):
2011 self._test_error(b"a" * 512)
2012
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002013class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
2014 pass
2015
2016class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
2017 pass
2018
2019class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
2020 pass
2021
Guido van Rossumd8faa362007-04-27 19:54:29 +00002022
2023class LimitsTest(unittest.TestCase):
2024
2025 def test_ustar_limits(self):
2026 # 100 char name
2027 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002028 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002029
2030 # 101 char name that cannot be stored
2031 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002032 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002033
2034 # 256 char name with a slash at pos 156
2035 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002036 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002037
2038 # 256 char name that cannot be stored
2039 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002040 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002041
2042 # 512 char name
2043 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002044 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002045
2046 # 512 char linkname
2047 tarinfo = tarfile.TarInfo("longlink")
2048 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002049 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002050
2051 # uid > 8 digits
2052 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002053 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002054 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002055
2056 def test_gnu_limits(self):
2057 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002058 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002059
2060 tarinfo = tarfile.TarInfo("longlink")
2061 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002062 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002063
2064 # uid >= 256 ** 7
2065 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002066 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002067 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002068
2069 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002070 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002071 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002072
2073 tarinfo = tarfile.TarInfo("longlink")
2074 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002075 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002076
2077 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002078 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002079 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002080
2081
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002082class MiscTest(unittest.TestCase):
2083
2084 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002085 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
2086 b"foo\0\0\0\0\0")
2087 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
2088 b"foo")
2089 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
2090 "foo")
2091 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
2092 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002093
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002094 def test_read_number_fields(self):
2095 # Issue 13158: Test if GNU tar specific base-256 number fields
2096 # are decoded correctly.
2097 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
2098 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002099 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
2100 0o10000000)
2101 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
2102 0xffffffff)
2103 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
2104 -1)
2105 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
2106 -100)
2107 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
2108 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002109
Lars Gustäbelb7a688b2015-07-02 19:38:38 +02002110 # Issue 24514: Test if empty number fields are converted to zero.
2111 self.assertEqual(tarfile.nti(b"\0"), 0)
2112 self.assertEqual(tarfile.nti(b" \0"), 0)
2113
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002114 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002115 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002116 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002117 self.assertEqual(tarfile.itn(0o10000000),
2118 b"\x80\x00\x00\x00\x00\x20\x00\x00")
2119 self.assertEqual(tarfile.itn(0xffffffff),
2120 b"\x80\x00\x00\x00\xff\xff\xff\xff")
2121 self.assertEqual(tarfile.itn(-1),
2122 b"\xff\xff\xff\xff\xff\xff\xff\xff")
2123 self.assertEqual(tarfile.itn(-100),
2124 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
2125 self.assertEqual(tarfile.itn(-0x100000000000000),
2126 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002127
2128 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002129 with self.assertRaises(ValueError):
2130 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
2131 with self.assertRaises(ValueError):
2132 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
2133 with self.assertRaises(ValueError):
2134 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
2135 with self.assertRaises(ValueError):
2136 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002137
Martin Panter104dcda2016-01-16 06:59:13 +00002138 def test__all__(self):
Martin Panter5318d102016-01-16 11:01:14 +00002139 blacklist = {'version', 'grp', 'pwd', 'symlink_exception',
Martin Panter104dcda2016-01-16 06:59:13 +00002140 'NUL', 'BLOCKSIZE', 'RECORDSIZE', 'GNU_MAGIC',
2141 'POSIX_MAGIC', 'LENGTH_NAME', 'LENGTH_LINK',
2142 'LENGTH_PREFIX', 'REGTYPE', 'AREGTYPE', 'LNKTYPE',
2143 'SYMTYPE', 'CHRTYPE', 'BLKTYPE', 'DIRTYPE', 'FIFOTYPE',
2144 'CONTTYPE', 'GNUTYPE_LONGNAME', 'GNUTYPE_LONGLINK',
2145 'GNUTYPE_SPARSE', 'XHDTYPE', 'XGLTYPE', 'SOLARIS_XHDTYPE',
2146 'SUPPORTED_TYPES', 'REGULAR_TYPES', 'GNU_TYPES',
2147 'PAX_FIELDS', 'PAX_NAME_FIELDS', 'PAX_NUMBER_FIELDS',
2148 'stn', 'nts', 'nti', 'itn', 'calc_chksums', 'copyfileobj',
2149 'filemode',
2150 'EmptyHeaderError', 'TruncatedHeaderError',
2151 'EOFHeaderError', 'InvalidHeaderError',
Serhiy Storchaka2c1d3e32016-01-16 11:05:11 +02002152 'SubsequentHeaderError', 'ExFileObject',
Martin Panter104dcda2016-01-16 06:59:13 +00002153 'main'}
2154 support.check__all__(self, tarfile, blacklist=blacklist)
2155
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002156
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002157class CommandLineTest(unittest.TestCase):
2158
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002159 def tarfilecmd(self, *args, **kwargs):
2160 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
2161 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01002162 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002163
2164 def tarfilecmd_failure(self, *args):
2165 return script_helper.assert_python_failure('-m', 'tarfile', *args)
2166
2167 def make_simple_tarfile(self, tar_name):
2168 files = [support.findfile('tokenize_tests.txt'),
2169 support.findfile('tokenize_tests-no-coding-cookie-'
2170 'and-utf8-bom-sig-only.txt')]
2171 self.addCleanup(support.unlink, tar_name)
2172 with tarfile.open(tar_name, 'w') as tf:
2173 for tardata in files:
2174 tf.add(tardata, arcname=os.path.basename(tardata))
2175
Serhiy Storchaka150cd192017-04-07 18:56:12 +03002176 def test_bad_use(self):
2177 rc, out, err = self.tarfilecmd_failure()
2178 self.assertEqual(out, b'')
2179 self.assertIn(b'usage', err.lower())
2180 self.assertIn(b'error', err.lower())
2181 self.assertIn(b'required', err.lower())
2182 rc, out, err = self.tarfilecmd_failure('-l', '')
2183 self.assertEqual(out, b'')
2184 self.assertNotEqual(err.strip(), b'')
2185
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002186 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002187 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002188 for opt in '-t', '--test':
2189 out = self.tarfilecmd(opt, tar_name)
2190 self.assertEqual(out, b'')
2191
2192 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002193 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002194 for opt in '-v', '--verbose':
2195 out = self.tarfilecmd(opt, '-t', tar_name)
2196 self.assertIn(b'is a tar archive.\n', out)
2197
2198 def test_test_command_invalid_file(self):
2199 zipname = support.findfile('zipdir.zip')
2200 rc, out, err = self.tarfilecmd_failure('-t', zipname)
2201 self.assertIn(b' is not a tar archive.', err)
2202 self.assertEqual(out, b'')
2203 self.assertEqual(rc, 1)
2204
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002205 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002206 with self.subTest(tar_name=tar_name):
2207 with open(tar_name, 'rb') as f:
2208 data = f.read()
2209 try:
2210 with open(tmpname, 'wb') as f:
2211 f.write(data[:511])
2212 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
2213 self.assertEqual(out, b'')
2214 self.assertEqual(rc, 1)
2215 finally:
2216 support.unlink(tmpname)
2217
2218 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002219 for tar_name in testtarnames:
2220 with support.captured_stdout() as t:
2221 with tarfile.open(tar_name, 'r') as tf:
2222 tf.list(verbose=False)
2223 expected = t.getvalue().encode('ascii', 'backslashreplace')
2224 for opt in '-l', '--list':
2225 out = self.tarfilecmd(opt, tar_name,
2226 PYTHONIOENCODING='ascii')
2227 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002228
2229 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002230 for tar_name in testtarnames:
2231 with support.captured_stdout() as t:
2232 with tarfile.open(tar_name, 'r') as tf:
2233 tf.list(verbose=True)
2234 expected = t.getvalue().encode('ascii', 'backslashreplace')
2235 for opt in '-v', '--verbose':
2236 out = self.tarfilecmd(opt, '-l', tar_name,
2237 PYTHONIOENCODING='ascii')
2238 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002239
2240 def test_list_command_invalid_file(self):
2241 zipname = support.findfile('zipdir.zip')
2242 rc, out, err = self.tarfilecmd_failure('-l', zipname)
2243 self.assertIn(b' is not a tar archive.', err)
2244 self.assertEqual(out, b'')
2245 self.assertEqual(rc, 1)
2246
2247 def test_create_command(self):
2248 files = [support.findfile('tokenize_tests.txt'),
2249 support.findfile('tokenize_tests-no-coding-cookie-'
2250 'and-utf8-bom-sig-only.txt')]
2251 for opt in '-c', '--create':
2252 try:
2253 out = self.tarfilecmd(opt, tmpname, *files)
2254 self.assertEqual(out, b'')
2255 with tarfile.open(tmpname) as tar:
2256 tar.getmembers()
2257 finally:
2258 support.unlink(tmpname)
2259
2260 def test_create_command_verbose(self):
2261 files = [support.findfile('tokenize_tests.txt'),
2262 support.findfile('tokenize_tests-no-coding-cookie-'
2263 'and-utf8-bom-sig-only.txt')]
2264 for opt in '-v', '--verbose':
2265 try:
2266 out = self.tarfilecmd(opt, '-c', tmpname, *files)
2267 self.assertIn(b' file created.', out)
2268 with tarfile.open(tmpname) as tar:
2269 tar.getmembers()
2270 finally:
2271 support.unlink(tmpname)
2272
2273 def test_create_command_dotless_filename(self):
2274 files = [support.findfile('tokenize_tests.txt')]
2275 try:
2276 out = self.tarfilecmd('-c', dotlessname, *files)
2277 self.assertEqual(out, b'')
2278 with tarfile.open(dotlessname) as tar:
2279 tar.getmembers()
2280 finally:
2281 support.unlink(dotlessname)
2282
2283 def test_create_command_dot_started_filename(self):
2284 tar_name = os.path.join(TEMPDIR, ".testtar")
2285 files = [support.findfile('tokenize_tests.txt')]
2286 try:
2287 out = self.tarfilecmd('-c', tar_name, *files)
2288 self.assertEqual(out, b'')
2289 with tarfile.open(tar_name) as tar:
2290 tar.getmembers()
2291 finally:
2292 support.unlink(tar_name)
2293
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002294 def test_create_command_compressed(self):
2295 files = [support.findfile('tokenize_tests.txt'),
2296 support.findfile('tokenize_tests-no-coding-cookie-'
2297 'and-utf8-bom-sig-only.txt')]
2298 for filetype in (GzipTest, Bz2Test, LzmaTest):
2299 if not filetype.open:
2300 continue
2301 try:
2302 tar_name = tmpname + '.' + filetype.suffix
2303 out = self.tarfilecmd('-c', tar_name, *files)
2304 with filetype.taropen(tar_name) as tar:
2305 tar.getmembers()
2306 finally:
2307 support.unlink(tar_name)
2308
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002309 def test_extract_command(self):
2310 self.make_simple_tarfile(tmpname)
2311 for opt in '-e', '--extract':
2312 try:
2313 with support.temp_cwd(tarextdir):
2314 out = self.tarfilecmd(opt, tmpname)
2315 self.assertEqual(out, b'')
2316 finally:
2317 support.rmtree(tarextdir)
2318
2319 def test_extract_command_verbose(self):
2320 self.make_simple_tarfile(tmpname)
2321 for opt in '-v', '--verbose':
2322 try:
2323 with support.temp_cwd(tarextdir):
2324 out = self.tarfilecmd(opt, '-e', tmpname)
2325 self.assertIn(b' file is extracted.', out)
2326 finally:
2327 support.rmtree(tarextdir)
2328
2329 def test_extract_command_different_directory(self):
2330 self.make_simple_tarfile(tmpname)
2331 try:
2332 with support.temp_cwd(tarextdir):
2333 out = self.tarfilecmd('-e', tmpname, 'spamdir')
2334 self.assertEqual(out, b'')
2335 finally:
2336 support.rmtree(tarextdir)
2337
2338 def test_extract_command_invalid_file(self):
2339 zipname = support.findfile('zipdir.zip')
2340 with support.temp_cwd(tarextdir):
2341 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2342 self.assertIn(b' is not a tar archive.', err)
2343 self.assertEqual(out, b'')
2344 self.assertEqual(rc, 1)
2345
2346
Lars Gustäbel01385812010-03-03 12:08:54 +00002347class ContextManagerTest(unittest.TestCase):
2348
2349 def test_basic(self):
2350 with tarfile.open(tarname) as tar:
2351 self.assertFalse(tar.closed, "closed inside runtime context")
2352 self.assertTrue(tar.closed, "context manager failed")
2353
2354 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002355 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002356 # if the TarFile object is already closed.
2357 tar = tarfile.open(tarname)
2358 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002359 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002360 with tar:
2361 pass
2362
2363 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002364 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002365 with self.assertRaises(Exception) as exc:
2366 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002367 raise OSError
2368 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002369 "wrong exception raised in context manager")
2370 self.assertTrue(tar.closed, "context manager failed")
2371
2372 def test_no_eof(self):
2373 # __exit__() must not write end-of-archive blocks if an
2374 # exception was raised.
2375 try:
2376 with tarfile.open(tmpname, "w") as tar:
2377 raise Exception
2378 except:
2379 pass
2380 self.assertEqual(os.path.getsize(tmpname), 0,
2381 "context manager wrote an end-of-archive block")
2382 self.assertTrue(tar.closed, "context manager failed")
2383
2384 def test_eof(self):
2385 # __exit__() must write end-of-archive blocks, i.e. call
2386 # TarFile.close() if there was no error.
2387 with tarfile.open(tmpname, "w"):
2388 pass
2389 self.assertNotEqual(os.path.getsize(tmpname), 0,
2390 "context manager wrote no end-of-archive block")
2391
2392 def test_fileobj(self):
2393 # Test that __exit__() did not close the external file
2394 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002395 with open(tmpname, "wb") as fobj:
2396 try:
2397 with tarfile.open(fileobj=fobj, mode="w") as tar:
2398 raise Exception
2399 except:
2400 pass
2401 self.assertFalse(fobj.closed, "external file object was closed")
2402 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002403
2404
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002405@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2406class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002407
2408 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002409 # symbolic or hard links tarfile tries to extract these types of members
2410 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002411 def _test_link_extraction(self, name):
2412 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002413 with open(os.path.join(TEMPDIR, name), "rb") as f:
2414 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002415 self.assertEqual(md5sum(data), md5_regtype)
2416
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002417 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002418 @unittest.skipIf(hasattr(os.path, "islink"),
2419 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002420 def test_hardlink_extraction1(self):
2421 self._test_link_extraction("ustar/lnktype")
2422
Brian Curtind40e6f72010-07-08 21:39:08 +00002423 @unittest.skipIf(hasattr(os.path, "islink"),
2424 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002425 def test_hardlink_extraction2(self):
2426 self._test_link_extraction("./ustar/linktest2/lnktype")
2427
Brian Curtin74e45612010-07-09 15:58:59 +00002428 @unittest.skipIf(hasattr(os, "symlink"),
2429 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002430 def test_symlink_extraction1(self):
2431 self._test_link_extraction("ustar/symtype")
2432
Brian Curtin74e45612010-07-09 15:58:59 +00002433 @unittest.skipIf(hasattr(os, "symlink"),
2434 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002435 def test_symlink_extraction2(self):
2436 self._test_link_extraction("./ustar/linktest2/symtype")
2437
2438
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002439class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002440 # Issue5068: The _BZ2Proxy.read() method loops forever
2441 # on an empty or partial bzipped file.
2442
2443 def _test_partial_input(self, mode):
2444 class MyBytesIO(io.BytesIO):
2445 hit_eof = False
2446 def read(self, n):
2447 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002448 raise AssertionError("infinite loop detected in "
2449 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002450 self.hit_eof = self.tell() == len(self.getvalue())
2451 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002452 def seek(self, *args):
2453 self.hit_eof = False
2454 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002455
2456 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2457 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002458 try:
2459 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2460 except tarfile.ReadError:
2461 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002462
2463 def test_partial_input(self):
2464 self._test_partial_input("r")
2465
2466 def test_partial_input_bz2(self):
2467 self._test_partial_input("r:bz2")
2468
2469
Eric V. Smith7a803892015-04-15 10:27:58 -04002470def root_is_uid_gid_0():
2471 try:
2472 import pwd, grp
2473 except ImportError:
2474 return False
2475 if pwd.getpwuid(0)[0] != 'root':
2476 return False
2477 if grp.getgrgid(0)[0] != 'root':
2478 return False
2479 return True
2480
2481
Zachary Waread3e27a2015-05-12 23:57:21 -05002482@unittest.skipUnless(hasattr(os, 'chown'), "missing os.chown")
2483@unittest.skipUnless(hasattr(os, 'geteuid'), "missing os.geteuid")
Eric V. Smith7a803892015-04-15 10:27:58 -04002484class NumericOwnerTest(unittest.TestCase):
2485 # mock the following:
2486 # os.chown: so we can test what's being called
2487 # os.chmod: so the modes are not actually changed. if they are, we can't
2488 # delete the files/directories
2489 # os.geteuid: so we can lie and say we're root (uid = 0)
2490
2491 @staticmethod
2492 def _make_test_archive(filename_1, dirname_1, filename_2):
2493 # the file contents to write
2494 fobj = io.BytesIO(b"content")
2495
2496 # create a tar file with a file, a directory, and a file within that
2497 # directory. Assign various .uid/.gid values to them
2498 items = [(filename_1, 99, 98, tarfile.REGTYPE, fobj),
2499 (dirname_1, 77, 76, tarfile.DIRTYPE, None),
2500 (filename_2, 88, 87, tarfile.REGTYPE, fobj),
2501 ]
2502 with tarfile.open(tmpname, 'w') as tarfl:
2503 for name, uid, gid, typ, contents in items:
2504 t = tarfile.TarInfo(name)
2505 t.uid = uid
2506 t.gid = gid
2507 t.uname = 'root'
2508 t.gname = 'root'
2509 t.type = typ
2510 tarfl.addfile(t, contents)
2511
2512 # return the full pathname to the tar file
2513 return tmpname
2514
2515 @staticmethod
2516 @contextmanager
2517 def _setup_test(mock_geteuid):
2518 mock_geteuid.return_value = 0 # lie and say we're root
2519 fname = 'numeric-owner-testfile'
2520 dirname = 'dir'
2521
2522 # the names we want stored in the tarfile
2523 filename_1 = fname
2524 dirname_1 = dirname
2525 filename_2 = os.path.join(dirname, fname)
2526
2527 # create the tarfile with the contents we're after
2528 tar_filename = NumericOwnerTest._make_test_archive(filename_1,
2529 dirname_1,
2530 filename_2)
2531
2532 # open the tarfile for reading. yield it and the names of the items
2533 # we stored into the file
2534 with tarfile.open(tar_filename) as tarfl:
2535 yield tarfl, filename_1, dirname_1, filename_2
2536
2537 @unittest.mock.patch('os.chown')
2538 @unittest.mock.patch('os.chmod')
2539 @unittest.mock.patch('os.geteuid')
2540 def test_extract_with_numeric_owner(self, mock_geteuid, mock_chmod,
2541 mock_chown):
2542 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _,
2543 filename_2):
2544 tarfl.extract(filename_1, TEMPDIR, numeric_owner=True)
2545 tarfl.extract(filename_2 , TEMPDIR, numeric_owner=True)
2546
2547 # convert to filesystem paths
2548 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2549 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2550
2551 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2552 unittest.mock.call(f_filename_2, 88, 87),
2553 ],
2554 any_order=True)
2555
2556 @unittest.mock.patch('os.chown')
2557 @unittest.mock.patch('os.chmod')
2558 @unittest.mock.patch('os.geteuid')
2559 def test_extractall_with_numeric_owner(self, mock_geteuid, mock_chmod,
2560 mock_chown):
2561 with self._setup_test(mock_geteuid) as (tarfl, filename_1, dirname_1,
2562 filename_2):
2563 tarfl.extractall(TEMPDIR, numeric_owner=True)
2564
2565 # convert to filesystem paths
2566 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2567 f_dirname_1 = os.path.join(TEMPDIR, dirname_1)
2568 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2569
2570 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2571 unittest.mock.call(f_dirname_1, 77, 76),
2572 unittest.mock.call(f_filename_2, 88, 87),
2573 ],
2574 any_order=True)
2575
2576 # this test requires that uid=0 and gid=0 really be named 'root'. that's
2577 # because the uname and gname in the test file are 'root', and extract()
2578 # will look them up using pwd and grp to find their uid and gid, which we
2579 # test here to be 0.
2580 @unittest.skipUnless(root_is_uid_gid_0(),
2581 'uid=0,gid=0 must be named "root"')
2582 @unittest.mock.patch('os.chown')
2583 @unittest.mock.patch('os.chmod')
2584 @unittest.mock.patch('os.geteuid')
2585 def test_extract_without_numeric_owner(self, mock_geteuid, mock_chmod,
2586 mock_chown):
2587 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2588 tarfl.extract(filename_1, TEMPDIR, numeric_owner=False)
2589
2590 # convert to filesystem paths
2591 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2592
2593 mock_chown.assert_called_with(f_filename_1, 0, 0)
2594
2595 @unittest.mock.patch('os.geteuid')
2596 def test_keyword_only(self, mock_geteuid):
2597 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2598 self.assertRaises(TypeError,
2599 tarfl.extract, filename_1, TEMPDIR, False, True)
2600
2601
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002602def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002603 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002604 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002605
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002606 global testtarnames
2607 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002608 with open(tarname, "rb") as fobj:
2609 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002610
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002611 # Create compressed tarfiles.
2612 for c in GzipTest, Bz2Test, LzmaTest:
2613 if c.open:
2614 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002615 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002616 with c.open(c.tarname, "wb") as tar:
2617 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002618
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002619def tearDownModule():
2620 if os.path.exists(TEMPDIR):
Tim Goldene0bd2c52014-05-06 13:24:26 +01002621 support.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002622
Neal Norwitz996acf12003-02-17 14:51:41 +00002623if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002624 unittest.main()