blob: 3c51c04c581e7f3f15481587931a7b7722e5fe2c [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
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00007
8import unittest
Eric V. Smith7a803892015-04-15 10:27:58 -04009import unittest.mock
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000010import tarfile
11
Berker Peksagce643912015-05-06 06:33:17 +030012from test import support
13from test.support import script_helper
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000014
15# Check for our compression modules.
16try:
17 import gzip
Brett Cannon260fbe82013-07-04 18:16:15 -040018except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000019 gzip = None
20try:
21 import bz2
Brett Cannon260fbe82013-07-04 18:16:15 -040022except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000023 bz2 = None
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010024try:
25 import lzma
Brett Cannon260fbe82013-07-04 18:16:15 -040026except ImportError:
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010027 lzma = None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000028
Guido van Rossumd8faa362007-04-27 19:54:29 +000029def md5sum(data):
Guido van Rossuma8add0e2007-05-14 22:03:55 +000030 return md5(data).hexdigest()
Guido van Rossumd8faa362007-04-27 19:54:29 +000031
Antoine Pitrouab58b5f2010-09-23 19:39:35 +000032TEMPDIR = os.path.abspath(support.TESTFN) + "-tardir"
Serhiy Storchakad27b4552013-11-24 01:53:29 +020033tarextdir = TEMPDIR + '-extract-test'
Antoine Pitrou941ee882009-11-11 20:59:38 +000034tarname = support.findfile("testtar.tar")
Guido van Rossumd8faa362007-04-27 19:54:29 +000035gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
36bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010037xzname = os.path.join(TEMPDIR, "testtar.tar.xz")
Guido van Rossumd8faa362007-04-27 19:54:29 +000038tmpname = os.path.join(TEMPDIR, "tmp.tar")
Serhiy Storchakad27b4552013-11-24 01:53:29 +020039dotlessname = os.path.join(TEMPDIR, "testtar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000040
Guido van Rossumd8faa362007-04-27 19:54:29 +000041md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
42md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000043
44
Serhiy Storchaka8b562922013-06-17 15:38:50 +030045class TarTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +000046 tarname = tarname
Serhiy Storchaka8b562922013-06-17 15:38:50 +030047 suffix = ''
48 open = io.FileIO
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020049 taropen = tarfile.TarFile.taropen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030050
51 @property
52 def mode(self):
53 return self.prefix + self.suffix
54
55@support.requires_gzip
56class GzipTest:
57 tarname = gzipname
58 suffix = 'gz'
59 open = gzip.GzipFile if gzip else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020060 taropen = tarfile.TarFile.gzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030061
62@support.requires_bz2
63class Bz2Test:
64 tarname = bz2name
65 suffix = 'bz2'
66 open = bz2.BZ2File if bz2 else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020067 taropen = tarfile.TarFile.bz2open
Serhiy Storchaka8b562922013-06-17 15:38:50 +030068
69@support.requires_lzma
70class LzmaTest:
71 tarname = xzname
72 suffix = 'xz'
73 open = lzma.LZMAFile if lzma else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020074 taropen = tarfile.TarFile.xzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030075
76
77class ReadTest(TarTest):
78
79 prefix = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000080
81 def setUp(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +030082 self.tar = tarfile.open(self.tarname, mode=self.mode,
83 encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000084
85 def tearDown(self):
86 self.tar.close()
87
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000088
Serhiy Storchaka8b562922013-06-17 15:38:50 +030089class UstarReadTest(ReadTest, unittest.TestCase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000090
Guido van Rossumd8faa362007-04-27 19:54:29 +000091 def test_fileobj_regular_file(self):
92 tarinfo = self.tar.getmember("ustar/regtype")
Lars Gustäbel7a919e92012-05-05 18:15:03 +020093 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000094 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +030095 self.assertEqual(len(data), tarinfo.size,
96 "regular file extraction failed")
97 self.assertEqual(md5sum(data), md5_regtype,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000098 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000099
Guido van Rossumd8faa362007-04-27 19:54:29 +0000100 def test_fileobj_readlines(self):
101 self.tar.extract("ustar/regtype", TEMPDIR)
102 tarinfo = self.tar.getmember("ustar/regtype")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000103 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
104 lines1 = fobj1.readlines()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000105
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200106 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000107 fobj2 = io.TextIOWrapper(fobj)
108 lines2 = fobj2.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300109 self.assertEqual(lines1, lines2,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000110 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300111 self.assertEqual(len(lines2), 114,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000112 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300113 self.assertEqual(lines2[83],
114 "I will gladly admit that Python is not the fastest "
115 "running scripting language.\n",
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000116 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000117
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118 def test_fileobj_iter(self):
119 self.tar.extract("ustar/regtype", TEMPDIR)
120 tarinfo = self.tar.getmember("ustar/regtype")
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200121 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000122 lines1 = fobj1.readlines()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200123 with self.tar.extractfile(tarinfo) as fobj2:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000124 lines2 = list(io.TextIOWrapper(fobj2))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300125 self.assertEqual(lines1, lines2,
126 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +0000127
Guido van Rossumd8faa362007-04-27 19:54:29 +0000128 def test_fileobj_seek(self):
129 self.tar.extract("ustar/regtype", TEMPDIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000130 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
131 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +0000132
Guido van Rossumd8faa362007-04-27 19:54:29 +0000133 tarinfo = self.tar.getmember("ustar/regtype")
134 fobj = self.tar.extractfile(tarinfo)
135
136 text = fobj.read()
137 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000138 self.assertEqual(0, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000139 "seek() to file's start failed")
140 fobj.seek(2048, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000141 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000142 "seek() to absolute position failed")
143 fobj.seek(-1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000144 self.assertEqual(1024, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000145 "seek() to negative relative position failed")
146 fobj.seek(1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000147 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148 "seek() to positive relative position failed")
149 s = fobj.read(10)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300150 self.assertEqual(s, data[2048:2058],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000151 "read() after seek failed")
152 fobj.seek(0, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000153 self.assertEqual(tarinfo.size, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000154 "seek() to file's end failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300155 self.assertEqual(fobj.read(), b"",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156 "read() at file's end did not return empty string")
157 fobj.seek(-tarinfo.size, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000158 self.assertEqual(0, fobj.tell(),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000159 "relative seek() to file's end failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000160 fobj.seek(512)
161 s1 = fobj.readlines()
162 fobj.seek(512)
163 s2 = fobj.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300164 self.assertEqual(s1, s2,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000165 "readlines() after seek failed")
166 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000167 self.assertEqual(len(fobj.readline()), fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000168 "tell() after readline() failed")
169 fobj.seek(512)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300170 self.assertEqual(len(fobj.readline()) + 512, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000171 "tell() after seek() and readline() failed")
172 fobj.seek(0)
173 line = fobj.readline()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000174 self.assertEqual(fobj.read(), data[len(line):],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000175 "read() after readline() failed")
176 fobj.close()
177
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200178 def test_fileobj_text(self):
179 with self.tar.extractfile("ustar/regtype") as fobj:
180 fobj = io.TextIOWrapper(fobj)
181 data = fobj.read().encode("iso8859-1")
182 self.assertEqual(md5sum(data), md5_regtype)
183 try:
184 fobj.seek(100)
185 except AttributeError:
186 # Issue #13815: seek() complained about a missing
187 # flush() method.
188 self.fail("seeking failed in text mode")
189
Lars Gustäbel1b512722010-06-03 12:45:16 +0000190 # Test if symbolic and hard links are resolved by extractfile(). The
191 # test link members each point to a regular member whose data is
192 # supposed to be exported.
193 def _test_fileobj_link(self, lnktype, regtype):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300194 with self.tar.extractfile(lnktype) as a, \
195 self.tar.extractfile(regtype) as b:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000196 self.assertEqual(a.name, b.name)
Lars Gustäbel1b512722010-06-03 12:45:16 +0000197
198 def test_fileobj_link1(self):
199 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
200
201 def test_fileobj_link2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300202 self._test_fileobj_link("./ustar/linktest2/lnktype",
203 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000204
205 def test_fileobj_symlink1(self):
206 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
207
208 def test_fileobj_symlink2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300209 self._test_fileobj_link("./ustar/linktest2/symtype",
210 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000211
Lars Gustäbel1ef9eda2012-04-24 21:04:40 +0200212 def test_issue14160(self):
213 self._test_fileobj_link("symtype2", "ustar/regtype")
214
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300215class GzipUstarReadTest(GzipTest, UstarReadTest):
216 pass
217
218class Bz2UstarReadTest(Bz2Test, UstarReadTest):
219 pass
220
221class LzmaUstarReadTest(LzmaTest, UstarReadTest):
222 pass
223
Guido van Rossumd8faa362007-04-27 19:54:29 +0000224
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200225class ListTest(ReadTest, unittest.TestCase):
226
227 # Override setUp to use default encoding (UTF-8)
228 def setUp(self):
229 self.tar = tarfile.open(self.tarname, mode=self.mode)
230
231 def test_list(self):
232 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
233 with support.swap_attr(sys, 'stdout', tio):
234 self.tar.list(verbose=False)
235 out = tio.detach().getvalue()
236 self.assertIn(b'ustar/conttype', out)
237 self.assertIn(b'ustar/regtype', out)
238 self.assertIn(b'ustar/lnktype', out)
239 self.assertIn(b'ustar' + (b'/12345' * 40) + b'67/longname', out)
240 self.assertIn(b'./ustar/linktest2/symtype', out)
241 self.assertIn(b'./ustar/linktest2/lnktype', out)
242 # Make sure it puts trailing slash for directory
243 self.assertIn(b'ustar/dirtype/', out)
244 self.assertIn(b'ustar/dirtype-with-size/', out)
245 # Make sure it is able to print unencodable characters
Serhiy Storchaka162c4772014-02-19 18:44:12 +0200246 def conv(b):
247 s = b.decode(self.tar.encoding, 'surrogateescape')
248 return s.encode('ascii', 'backslashreplace')
249 self.assertIn(conv(b'ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
250 self.assertIn(conv(b'misc/regtype-hpux-signed-chksum-'
251 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
252 self.assertIn(conv(b'misc/regtype-old-v7-signed-chksum-'
253 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
254 self.assertIn(conv(b'pax/bad-pax-\xe4\xf6\xfc'), out)
255 self.assertIn(conv(b'pax/hdrcharset-\xe4\xf6\xfc'), out)
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200256 # Make sure it prints files separated by one newline without any
257 # 'ls -l'-like accessories if verbose flag is not being used
258 # ...
259 # ustar/conttype
260 # ustar/regtype
261 # ...
262 self.assertRegex(out, br'ustar/conttype ?\r?\n'
263 br'ustar/regtype ?\r?\n')
264 # Make sure it does not print the source of link without verbose flag
265 self.assertNotIn(b'link to', out)
266 self.assertNotIn(b'->', out)
267
268 def test_list_verbose(self):
269 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
270 with support.swap_attr(sys, 'stdout', tio):
271 self.tar.list(verbose=True)
272 out = tio.detach().getvalue()
273 # Make sure it prints files separated by one newline with 'ls -l'-like
274 # accessories if verbose flag is being used
275 # ...
276 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
277 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
278 # ...
Serhiy Storchaka255493c2014-02-05 20:54:43 +0200279 self.assertRegex(out, (br'\?rw-r--r-- tarfile/tarfile\s+7011 '
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200280 br'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
281 br'ustar/\w+type ?\r?\n') * 2)
282 # Make sure it prints the source of link with verbose flag
283 self.assertIn(b'ustar/symtype -> regtype', out)
284 self.assertIn(b'./ustar/linktest2/symtype -> ../linktest1/regtype', out)
285 self.assertIn(b'./ustar/linktest2/lnktype link to '
286 b'./ustar/linktest1/regtype', out)
287 self.assertIn(b'gnu' + (b'/123' * 125) + b'/longlink link to gnu' +
288 (b'/123' * 125) + b'/longname', out)
289 self.assertIn(b'pax' + (b'/123' * 125) + b'/longlink link to pax' +
290 (b'/123' * 125) + b'/longname', out)
291
Serhiy Storchakaa7eb7462014-08-21 10:01:16 +0300292 def test_list_members(self):
293 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
294 def members(tar):
295 for tarinfo in tar.getmembers():
296 if 'reg' in tarinfo.name:
297 yield tarinfo
298 with support.swap_attr(sys, 'stdout', tio):
299 self.tar.list(verbose=False, members=members(self.tar))
300 out = tio.detach().getvalue()
301 self.assertIn(b'ustar/regtype', out)
302 self.assertNotIn(b'ustar/conttype', out)
303
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200304
305class GzipListTest(GzipTest, ListTest):
306 pass
307
308
309class Bz2ListTest(Bz2Test, ListTest):
310 pass
311
312
313class LzmaListTest(LzmaTest, ListTest):
314 pass
315
316
Lars Gustäbel9520a432009-11-22 18:48:49 +0000317class CommonReadTest(ReadTest):
318
319 def test_empty_tarfile(self):
320 # Test for issue6123: Allow opening empty archives.
321 # This test checks if tarfile.open() is able to open an empty tar
322 # archive successfully. Note that an empty tar archive is not the
323 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000324 with tarfile.open(tmpname, self.mode.replace("r", "w")):
325 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000326 try:
327 tar = tarfile.open(tmpname, self.mode)
328 tar.getnames()
329 except tarfile.ReadError:
330 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000331 else:
332 self.assertListEqual(tar.getmembers(), [])
333 finally:
334 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000335
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200336 def test_non_existent_tarfile(self):
337 # Test for issue11513: prevent non-existent gzipped tarfiles raising
338 # multiple exceptions.
339 with self.assertRaisesRegex(FileNotFoundError, "xxx"):
340 tarfile.open("xxx", self.mode)
341
Lars Gustäbel9520a432009-11-22 18:48:49 +0000342 def test_null_tarfile(self):
343 # Test for issue6123: Allow opening empty archives.
344 # This test guarantees that tarfile.open() does not treat an empty
345 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000346 with open(tmpname, "wb"):
347 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000348 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
349 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
350
351 def test_ignore_zeros(self):
352 # Test TarFile's ignore_zeros option.
Serhiy Storchakaa89d22a2016-10-30 20:52:29 +0200353 # generate 512 pseudorandom bytes
354 data = Random(0).getrandbits(512*8).to_bytes(512, 'big')
Lars Gustäbel9520a432009-11-22 18:48:49 +0000355 for char in (b'\0', b'a'):
356 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
357 # are ignored correctly.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300358 with self.open(tmpname, "w") as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000359 fobj.write(char * 1024)
Serhiy Storchakaa89d22a2016-10-30 20:52:29 +0200360 tarinfo = tarfile.TarInfo("foo")
361 tarinfo.size = len(data)
362 fobj.write(tarinfo.tobuf())
363 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +0000364
365 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000366 try:
367 self.assertListEqual(tar.getnames(), ["foo"],
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300368 "ignore_zeros=True should have skipped the %r-blocks" %
369 char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000370 finally:
371 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000372
Lars Gustäbel03572682015-07-06 09:27:24 +0200373 def test_premature_end_of_archive(self):
374 for size in (512, 600, 1024, 1200):
375 with tarfile.open(tmpname, "w:") as tar:
376 t = tarfile.TarInfo("foo")
377 t.size = 1024
378 tar.addfile(t, io.BytesIO(b"a" * 1024))
379
380 with open(tmpname, "r+b") as fobj:
381 fobj.truncate(size)
382
383 with tarfile.open(tmpname) as tar:
384 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
385 for t in tar:
386 pass
387
388 with tarfile.open(tmpname) as tar:
389 t = tar.next()
390
391 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
392 tar.extract(t, TEMPDIR)
393
394 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
395 tar.extractfile(t).read()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000396
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300397class MiscReadTestBase(CommonReadTest):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300398 def requires_name_attribute(self):
399 pass
400
Thomas Woutersed03b412007-08-28 21:37:11 +0000401 def test_no_name_argument(self):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300402 self.requires_name_attribute()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000403 with open(self.tarname, "rb") as fobj:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300404 self.assertIsInstance(fobj.name, str)
405 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
406 self.assertIsInstance(tar.name, str)
407 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000408
Thomas Woutersed03b412007-08-28 21:37:11 +0000409 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000410 with open(self.tarname, "rb") as fobj:
411 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000412 fobj = io.BytesIO(data)
413 self.assertRaises(AttributeError, getattr, fobj, "name")
414 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300415 self.assertIsNone(tar.name)
Thomas Woutersed03b412007-08-28 21:37:11 +0000416
417 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000418 with open(self.tarname, "rb") as fobj:
419 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000420 fobj = io.BytesIO(data)
421 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000422 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300423 self.assertIsNone(tar.name)
424
425 def test_int_name_attribute(self):
426 # Issue 21044: tarfile.open() should handle fileobj with an integer
427 # 'name' attribute.
428 fd = os.open(self.tarname, os.O_RDONLY)
429 with open(fd, 'rb') as fobj:
430 self.assertIsInstance(fobj.name, int)
431 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
432 self.assertIsNone(tar.name)
433
434 def test_bytes_name_attribute(self):
435 self.requires_name_attribute()
436 tarname = os.fsencode(self.tarname)
437 with open(tarname, 'rb') as fobj:
438 self.assertIsInstance(fobj.name, bytes)
439 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
440 self.assertIsInstance(tar.name, bytes)
441 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Thomas Woutersed03b412007-08-28 21:37:11 +0000442
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +0200443 def test_illegal_mode_arg(self):
444 with open(tmpname, 'wb'):
445 pass
446 with self.assertRaisesRegex(ValueError, 'mode must be '):
447 tar = self.taropen(tmpname, 'q')
448 with self.assertRaisesRegex(ValueError, 'mode must be '):
449 tar = self.taropen(tmpname, 'rw')
450 with self.assertRaisesRegex(ValueError, 'mode must be '):
451 tar = self.taropen(tmpname, '')
452
Christian Heimesd8654cf2007-12-02 15:22:16 +0000453 def test_fileobj_with_offset(self):
454 # Skip the first member and store values from the second member
455 # of the testtar.
456 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000457 try:
458 tar.next()
459 t = tar.next()
460 name = t.name
461 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200462 with tar.extractfile(t) as f:
463 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000464 finally:
465 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000466
467 # Open the testtar and seek to the offset of the second member.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300468 with self.open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000469 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000470
Antoine Pitrou95f55602010-09-23 18:36:46 +0000471 # Test if the tarfile starts with the second member.
472 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
473 t = tar.next()
474 self.assertEqual(t.name, name)
475 # Read to the end of fileobj and test if seeking back to the
476 # beginning works.
477 tar.getmembers()
478 self.assertEqual(tar.extractfile(t).read(), data,
479 "seek back did not work")
480 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000481
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482 def test_fail_comp(self):
483 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000484 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000485 with open(tarname, "rb") as fobj:
486 self.assertRaises(tarfile.ReadError, tarfile.open,
487 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000488
489 def test_v7_dirtype(self):
490 # Test old style dirtype member (bug #1336623):
491 # Old V7 tars create directory members using an AREGTYPE
492 # header with a "/" appended to the filename field.
493 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300494 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000495 "v7 dirtype failed")
496
Christian Heimes126d29a2008-02-11 22:57:17 +0000497 def test_xstar_type(self):
498 # The xstar format stores extra atime and ctime fields inside the
499 # space reserved for the prefix field. The prefix field must be
500 # ignored in this case, otherwise it will mess up the name.
501 try:
502 self.tar.getmember("misc/regtype-xstar")
503 except KeyError:
504 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
505
Guido van Rossumd8faa362007-04-27 19:54:29 +0000506 def test_check_members(self):
507 for tarinfo in self.tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300508 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000509 "wrong mtime for %s" % tarinfo.name)
510 if not tarinfo.name.startswith("ustar/"):
511 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300512 self.assertEqual(tarinfo.uname, "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000513 "wrong uname for %s" % tarinfo.name)
514
515 def test_find_members(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300516 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000517 "could not find all members")
518
Brian Curtin74e45612010-07-09 15:58:59 +0000519 @unittest.skipUnless(hasattr(os, "link"),
520 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000521 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000522 def test_extract_hardlink(self):
523 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200524 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000525 tar.extract("ustar/regtype", TEMPDIR)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100526 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000527
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200528 tar.extract("ustar/lnktype", TEMPDIR)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100529 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000530 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
531 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000532 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000533
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200534 tar.extract("ustar/symtype", TEMPDIR)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100535 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000536 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
537 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000538 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000539
Christian Heimesfaf2f632008-01-06 16:59:19 +0000540 def test_extractall(self):
541 # Test if extractall() correctly restores directory permissions
542 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000543 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000544 DIR = os.path.join(TEMPDIR, "extractall")
545 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000546 try:
547 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000548 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000549 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000550 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000551 if sys.platform != "win32":
552 # Win32 has no support for fine grained permissions.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300553 self.assertEqual(tarinfo.mode & 0o777,
554 os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000555 def format_mtime(mtime):
556 if isinstance(mtime, float):
557 return "{} ({})".format(mtime, mtime.hex())
558 else:
559 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000560 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000561 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
562 format_mtime(tarinfo.mtime),
563 format_mtime(file_mtime),
564 path)
565 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000566 finally:
567 tar.close()
Tim Goldene0bd2c52014-05-06 13:24:26 +0100568 support.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000569
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000570 def test_extract_directory(self):
571 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000572 DIR = os.path.join(TEMPDIR, "extractdir")
573 os.mkdir(DIR)
574 try:
575 with tarfile.open(tarname, encoding="iso8859-1") as tar:
576 tarinfo = tar.getmember(dirtype)
577 tar.extract(tarinfo, path=DIR)
578 extracted = os.path.join(DIR, dirtype)
579 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
580 if sys.platform != "win32":
581 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
582 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +0100583 support.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000584
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000585 def test_init_close_fobj(self):
586 # Issue #7341: Close the internal file object in the TarFile
587 # constructor in case of an error. For the test we rely on
588 # the fact that opening an empty file raises a ReadError.
589 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000590 with open(empty, "wb") as fobj:
591 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000592
593 try:
594 tar = object.__new__(tarfile.TarFile)
595 try:
596 tar.__init__(empty)
597 except tarfile.ReadError:
598 self.assertTrue(tar.fileobj.closed)
599 else:
600 self.fail("ReadError not raised")
601 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000602 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000603
Serhiy Storchaka263fab92013-05-09 14:22:26 +0300604 def test_parallel_iteration(self):
605 # Issue #16601: Restarting iteration over tarfile continued
606 # from where it left off.
607 with tarfile.open(self.tarname) as tar:
608 for m1, m2 in zip(tar, tar):
609 self.assertEqual(m1.offset, m2.offset)
610 self.assertEqual(m1.get_info(), m2.get_info())
611
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300612class MiscReadTest(MiscReadTestBase, unittest.TestCase):
613 test_fail_comp = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000614
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300615class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200616 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300618class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300619 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300620 self.skipTest("BZ2File have no name attribute")
621
622class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300623 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300624 self.skipTest("LZMAFile have no name attribute")
625
626
627class StreamReadTest(CommonReadTest, unittest.TestCase):
628
629 prefix="r|"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000630
Lars Gustäbeldd071042011-02-23 11:42:22 +0000631 def test_read_through(self):
632 # Issue #11224: A poorly designed _FileInFile.read() method
633 # caused seeking errors with stream tar files.
634 for tarinfo in self.tar:
635 if not tarinfo.isreg():
636 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200637 with self.tar.extractfile(tarinfo) as fobj:
638 while True:
639 try:
640 buf = fobj.read(512)
641 except tarfile.StreamError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300642 self.fail("simple read-through using "
643 "TarFile.extractfile() failed")
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200644 if not buf:
645 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000646
Guido van Rossumd8faa362007-04-27 19:54:29 +0000647 def test_fileobj_regular_file(self):
648 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200649 with self.tar.extractfile(tarinfo) as fobj:
650 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300651 self.assertEqual(len(data), tarinfo.size,
652 "regular file extraction failed")
653 self.assertEqual(md5sum(data), md5_regtype,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000654 "regular file extraction failed")
655
656 def test_provoke_stream_error(self):
657 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200658 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
659 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000660
Guido van Rossumd8faa362007-04-27 19:54:29 +0000661 def test_compare_members(self):
662 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000663 try:
664 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000665
Antoine Pitrou95f55602010-09-23 18:36:46 +0000666 while True:
667 t1 = tar1.next()
668 t2 = tar2.next()
669 if t1 is None:
670 break
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300671 self.assertIsNotNone(t2, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000672
Antoine Pitrou95f55602010-09-23 18:36:46 +0000673 if t2.islnk() or t2.issym():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300674 with self.assertRaises(tarfile.StreamError):
675 tar2.extractfile(t2)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000676 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000677
Antoine Pitrou95f55602010-09-23 18:36:46 +0000678 v1 = tar1.extractfile(t1)
679 v2 = tar2.extractfile(t2)
680 if v1 is None:
681 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300682 self.assertIsNotNone(v2, "stream.extractfile() failed")
683 self.assertEqual(v1.read(), v2.read(),
684 "stream extraction failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000685 finally:
686 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000687
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300688class GzipStreamReadTest(GzipTest, StreamReadTest):
689 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000690
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300691class Bz2StreamReadTest(Bz2Test, StreamReadTest):
692 pass
Thomas Wouterscf297e42007-02-23 15:07:44 +0000693
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300694class LzmaStreamReadTest(LzmaTest, StreamReadTest):
695 pass
696
697
698class DetectReadTest(TarTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000699 def _testfunc_file(self, name, mode):
700 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000701 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000702 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000703 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000704 else:
705 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000706
Guido van Rossumd8faa362007-04-27 19:54:29 +0000707 def _testfunc_fileobj(self, name, mode):
708 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000709 with open(name, "rb") as f:
710 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000711 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000712 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000713 else:
714 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000715
716 def _test_modes(self, testfunc):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300717 if self.suffix:
718 with self.assertRaises(tarfile.ReadError):
719 tarfile.open(tarname, mode="r:" + self.suffix)
720 with self.assertRaises(tarfile.ReadError):
721 tarfile.open(tarname, mode="r|" + self.suffix)
722 with self.assertRaises(tarfile.ReadError):
723 tarfile.open(self.tarname, mode="r:")
724 with self.assertRaises(tarfile.ReadError):
725 tarfile.open(self.tarname, mode="r|")
726 testfunc(self.tarname, "r")
727 testfunc(self.tarname, "r:" + self.suffix)
728 testfunc(self.tarname, "r:*")
729 testfunc(self.tarname, "r|" + self.suffix)
730 testfunc(self.tarname, "r|*")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100731
Guido van Rossumd8faa362007-04-27 19:54:29 +0000732 def test_detect_file(self):
733 self._test_modes(self._testfunc_file)
734
735 def test_detect_fileobj(self):
736 self._test_modes(self._testfunc_fileobj)
737
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300738class GzipDetectReadTest(GzipTest, DetectReadTest):
739 pass
740
741class Bz2DetectReadTest(Bz2Test, DetectReadTest):
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100742 def test_detect_stream_bz2(self):
743 # Originally, tarfile's stream detection looked for the string
744 # "BZh91" at the start of the file. This is incorrect because
745 # the '9' represents the blocksize (900kB). If the file was
746 # compressed using another blocksize autodetection fails.
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100747 with open(tarname, "rb") as fobj:
748 data = fobj.read()
749
750 # Compress with blocksize 100kB, the file starts with "BZh11".
751 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
752 fobj.write(data)
753
754 self._testfunc_file(tmpname, "r|*")
755
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300756class LzmaDetectReadTest(LzmaTest, DetectReadTest):
757 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300759
760class MemberReadTest(ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000761
762 def _test_member(self, tarinfo, chksum=None, **kwargs):
763 if chksum is not None:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300764 with self.tar.extractfile(tarinfo) as f:
765 self.assertEqual(md5sum(f.read()), chksum,
766 "wrong md5sum for %s" % tarinfo.name)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000767
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000768 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000769 kwargs["uid"] = 1000
770 kwargs["gid"] = 100
771 if "old-v7" not in tarinfo.name:
772 # V7 tar can't handle alphabetic owners.
773 kwargs["uname"] = "tarfile"
774 kwargs["gname"] = "tarfile"
775 for k, v in kwargs.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300776 self.assertEqual(getattr(tarinfo, k), v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777 "wrong value in %s field of %s" % (k, tarinfo.name))
778
779 def test_find_regtype(self):
780 tarinfo = self.tar.getmember("ustar/regtype")
781 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
782
783 def test_find_conttype(self):
784 tarinfo = self.tar.getmember("ustar/conttype")
785 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
786
787 def test_find_dirtype(self):
788 tarinfo = self.tar.getmember("ustar/dirtype")
789 self._test_member(tarinfo, size=0)
790
791 def test_find_dirtype_with_size(self):
792 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
793 self._test_member(tarinfo, size=255)
794
795 def test_find_lnktype(self):
796 tarinfo = self.tar.getmember("ustar/lnktype")
797 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
798
799 def test_find_symtype(self):
800 tarinfo = self.tar.getmember("ustar/symtype")
801 self._test_member(tarinfo, size=0, linkname="regtype")
802
803 def test_find_blktype(self):
804 tarinfo = self.tar.getmember("ustar/blktype")
805 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
806
807 def test_find_chrtype(self):
808 tarinfo = self.tar.getmember("ustar/chrtype")
809 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
810
811 def test_find_fifotype(self):
812 tarinfo = self.tar.getmember("ustar/fifotype")
813 self._test_member(tarinfo, size=0)
814
815 def test_find_sparse(self):
816 tarinfo = self.tar.getmember("ustar/sparse")
817 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
818
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000819 def test_find_gnusparse(self):
820 tarinfo = self.tar.getmember("gnu/sparse")
821 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
822
823 def test_find_gnusparse_00(self):
824 tarinfo = self.tar.getmember("gnu/sparse-0.0")
825 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
826
827 def test_find_gnusparse_01(self):
828 tarinfo = self.tar.getmember("gnu/sparse-0.1")
829 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
830
831 def test_find_gnusparse_10(self):
832 tarinfo = self.tar.getmember("gnu/sparse-1.0")
833 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
834
Guido van Rossumd8faa362007-04-27 19:54:29 +0000835 def test_find_umlauts(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300836 tarinfo = self.tar.getmember("ustar/umlauts-"
837 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000838 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
839
840 def test_find_ustar_longname(self):
841 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000842 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000843
844 def test_find_regtype_oldv7(self):
845 tarinfo = self.tar.getmember("misc/regtype-old-v7")
846 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
847
848 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000849 self.tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300850 self.tar = tarfile.open(self.tarname, mode=self.mode,
851 encoding="iso8859-1")
852 tarinfo = self.tar.getmember("pax/umlauts-"
853 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000854 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
855
856
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300857class LongnameTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000858
859 def test_read_longname(self):
860 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000861 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000862 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000863 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000864 except KeyError:
865 self.fail("longname not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300866 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
867 "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000868
869 def test_read_longlink(self):
870 longname = self.subdir + "/" + "123/" * 125 + "longname"
871 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
872 try:
873 tarinfo = self.tar.getmember(longlink)
874 except KeyError:
875 self.fail("longlink not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300876 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000877
878 def test_truncated_longname(self):
879 longname = self.subdir + "/" + "123/" * 125 + "longname"
880 tarinfo = self.tar.getmember(longname)
881 offset = tarinfo.offset
882 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000883 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300884 with self.assertRaises(tarfile.ReadError):
885 tarfile.open(name="foo.tar", fileobj=fobj)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000886
Guido van Rossume7ba4952007-06-06 23:52:48 +0000887 def test_header_offset(self):
888 # Test if the start offset of the TarInfo object includes
889 # the preceding extended header.
890 longname = self.subdir + "/" + "123/" * 125 + "longname"
891 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000892 with open(tarname, "rb") as fobj:
893 fobj.seek(offset)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300894 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
895 "iso8859-1", "strict")
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000896 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000897
Guido van Rossumd8faa362007-04-27 19:54:29 +0000898
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300899class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000900
901 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000902 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000903
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000904 # Since 3.2 tarfile is supposed to accurately restore sparse members and
905 # produce files with holes. This is what we actually want to test here.
906 # Unfortunately, not all platforms/filesystems support sparse files, and
907 # even on platforms that do it is non-trivial to make reliable assertions
908 # about holes in files. Therefore, we first do one basic test which works
909 # an all platforms, and after that a test that will work only on
910 # platforms/filesystems that prove to support sparse files.
911 def _test_sparse_file(self, name):
912 self.tar.extract(name, TEMPDIR)
913 filename = os.path.join(TEMPDIR, name)
914 with open(filename, "rb") as fobj:
915 data = fobj.read()
916 self.assertEqual(md5sum(data), md5_sparse,
917 "wrong md5sum for %s" % name)
918
919 if self._fs_supports_holes():
920 s = os.stat(filename)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300921 self.assertLess(s.st_blocks * 512, s.st_size)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000922
923 def test_sparse_file_old(self):
924 self._test_sparse_file("gnu/sparse")
925
926 def test_sparse_file_00(self):
927 self._test_sparse_file("gnu/sparse-0.0")
928
929 def test_sparse_file_01(self):
930 self._test_sparse_file("gnu/sparse-0.1")
931
932 def test_sparse_file_10(self):
933 self._test_sparse_file("gnu/sparse-1.0")
934
935 @staticmethod
936 def _fs_supports_holes():
937 # Return True if the platform knows the st_blocks stat attribute and
938 # uses st_blocks units of 512 bytes, and if the filesystem is able to
939 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200940 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000941 # Linux evidentially has 512 byte st_blocks units.
942 name = os.path.join(TEMPDIR, "sparse-test")
943 with open(name, "wb") as fobj:
944 fobj.seek(4096)
945 fobj.truncate()
946 s = os.stat(name)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100947 support.unlink(name)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000948 return s.st_blocks == 0
949 else:
950 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951
952
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300953class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000954
955 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000956 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000957
Guido van Rossume7ba4952007-06-06 23:52:48 +0000958 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000959 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000960 try:
961 tarinfo = tar.getmember("pax/regtype1")
962 self.assertEqual(tarinfo.uname, "foo")
963 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300964 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
965 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000966
Antoine Pitrou95f55602010-09-23 18:36:46 +0000967 tarinfo = tar.getmember("pax/regtype2")
968 self.assertEqual(tarinfo.uname, "")
969 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300970 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
971 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972
Antoine Pitrou95f55602010-09-23 18:36:46 +0000973 tarinfo = tar.getmember("pax/regtype3")
974 self.assertEqual(tarinfo.uname, "tarfile")
975 self.assertEqual(tarinfo.gname, "tarfile")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300976 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
977 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000978 finally:
979 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000980
981 def test_pax_number_fields(self):
982 # All following number fields are read from the pax header.
983 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000984 try:
985 tarinfo = tar.getmember("pax/regtype4")
986 self.assertEqual(tarinfo.size, 7011)
987 self.assertEqual(tarinfo.uid, 123)
988 self.assertEqual(tarinfo.gid, 123)
989 self.assertEqual(tarinfo.mtime, 1041808783.0)
990 self.assertEqual(type(tarinfo.mtime), float)
991 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
992 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
993 finally:
994 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000995
996
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300997class WriteTestBase(TarTest):
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000998 # Put all write tests in here that are supposed to be tested
999 # in all possible mode combinations.
1000
1001 def test_fileobj_no_close(self):
1002 fobj = io.BytesIO()
1003 tar = tarfile.open(fileobj=fobj, mode=self.mode)
1004 tar.addfile(tarfile.TarInfo("foo"))
1005 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001006 self.assertFalse(fobj.closed, "external fileobjs must never closed")
Serhiy Storchaka9fbec7a2014-01-18 15:53:05 +02001007 # Issue #20238: Incomplete gzip output with mode="w:gz"
1008 data = fobj.getvalue()
1009 del tar
1010 support.gc_collect()
1011 self.assertFalse(fobj.closed)
1012 self.assertEqual(data, fobj.getvalue())
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001013
Lars Gustäbel20703c62015-05-27 12:53:44 +02001014 def test_eof_marker(self):
1015 # Make sure an end of archive marker is written (two zero blocks).
1016 # tarfile insists on aligning archives to a 20 * 512 byte recordsize.
1017 # So, we create an archive that has exactly 10240 bytes without the
1018 # marker, and has 20480 bytes once the marker is written.
1019 with tarfile.open(tmpname, self.mode) as tar:
1020 t = tarfile.TarInfo("foo")
1021 t.size = tarfile.RECORDSIZE - tarfile.BLOCKSIZE
1022 tar.addfile(t, io.BytesIO(b"a" * t.size))
1023
1024 with self.open(tmpname, "rb") as fobj:
1025 self.assertEqual(len(fobj.read()), tarfile.RECORDSIZE * 2)
1026
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001027
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001028class WriteTest(WriteTestBase, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001030 prefix = "w:"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031
1032 def test_100_char_name(self):
1033 # The name field in a tar header stores strings of at most 100 chars.
1034 # If a string is shorter than 100 chars it has to be padded with '\0',
1035 # which implies that a string of exactly 100 chars is stored without
1036 # a trailing '\0'.
1037 name = "0123456789" * 10
1038 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001039 try:
1040 t = tarfile.TarInfo(name)
1041 tar.addfile(t)
1042 finally:
1043 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +00001044
Guido van Rossumd8faa362007-04-27 19:54:29 +00001045 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001046 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001047 self.assertEqual(tar.getnames()[0], name,
Antoine Pitrou95f55602010-09-23 18:36:46 +00001048 "failed to store 100 char filename")
1049 finally:
1050 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001051
Guido van Rossumd8faa362007-04-27 19:54:29 +00001052 def test_tar_size(self):
1053 # Test for bug #1013882.
1054 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001055 try:
1056 path = os.path.join(TEMPDIR, "file")
1057 with open(path, "wb") as fobj:
1058 fobj.write(b"aaa")
1059 tar.add(path)
1060 finally:
1061 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001062 self.assertGreater(os.path.getsize(tmpname), 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001063 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001064
Guido van Rossumd8faa362007-04-27 19:54:29 +00001065 # The test_*_size tests test for bug #1167128.
1066 def test_file_size(self):
1067 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001068 try:
1069 path = os.path.join(TEMPDIR, "file")
1070 with open(path, "wb"):
1071 pass
1072 tarinfo = tar.gettarinfo(path)
1073 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001074
Antoine Pitrou95f55602010-09-23 18:36:46 +00001075 with open(path, "wb") as fobj:
1076 fobj.write(b"aaa")
1077 tarinfo = tar.gettarinfo(path)
1078 self.assertEqual(tarinfo.size, 3)
1079 finally:
1080 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001081
1082 def test_directory_size(self):
1083 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001084 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001085 try:
1086 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001087 try:
1088 tarinfo = tar.gettarinfo(path)
1089 self.assertEqual(tarinfo.size, 0)
1090 finally:
1091 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001092 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001093 support.rmdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001094
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001095 @unittest.skipUnless(hasattr(os, "link"),
1096 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001097 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001098 link = os.path.join(TEMPDIR, "link")
1099 target = os.path.join(TEMPDIR, "link_target")
1100 with open(target, "wb") as fobj:
1101 fobj.write(b"aaa")
1102 os.link(target, link)
1103 try:
1104 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001105 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001106 # Record the link target in the inodes list.
1107 tar.gettarinfo(target)
1108 tarinfo = tar.gettarinfo(link)
1109 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001110 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001111 tar.close()
1112 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001113 support.unlink(target)
1114 support.unlink(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001115
Brian Curtin3b4499c2010-12-28 14:31:47 +00001116 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +00001117 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +00001118 path = os.path.join(TEMPDIR, "symlink")
1119 os.symlink("link_target", path)
1120 try:
1121 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001122 try:
1123 tarinfo = tar.gettarinfo(path)
1124 self.assertEqual(tarinfo.size, 0)
1125 finally:
1126 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +00001127 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001128 support.unlink(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129
1130 def test_add_self(self):
1131 # Test for #1257255.
1132 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001133 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001134 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001135 self.assertEqual(tar.name, dstname,
1136 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001137 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001138 self.assertEqual(tar.getnames(), [],
1139 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001140
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001141 with support.change_cwd(TEMPDIR):
1142 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001143 self.assertEqual(tar.getnames(), [],
1144 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001145 finally:
1146 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001147
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001148 def test_filter(self):
1149 tempdir = os.path.join(TEMPDIR, "filter")
1150 os.mkdir(tempdir)
1151 try:
1152 for name in ("foo", "bar", "baz"):
1153 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001154 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001155
1156 def filter(tarinfo):
1157 if os.path.basename(tarinfo.name) == "bar":
1158 return
1159 tarinfo.uid = 123
1160 tarinfo.uname = "foo"
1161 return tarinfo
1162
1163 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001164 try:
1165 tar.add(tempdir, arcname="empty_dir", filter=filter)
1166 finally:
1167 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001168
Raymond Hettingera63a3122011-01-26 20:34:14 +00001169 # Verify that filter is a keyword-only argument
1170 with self.assertRaises(TypeError):
1171 tar.add(tempdir, "empty_dir", True, None, filter)
1172
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001173 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001174 try:
1175 for tarinfo in tar:
1176 self.assertEqual(tarinfo.uid, 123)
1177 self.assertEqual(tarinfo.uname, "foo")
1178 self.assertEqual(len(tar.getmembers()), 3)
1179 finally:
1180 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001181 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001182 support.rmtree(tempdir)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001183
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001184 # Guarantee that stored pathnames are not modified. Don't
1185 # remove ./ or ../ or double slashes. Still make absolute
1186 # pathnames relative.
1187 # For details see bug #6054.
1188 def _test_pathname(self, path, cmp_path=None, dir=False):
1189 # Create a tarfile with an empty member named path
1190 # and compare the stored name with the original.
1191 foo = os.path.join(TEMPDIR, "foo")
1192 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001193 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001194 else:
1195 os.mkdir(foo)
1196
1197 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001198 try:
1199 tar.add(foo, arcname=path)
1200 finally:
1201 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001202
1203 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001204 try:
1205 t = tar.next()
1206 finally:
1207 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001208
1209 if not dir:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001210 support.unlink(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001211 else:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001212 support.rmdir(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001213
1214 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1215
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001216
1217 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001218 def test_extractall_symlinks(self):
1219 # Test if extractall works properly when tarfile contains symlinks
1220 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1221 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1222 os.mkdir(tempdir)
1223 try:
1224 source_file = os.path.join(tempdir,'source')
1225 target_file = os.path.join(tempdir,'symlink')
1226 with open(source_file,'w') as f:
1227 f.write('something\n')
1228 os.symlink(source_file, target_file)
1229 tar = tarfile.open(temparchive,'w')
1230 tar.add(source_file)
1231 tar.add(target_file)
1232 tar.close()
1233 # Let's extract it to the location which contains the symlink
1234 tar = tarfile.open(temparchive,'r')
1235 # this should not raise OSError: [Errno 17] File exists
1236 try:
1237 tar.extractall(path=tempdir)
1238 except OSError:
1239 self.fail("extractall failed with symlinked files")
1240 finally:
1241 tar.close()
1242 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001243 support.unlink(temparchive)
1244 support.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001245
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001246 def test_pathnames(self):
1247 self._test_pathname("foo")
1248 self._test_pathname(os.path.join("foo", ".", "bar"))
1249 self._test_pathname(os.path.join("foo", "..", "bar"))
1250 self._test_pathname(os.path.join(".", "foo"))
1251 self._test_pathname(os.path.join(".", "foo", "."))
1252 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1253 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1254 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1255 self._test_pathname(os.path.join("..", "foo"))
1256 self._test_pathname(os.path.join("..", "foo", ".."))
1257 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1258 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1259
1260 self._test_pathname("foo" + os.sep + os.sep + "bar")
1261 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1262
1263 def test_abs_pathnames(self):
1264 if sys.platform == "win32":
1265 self._test_pathname("C:\\foo", "foo")
1266 else:
1267 self._test_pathname("/foo", "foo")
1268 self._test_pathname("///foo", "foo")
1269
1270 def test_cwd(self):
1271 # Test adding the current working directory.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001272 with support.change_cwd(TEMPDIR):
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001273 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001274 try:
1275 tar.add(".")
1276 finally:
1277 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001278
1279 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001280 try:
1281 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001282 if t.name != ".":
1283 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001284 finally:
1285 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001286
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001287 def test_open_nonwritable_fileobj(self):
1288 for exctype in OSError, EOFError, RuntimeError:
1289 class BadFile(io.BytesIO):
1290 first = True
1291 def write(self, data):
1292 if self.first:
1293 self.first = False
1294 raise exctype
1295
1296 f = BadFile()
1297 with self.assertRaises(exctype):
1298 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1299 format=tarfile.PAX_FORMAT,
1300 pax_headers={'non': 'empty'})
1301 self.assertFalse(f.closed)
1302
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001303class GzipWriteTest(GzipTest, WriteTest):
1304 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001305
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001306class Bz2WriteTest(Bz2Test, WriteTest):
1307 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001308
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001309class LzmaWriteTest(LzmaTest, WriteTest):
1310 pass
1311
1312
1313class StreamWriteTest(WriteTestBase, unittest.TestCase):
1314
1315 prefix = "w|"
1316 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001317
Guido van Rossumd8faa362007-04-27 19:54:29 +00001318 def test_stream_padding(self):
1319 # Test for bug #1543303.
1320 tar = tarfile.open(tmpname, self.mode)
1321 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001322 if self.decompressor:
1323 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001324 with open(tmpname, "rb") as fobj:
1325 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001326 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001327 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001328 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001329 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001330 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001331 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1332 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001333
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001334 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1335 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001336 def test_file_mode(self):
1337 # Test for issue #8464: Create files with correct
1338 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001339 if os.path.exists(tmpname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001340 support.unlink(tmpname)
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001341
1342 original_umask = os.umask(0o022)
1343 try:
1344 tar = tarfile.open(tmpname, self.mode)
1345 tar.close()
1346 mode = os.stat(tmpname).st_mode & 0o777
1347 self.assertEqual(mode, 0o644, "wrong file permissions")
1348 finally:
1349 os.umask(original_umask)
1350
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001351class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1352 pass
1353
1354class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1355 decompressor = bz2.BZ2Decompressor if bz2 else None
1356
1357class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1358 decompressor = lzma.LZMADecompressor if lzma else None
1359
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001360
Guido van Rossumd8faa362007-04-27 19:54:29 +00001361class GNUWriteTest(unittest.TestCase):
1362 # This testcase checks for correct creation of GNU Longname
1363 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001364
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001365 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001366 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001367 return blocks * 512
1368
1369 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001370 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001371 count = 512
1372
1373 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001374 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001375 count += 512
1376 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001377 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001378 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001379 count += 512
1380 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001381 return count
1382
1383 def _test(self, name, link=None):
1384 tarinfo = tarfile.TarInfo(name)
1385 if link:
1386 tarinfo.linkname = link
1387 tarinfo.type = tarfile.LNKTYPE
1388
Guido van Rossumd8faa362007-04-27 19:54:29 +00001389 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001390 try:
1391 tar.format = tarfile.GNU_FORMAT
1392 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001393
Antoine Pitrou95f55602010-09-23 18:36:46 +00001394 v1 = self._calc_size(name, link)
1395 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001396 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001397 finally:
1398 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001399
Guido van Rossumd8faa362007-04-27 19:54:29 +00001400 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001401 try:
1402 member = tar.next()
1403 self.assertIsNotNone(member,
1404 "unable to read longname member")
1405 self.assertEqual(tarinfo.name, member.name,
1406 "unable to read longname member")
1407 self.assertEqual(tarinfo.linkname, member.linkname,
1408 "unable to read longname member")
1409 finally:
1410 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001411
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001412 def test_longname_1023(self):
1413 self._test(("longnam/" * 127) + "longnam")
1414
1415 def test_longname_1024(self):
1416 self._test(("longnam/" * 127) + "longname")
1417
1418 def test_longname_1025(self):
1419 self._test(("longnam/" * 127) + "longname_")
1420
1421 def test_longlink_1023(self):
1422 self._test("name", ("longlnk/" * 127) + "longlnk")
1423
1424 def test_longlink_1024(self):
1425 self._test("name", ("longlnk/" * 127) + "longlink")
1426
1427 def test_longlink_1025(self):
1428 self._test("name", ("longlnk/" * 127) + "longlink_")
1429
1430 def test_longnamelink_1023(self):
1431 self._test(("longnam/" * 127) + "longnam",
1432 ("longlnk/" * 127) + "longlnk")
1433
1434 def test_longnamelink_1024(self):
1435 self._test(("longnam/" * 127) + "longname",
1436 ("longlnk/" * 127) + "longlink")
1437
1438 def test_longnamelink_1025(self):
1439 self._test(("longnam/" * 127) + "longname_",
1440 ("longlnk/" * 127) + "longlink_")
1441
Guido van Rossumd8faa362007-04-27 19:54:29 +00001442
Lars Gustäbel20703c62015-05-27 12:53:44 +02001443class CreateTest(WriteTestBase, unittest.TestCase):
Berker Peksag0fe63252015-02-13 21:02:12 +02001444
1445 prefix = "x:"
1446
1447 file_path = os.path.join(TEMPDIR, "spameggs42")
1448
1449 def setUp(self):
1450 support.unlink(tmpname)
1451
1452 @classmethod
1453 def setUpClass(cls):
1454 with open(cls.file_path, "wb") as fobj:
1455 fobj.write(b"aaa")
1456
1457 @classmethod
1458 def tearDownClass(cls):
1459 support.unlink(cls.file_path)
1460
1461 def test_create(self):
1462 with tarfile.open(tmpname, self.mode) as tobj:
1463 tobj.add(self.file_path)
1464
1465 with self.taropen(tmpname) as tobj:
1466 names = tobj.getnames()
1467 self.assertEqual(len(names), 1)
1468 self.assertIn('spameggs42', names[0])
1469
1470 def test_create_existing(self):
1471 with tarfile.open(tmpname, self.mode) as tobj:
1472 tobj.add(self.file_path)
1473
1474 with self.assertRaises(FileExistsError):
1475 tobj = tarfile.open(tmpname, self.mode)
1476
1477 with self.taropen(tmpname) as tobj:
1478 names = tobj.getnames()
1479 self.assertEqual(len(names), 1)
1480 self.assertIn('spameggs42', names[0])
1481
1482 def test_create_taropen(self):
1483 with self.taropen(tmpname, "x") as tobj:
1484 tobj.add(self.file_path)
1485
1486 with self.taropen(tmpname) as tobj:
1487 names = tobj.getnames()
1488 self.assertEqual(len(names), 1)
1489 self.assertIn('spameggs42', names[0])
1490
1491 def test_create_existing_taropen(self):
1492 with self.taropen(tmpname, "x") as tobj:
1493 tobj.add(self.file_path)
1494
1495 with self.assertRaises(FileExistsError):
1496 with self.taropen(tmpname, "x"):
1497 pass
1498
1499 with self.taropen(tmpname) as tobj:
1500 names = tobj.getnames()
1501 self.assertEqual(len(names), 1)
1502 self.assertIn("spameggs42", names[0])
1503
1504
1505class GzipCreateTest(GzipTest, CreateTest):
1506 pass
1507
1508
1509class Bz2CreateTest(Bz2Test, CreateTest):
1510 pass
1511
1512
1513class LzmaCreateTest(LzmaTest, CreateTest):
1514 pass
1515
1516
1517class CreateWithXModeTest(CreateTest):
1518
1519 prefix = "x"
1520
1521 test_create_taropen = None
1522 test_create_existing_taropen = None
1523
1524
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001525@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001526class HardlinkTest(unittest.TestCase):
1527 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001528
1529 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001530 self.foo = os.path.join(TEMPDIR, "foo")
1531 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001532
Antoine Pitrou95f55602010-09-23 18:36:46 +00001533 with open(self.foo, "wb") as fobj:
1534 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001535
Guido van Rossumd8faa362007-04-27 19:54:29 +00001536 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001537
Guido van Rossumd8faa362007-04-27 19:54:29 +00001538 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001539 self.tar.add(self.foo)
1540
Guido van Rossumd8faa362007-04-27 19:54:29 +00001541 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001542 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001543 support.unlink(self.foo)
1544 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001545
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001546 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001547 # The same name will be added as a REGTYPE every
1548 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001549 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001550 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001551 "add file as regular failed")
1552
1553 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001554 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001555 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001556 "add file as hardlink failed")
1557
1558 def test_dereference_hardlink(self):
1559 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001560 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001561 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001562 "dereferencing hardlink failed")
1563
Neal Norwitza4f651a2004-07-20 22:07:44 +00001564
Guido van Rossumd8faa362007-04-27 19:54:29 +00001565class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001566
Guido van Rossumd8faa362007-04-27 19:54:29 +00001567 def _test(self, name, link=None):
1568 # See GNUWriteTest.
1569 tarinfo = tarfile.TarInfo(name)
1570 if link:
1571 tarinfo.linkname = link
1572 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001573
Guido van Rossumd8faa362007-04-27 19:54:29 +00001574 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001575 try:
1576 tar.addfile(tarinfo)
1577 finally:
1578 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001579
Guido van Rossumd8faa362007-04-27 19:54:29 +00001580 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001581 try:
1582 if link:
1583 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001584 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001585 else:
1586 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001587 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001588 finally:
1589 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001590
Guido van Rossume7ba4952007-06-06 23:52:48 +00001591 def test_pax_global_header(self):
1592 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001593 "foo": "bar",
1594 "uid": "0",
1595 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001596 "test": "\xe4\xf6\xfc",
1597 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001598
Benjamin Peterson886af962010-03-21 23:13:07 +00001599 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001600 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001601 try:
1602 tar.addfile(tarfile.TarInfo("test"))
1603 finally:
1604 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001605
1606 # Test if the global header was written correctly.
1607 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001608 try:
1609 self.assertEqual(tar.pax_headers, pax_headers)
1610 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1611 # Test if all the fields are strings.
1612 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001613 self.assertIsNot(type(key), bytes)
1614 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001615 if key in tarfile.PAX_NUMBER_FIELDS:
1616 try:
1617 tarfile.PAX_NUMBER_FIELDS[key](val)
1618 except (TypeError, ValueError):
1619 self.fail("unable to convert pax header field")
1620 finally:
1621 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001622
1623 def test_pax_extended_header(self):
1624 # The fields from the pax header have priority over the
1625 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001626 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001627
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001628 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1629 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001630 try:
1631 t = tarfile.TarInfo()
1632 t.name = "\xe4\xf6\xfc" # non-ASCII
1633 t.uid = 8**8 # too large
1634 t.pax_headers = pax_headers
1635 tar.addfile(t)
1636 finally:
1637 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001638
1639 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001640 try:
1641 t = tar.getmembers()[0]
1642 self.assertEqual(t.pax_headers, pax_headers)
1643 self.assertEqual(t.name, "foo")
1644 self.assertEqual(t.uid, 123)
1645 finally:
1646 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001647
1648
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001649class UnicodeTest:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001650
1651 def test_iso8859_1_filename(self):
1652 self._test_unicode_filename("iso8859-1")
1653
1654 def test_utf7_filename(self):
1655 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001656
1657 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001658 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001659
Guido van Rossumd8faa362007-04-27 19:54:29 +00001660 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001661 tar = tarfile.open(tmpname, "w", format=self.format,
1662 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001663 try:
1664 name = "\xe4\xf6\xfc"
1665 tar.addfile(tarfile.TarInfo(name))
1666 finally:
1667 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001668
1669 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001670 try:
1671 self.assertEqual(tar.getmembers()[0].name, name)
1672 finally:
1673 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001674
1675 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001676 tar = tarfile.open(tmpname, "w", format=self.format,
1677 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001678 try:
1679 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001680
Antoine Pitrou95f55602010-09-23 18:36:46 +00001681 tarinfo.name = "\xe4\xf6\xfc"
1682 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001683
Antoine Pitrou95f55602010-09-23 18:36:46 +00001684 tarinfo.name = "foo"
1685 tarinfo.uname = "\xe4\xf6\xfc"
1686 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1687 finally:
1688 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001689
1690 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001691 tar = tarfile.open(tarname, "r",
1692 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001693 try:
1694 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001695 self.assertIs(type(t.name), str)
1696 self.assertIs(type(t.linkname), str)
1697 self.assertIs(type(t.uname), str)
1698 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001699 finally:
1700 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001701
Guido van Rossume7ba4952007-06-06 23:52:48 +00001702 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001703 t = tarfile.TarInfo("foo")
1704 t.uname = "\xe4\xf6\xfc"
1705 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001706
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001707 tar = tarfile.open(tmpname, mode="w", format=self.format,
1708 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001709 try:
1710 tar.addfile(t)
1711 finally:
1712 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001713
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001714 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001715 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001716 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001717 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1718 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1719
1720 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001721 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001722 tar = tarfile.open(tmpname, encoding="ascii")
1723 t = tar.getmember("foo")
1724 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1725 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1726 finally:
1727 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001728
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001729
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001730class UstarUnicodeTest(UnicodeTest, unittest.TestCase):
1731
1732 format = tarfile.USTAR_FORMAT
1733
1734 # Test whether the utf-8 encoded version of a filename exceeds the 100
1735 # bytes name field limit (every occurrence of '\xff' will be expanded to 2
1736 # bytes).
1737 def test_unicode_name1(self):
1738 self._test_ustar_name("0123456789" * 10)
1739 self._test_ustar_name("0123456789" * 10 + "0", ValueError)
1740 self._test_ustar_name("0123456789" * 9 + "01234567\xff")
1741 self._test_ustar_name("0123456789" * 9 + "012345678\xff", ValueError)
1742
1743 def test_unicode_name2(self):
1744 self._test_ustar_name("0123456789" * 9 + "012345\xff\xff")
1745 self._test_ustar_name("0123456789" * 9 + "0123456\xff\xff", ValueError)
1746
1747 # Test whether the utf-8 encoded version of a filename exceeds the 155
1748 # bytes prefix + '/' + 100 bytes name limit.
1749 def test_unicode_longname1(self):
1750 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 10)
1751 self._test_ustar_name("0123456789" * 15 + "0123/4" + "0123456789" * 10, ValueError)
1752 self._test_ustar_name("0123456789" * 15 + "012\xff/" + "0123456789" * 10)
1753 self._test_ustar_name("0123456789" * 15 + "0123\xff/" + "0123456789" * 10, ValueError)
1754
1755 def test_unicode_longname2(self):
1756 self._test_ustar_name("0123456789" * 15 + "01\xff/2" + "0123456789" * 10, ValueError)
1757 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/" + "0123456789" * 10, ValueError)
1758
1759 def test_unicode_longname3(self):
1760 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/2" + "0123456789" * 10, ValueError)
1761 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "01234567\xff")
1762 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345678\xff", ValueError)
1763
1764 def test_unicode_longname4(self):
1765 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345\xff\xff")
1766 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "0123456\xff\xff", ValueError)
1767
1768 def _test_ustar_name(self, name, exc=None):
1769 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1770 t = tarfile.TarInfo(name)
1771 if exc is None:
1772 tar.addfile(t)
1773 else:
1774 self.assertRaises(exc, tar.addfile, t)
1775
1776 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001777 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001778 for t in tar:
1779 self.assertEqual(name, t.name)
1780 break
1781
1782 # Test the same as above for the 100 bytes link field.
1783 def test_unicode_link1(self):
1784 self._test_ustar_link("0123456789" * 10)
1785 self._test_ustar_link("0123456789" * 10 + "0", ValueError)
1786 self._test_ustar_link("0123456789" * 9 + "01234567\xff")
1787 self._test_ustar_link("0123456789" * 9 + "012345678\xff", ValueError)
1788
1789 def test_unicode_link2(self):
1790 self._test_ustar_link("0123456789" * 9 + "012345\xff\xff")
1791 self._test_ustar_link("0123456789" * 9 + "0123456\xff\xff", ValueError)
1792
1793 def _test_ustar_link(self, name, exc=None):
1794 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1795 t = tarfile.TarInfo("foo")
1796 t.linkname = name
1797 if exc is None:
1798 tar.addfile(t)
1799 else:
1800 self.assertRaises(exc, tar.addfile, t)
1801
1802 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001803 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001804 for t in tar:
1805 self.assertEqual(name, t.linkname)
1806 break
1807
1808
1809class GNUUnicodeTest(UnicodeTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001810
Guido van Rossume7ba4952007-06-06 23:52:48 +00001811 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001812
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001813 def test_bad_pax_header(self):
1814 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1815 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001816 for encoding, name in (
1817 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001818 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001819 with tarfile.open(tarname, encoding=encoding,
1820 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001821 try:
1822 t = tar.getmember(name)
1823 except KeyError:
1824 self.fail("unable to read bad GNU tar pax header")
1825
Guido van Rossumd8faa362007-04-27 19:54:29 +00001826
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001827class PAXUnicodeTest(UnicodeTest, unittest.TestCase):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001828
1829 format = tarfile.PAX_FORMAT
1830
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001831 # PAX_FORMAT ignores encoding in write mode.
1832 test_unicode_filename_error = None
1833
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001834 def test_binary_header(self):
1835 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001836 for encoding, name in (
1837 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001838 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001839 with tarfile.open(tarname, encoding=encoding,
1840 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001841 try:
1842 t = tar.getmember(name)
1843 except KeyError:
1844 self.fail("unable to read POSIX.1-2008 binary header")
1845
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001846
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001847class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001848 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001849
Guido van Rossumd8faa362007-04-27 19:54:29 +00001850 def setUp(self):
1851 self.tarname = tmpname
1852 if os.path.exists(self.tarname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001853 support.unlink(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001854
Guido van Rossumd8faa362007-04-27 19:54:29 +00001855 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001856 with tarfile.open(tarname, encoding="iso8859-1") as src:
1857 t = src.getmember("ustar/regtype")
1858 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001859 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001860 with tarfile.open(self.tarname, mode) as tar:
1861 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001862
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001863 def test_append_compressed(self):
1864 self._create_testtar("w:" + self.suffix)
1865 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1866
1867class AppendTest(AppendTestBase, unittest.TestCase):
1868 test_append_compressed = None
1869
1870 def _add_testfile(self, fileobj=None):
1871 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1872 tar.addfile(tarfile.TarInfo("bar"))
1873
Guido van Rossumd8faa362007-04-27 19:54:29 +00001874 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001875 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1876 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001877
1878 def test_non_existing(self):
1879 self._add_testfile()
1880 self._test()
1881
1882 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001883 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001884 self._add_testfile()
1885 self._test()
1886
1887 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001888 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001889 self._add_testfile(fobj)
1890 fobj.seek(0)
1891 self._test(fileobj=fobj)
1892
1893 def test_fileobj(self):
1894 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001895 with open(self.tarname, "rb") as fobj:
1896 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001897 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001898 self._add_testfile(fobj)
1899 fobj.seek(0)
1900 self._test(names=["foo", "bar"], fileobj=fobj)
1901
1902 def test_existing(self):
1903 self._create_testtar()
1904 self._add_testfile()
1905 self._test(names=["foo", "bar"])
1906
Lars Gustäbel9520a432009-11-22 18:48:49 +00001907 # Append mode is supposed to fail if the tarfile to append to
1908 # does not end with a zero block.
1909 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001910 with open(self.tarname, "wb") as fobj:
1911 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001912 self.assertRaises(tarfile.ReadError, self._add_testfile)
1913
1914 def test_null(self):
1915 self._test_error(b"")
1916
1917 def test_incomplete(self):
1918 self._test_error(b"\0" * 13)
1919
1920 def test_premature_eof(self):
1921 data = tarfile.TarInfo("foo").tobuf()
1922 self._test_error(data)
1923
1924 def test_trailing_garbage(self):
1925 data = tarfile.TarInfo("foo").tobuf()
1926 self._test_error(data + b"\0" * 13)
1927
1928 def test_invalid(self):
1929 self._test_error(b"a" * 512)
1930
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001931class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
1932 pass
1933
1934class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
1935 pass
1936
1937class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
1938 pass
1939
Guido van Rossumd8faa362007-04-27 19:54:29 +00001940
1941class LimitsTest(unittest.TestCase):
1942
1943 def test_ustar_limits(self):
1944 # 100 char name
1945 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001946 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001947
1948 # 101 char name that cannot be stored
1949 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001950 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001951
1952 # 256 char name with a slash at pos 156
1953 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001954 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001955
1956 # 256 char name that cannot be stored
1957 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001958 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001959
1960 # 512 char name
1961 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001962 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001963
1964 # 512 char linkname
1965 tarinfo = tarfile.TarInfo("longlink")
1966 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001967 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001968
1969 # uid > 8 digits
1970 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001971 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001972 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001973
1974 def test_gnu_limits(self):
1975 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001976 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001977
1978 tarinfo = tarfile.TarInfo("longlink")
1979 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001980 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001981
1982 # uid >= 256 ** 7
1983 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001984 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001985 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001986
1987 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001988 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001989 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001990
1991 tarinfo = tarfile.TarInfo("longlink")
1992 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001993 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001994
1995 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001996 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001997 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001998
1999
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002000class MiscTest(unittest.TestCase):
2001
2002 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002003 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
2004 b"foo\0\0\0\0\0")
2005 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
2006 b"foo")
2007 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
2008 "foo")
2009 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
2010 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002011
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002012 def test_read_number_fields(self):
2013 # Issue 13158: Test if GNU tar specific base-256 number fields
2014 # are decoded correctly.
2015 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
2016 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002017 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
2018 0o10000000)
2019 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
2020 0xffffffff)
2021 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
2022 -1)
2023 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
2024 -100)
2025 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
2026 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002027
Lars Gustäbelb7a688b2015-07-02 19:38:38 +02002028 # Issue 24514: Test if empty number fields are converted to zero.
2029 self.assertEqual(tarfile.nti(b"\0"), 0)
2030 self.assertEqual(tarfile.nti(b" \0"), 0)
2031
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002032 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002033 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002034 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002035 self.assertEqual(tarfile.itn(0o10000000),
2036 b"\x80\x00\x00\x00\x00\x20\x00\x00")
2037 self.assertEqual(tarfile.itn(0xffffffff),
2038 b"\x80\x00\x00\x00\xff\xff\xff\xff")
2039 self.assertEqual(tarfile.itn(-1),
2040 b"\xff\xff\xff\xff\xff\xff\xff\xff")
2041 self.assertEqual(tarfile.itn(-100),
2042 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
2043 self.assertEqual(tarfile.itn(-0x100000000000000),
2044 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002045
2046 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002047 with self.assertRaises(ValueError):
2048 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
2049 with self.assertRaises(ValueError):
2050 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
2051 with self.assertRaises(ValueError):
2052 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
2053 with self.assertRaises(ValueError):
2054 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002055
Martin Panter104dcda2016-01-16 06:59:13 +00002056 def test__all__(self):
Martin Panter5318d102016-01-16 11:01:14 +00002057 blacklist = {'version', 'grp', 'pwd', 'symlink_exception',
Martin Panter104dcda2016-01-16 06:59:13 +00002058 'NUL', 'BLOCKSIZE', 'RECORDSIZE', 'GNU_MAGIC',
2059 'POSIX_MAGIC', 'LENGTH_NAME', 'LENGTH_LINK',
2060 'LENGTH_PREFIX', 'REGTYPE', 'AREGTYPE', 'LNKTYPE',
2061 'SYMTYPE', 'CHRTYPE', 'BLKTYPE', 'DIRTYPE', 'FIFOTYPE',
2062 'CONTTYPE', 'GNUTYPE_LONGNAME', 'GNUTYPE_LONGLINK',
2063 'GNUTYPE_SPARSE', 'XHDTYPE', 'XGLTYPE', 'SOLARIS_XHDTYPE',
2064 'SUPPORTED_TYPES', 'REGULAR_TYPES', 'GNU_TYPES',
2065 'PAX_FIELDS', 'PAX_NAME_FIELDS', 'PAX_NUMBER_FIELDS',
2066 'stn', 'nts', 'nti', 'itn', 'calc_chksums', 'copyfileobj',
2067 'filemode',
2068 'EmptyHeaderError', 'TruncatedHeaderError',
2069 'EOFHeaderError', 'InvalidHeaderError',
Serhiy Storchaka2c1d3e32016-01-16 11:05:11 +02002070 'SubsequentHeaderError', 'ExFileObject',
Martin Panter104dcda2016-01-16 06:59:13 +00002071 'main'}
2072 support.check__all__(self, tarfile, blacklist=blacklist)
2073
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002074
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002075class CommandLineTest(unittest.TestCase):
2076
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002077 def tarfilecmd(self, *args, **kwargs):
2078 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
2079 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01002080 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002081
2082 def tarfilecmd_failure(self, *args):
2083 return script_helper.assert_python_failure('-m', 'tarfile', *args)
2084
2085 def make_simple_tarfile(self, tar_name):
2086 files = [support.findfile('tokenize_tests.txt'),
2087 support.findfile('tokenize_tests-no-coding-cookie-'
2088 'and-utf8-bom-sig-only.txt')]
2089 self.addCleanup(support.unlink, tar_name)
2090 with tarfile.open(tar_name, 'w') as tf:
2091 for tardata in files:
2092 tf.add(tardata, arcname=os.path.basename(tardata))
2093
2094 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002095 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002096 for opt in '-t', '--test':
2097 out = self.tarfilecmd(opt, tar_name)
2098 self.assertEqual(out, b'')
2099
2100 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002101 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002102 for opt in '-v', '--verbose':
2103 out = self.tarfilecmd(opt, '-t', tar_name)
2104 self.assertIn(b'is a tar archive.\n', out)
2105
2106 def test_test_command_invalid_file(self):
2107 zipname = support.findfile('zipdir.zip')
2108 rc, out, err = self.tarfilecmd_failure('-t', zipname)
2109 self.assertIn(b' is not a tar archive.', err)
2110 self.assertEqual(out, b'')
2111 self.assertEqual(rc, 1)
2112
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002113 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002114 with self.subTest(tar_name=tar_name):
2115 with open(tar_name, 'rb') as f:
2116 data = f.read()
2117 try:
2118 with open(tmpname, 'wb') as f:
2119 f.write(data[:511])
2120 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
2121 self.assertEqual(out, b'')
2122 self.assertEqual(rc, 1)
2123 finally:
2124 support.unlink(tmpname)
2125
2126 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002127 for tar_name in testtarnames:
2128 with support.captured_stdout() as t:
2129 with tarfile.open(tar_name, 'r') as tf:
2130 tf.list(verbose=False)
2131 expected = t.getvalue().encode('ascii', 'backslashreplace')
2132 for opt in '-l', '--list':
2133 out = self.tarfilecmd(opt, tar_name,
2134 PYTHONIOENCODING='ascii')
2135 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002136
2137 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002138 for tar_name in testtarnames:
2139 with support.captured_stdout() as t:
2140 with tarfile.open(tar_name, 'r') as tf:
2141 tf.list(verbose=True)
2142 expected = t.getvalue().encode('ascii', 'backslashreplace')
2143 for opt in '-v', '--verbose':
2144 out = self.tarfilecmd(opt, '-l', tar_name,
2145 PYTHONIOENCODING='ascii')
2146 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002147
2148 def test_list_command_invalid_file(self):
2149 zipname = support.findfile('zipdir.zip')
2150 rc, out, err = self.tarfilecmd_failure('-l', zipname)
2151 self.assertIn(b' is not a tar archive.', err)
2152 self.assertEqual(out, b'')
2153 self.assertEqual(rc, 1)
2154
2155 def test_create_command(self):
2156 files = [support.findfile('tokenize_tests.txt'),
2157 support.findfile('tokenize_tests-no-coding-cookie-'
2158 'and-utf8-bom-sig-only.txt')]
2159 for opt in '-c', '--create':
2160 try:
2161 out = self.tarfilecmd(opt, tmpname, *files)
2162 self.assertEqual(out, b'')
2163 with tarfile.open(tmpname) as tar:
2164 tar.getmembers()
2165 finally:
2166 support.unlink(tmpname)
2167
2168 def test_create_command_verbose(self):
2169 files = [support.findfile('tokenize_tests.txt'),
2170 support.findfile('tokenize_tests-no-coding-cookie-'
2171 'and-utf8-bom-sig-only.txt')]
2172 for opt in '-v', '--verbose':
2173 try:
2174 out = self.tarfilecmd(opt, '-c', tmpname, *files)
2175 self.assertIn(b' file created.', out)
2176 with tarfile.open(tmpname) as tar:
2177 tar.getmembers()
2178 finally:
2179 support.unlink(tmpname)
2180
2181 def test_create_command_dotless_filename(self):
2182 files = [support.findfile('tokenize_tests.txt')]
2183 try:
2184 out = self.tarfilecmd('-c', dotlessname, *files)
2185 self.assertEqual(out, b'')
2186 with tarfile.open(dotlessname) as tar:
2187 tar.getmembers()
2188 finally:
2189 support.unlink(dotlessname)
2190
2191 def test_create_command_dot_started_filename(self):
2192 tar_name = os.path.join(TEMPDIR, ".testtar")
2193 files = [support.findfile('tokenize_tests.txt')]
2194 try:
2195 out = self.tarfilecmd('-c', tar_name, *files)
2196 self.assertEqual(out, b'')
2197 with tarfile.open(tar_name) as tar:
2198 tar.getmembers()
2199 finally:
2200 support.unlink(tar_name)
2201
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002202 def test_create_command_compressed(self):
2203 files = [support.findfile('tokenize_tests.txt'),
2204 support.findfile('tokenize_tests-no-coding-cookie-'
2205 'and-utf8-bom-sig-only.txt')]
2206 for filetype in (GzipTest, Bz2Test, LzmaTest):
2207 if not filetype.open:
2208 continue
2209 try:
2210 tar_name = tmpname + '.' + filetype.suffix
2211 out = self.tarfilecmd('-c', tar_name, *files)
2212 with filetype.taropen(tar_name) as tar:
2213 tar.getmembers()
2214 finally:
2215 support.unlink(tar_name)
2216
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002217 def test_extract_command(self):
2218 self.make_simple_tarfile(tmpname)
2219 for opt in '-e', '--extract':
2220 try:
2221 with support.temp_cwd(tarextdir):
2222 out = self.tarfilecmd(opt, tmpname)
2223 self.assertEqual(out, b'')
2224 finally:
2225 support.rmtree(tarextdir)
2226
2227 def test_extract_command_verbose(self):
2228 self.make_simple_tarfile(tmpname)
2229 for opt in '-v', '--verbose':
2230 try:
2231 with support.temp_cwd(tarextdir):
2232 out = self.tarfilecmd(opt, '-e', tmpname)
2233 self.assertIn(b' file is extracted.', out)
2234 finally:
2235 support.rmtree(tarextdir)
2236
2237 def test_extract_command_different_directory(self):
2238 self.make_simple_tarfile(tmpname)
2239 try:
2240 with support.temp_cwd(tarextdir):
2241 out = self.tarfilecmd('-e', tmpname, 'spamdir')
2242 self.assertEqual(out, b'')
2243 finally:
2244 support.rmtree(tarextdir)
2245
2246 def test_extract_command_invalid_file(self):
2247 zipname = support.findfile('zipdir.zip')
2248 with support.temp_cwd(tarextdir):
2249 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2250 self.assertIn(b' is not a tar archive.', err)
2251 self.assertEqual(out, b'')
2252 self.assertEqual(rc, 1)
2253
2254
Lars Gustäbel01385812010-03-03 12:08:54 +00002255class ContextManagerTest(unittest.TestCase):
2256
2257 def test_basic(self):
2258 with tarfile.open(tarname) as tar:
2259 self.assertFalse(tar.closed, "closed inside runtime context")
2260 self.assertTrue(tar.closed, "context manager failed")
2261
2262 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002263 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002264 # if the TarFile object is already closed.
2265 tar = tarfile.open(tarname)
2266 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002267 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002268 with tar:
2269 pass
2270
2271 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002272 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002273 with self.assertRaises(Exception) as exc:
2274 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002275 raise OSError
2276 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002277 "wrong exception raised in context manager")
2278 self.assertTrue(tar.closed, "context manager failed")
2279
2280 def test_no_eof(self):
2281 # __exit__() must not write end-of-archive blocks if an
2282 # exception was raised.
2283 try:
2284 with tarfile.open(tmpname, "w") as tar:
2285 raise Exception
2286 except:
2287 pass
2288 self.assertEqual(os.path.getsize(tmpname), 0,
2289 "context manager wrote an end-of-archive block")
2290 self.assertTrue(tar.closed, "context manager failed")
2291
2292 def test_eof(self):
2293 # __exit__() must write end-of-archive blocks, i.e. call
2294 # TarFile.close() if there was no error.
2295 with tarfile.open(tmpname, "w"):
2296 pass
2297 self.assertNotEqual(os.path.getsize(tmpname), 0,
2298 "context manager wrote no end-of-archive block")
2299
2300 def test_fileobj(self):
2301 # Test that __exit__() did not close the external file
2302 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002303 with open(tmpname, "wb") as fobj:
2304 try:
2305 with tarfile.open(fileobj=fobj, mode="w") as tar:
2306 raise Exception
2307 except:
2308 pass
2309 self.assertFalse(fobj.closed, "external file object was closed")
2310 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002311
2312
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002313@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2314class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002315
2316 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002317 # symbolic or hard links tarfile tries to extract these types of members
2318 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002319 def _test_link_extraction(self, name):
2320 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002321 with open(os.path.join(TEMPDIR, name), "rb") as f:
2322 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002323 self.assertEqual(md5sum(data), md5_regtype)
2324
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002325 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002326 @unittest.skipIf(hasattr(os.path, "islink"),
2327 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002328 def test_hardlink_extraction1(self):
2329 self._test_link_extraction("ustar/lnktype")
2330
Brian Curtind40e6f72010-07-08 21:39:08 +00002331 @unittest.skipIf(hasattr(os.path, "islink"),
2332 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002333 def test_hardlink_extraction2(self):
2334 self._test_link_extraction("./ustar/linktest2/lnktype")
2335
Brian Curtin74e45612010-07-09 15:58:59 +00002336 @unittest.skipIf(hasattr(os, "symlink"),
2337 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002338 def test_symlink_extraction1(self):
2339 self._test_link_extraction("ustar/symtype")
2340
Brian Curtin74e45612010-07-09 15:58:59 +00002341 @unittest.skipIf(hasattr(os, "symlink"),
2342 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002343 def test_symlink_extraction2(self):
2344 self._test_link_extraction("./ustar/linktest2/symtype")
2345
2346
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002347class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002348 # Issue5068: The _BZ2Proxy.read() method loops forever
2349 # on an empty or partial bzipped file.
2350
2351 def _test_partial_input(self, mode):
2352 class MyBytesIO(io.BytesIO):
2353 hit_eof = False
2354 def read(self, n):
2355 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002356 raise AssertionError("infinite loop detected in "
2357 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002358 self.hit_eof = self.tell() == len(self.getvalue())
2359 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002360 def seek(self, *args):
2361 self.hit_eof = False
2362 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002363
2364 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2365 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002366 try:
2367 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2368 except tarfile.ReadError:
2369 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002370
2371 def test_partial_input(self):
2372 self._test_partial_input("r")
2373
2374 def test_partial_input_bz2(self):
2375 self._test_partial_input("r:bz2")
2376
2377
Eric V. Smith7a803892015-04-15 10:27:58 -04002378def root_is_uid_gid_0():
2379 try:
2380 import pwd, grp
2381 except ImportError:
2382 return False
2383 if pwd.getpwuid(0)[0] != 'root':
2384 return False
2385 if grp.getgrgid(0)[0] != 'root':
2386 return False
2387 return True
2388
2389
Zachary Waread3e27a2015-05-12 23:57:21 -05002390@unittest.skipUnless(hasattr(os, 'chown'), "missing os.chown")
2391@unittest.skipUnless(hasattr(os, 'geteuid'), "missing os.geteuid")
Eric V. Smith7a803892015-04-15 10:27:58 -04002392class NumericOwnerTest(unittest.TestCase):
2393 # mock the following:
2394 # os.chown: so we can test what's being called
2395 # os.chmod: so the modes are not actually changed. if they are, we can't
2396 # delete the files/directories
2397 # os.geteuid: so we can lie and say we're root (uid = 0)
2398
2399 @staticmethod
2400 def _make_test_archive(filename_1, dirname_1, filename_2):
2401 # the file contents to write
2402 fobj = io.BytesIO(b"content")
2403
2404 # create a tar file with a file, a directory, and a file within that
2405 # directory. Assign various .uid/.gid values to them
2406 items = [(filename_1, 99, 98, tarfile.REGTYPE, fobj),
2407 (dirname_1, 77, 76, tarfile.DIRTYPE, None),
2408 (filename_2, 88, 87, tarfile.REGTYPE, fobj),
2409 ]
2410 with tarfile.open(tmpname, 'w') as tarfl:
2411 for name, uid, gid, typ, contents in items:
2412 t = tarfile.TarInfo(name)
2413 t.uid = uid
2414 t.gid = gid
2415 t.uname = 'root'
2416 t.gname = 'root'
2417 t.type = typ
2418 tarfl.addfile(t, contents)
2419
2420 # return the full pathname to the tar file
2421 return tmpname
2422
2423 @staticmethod
2424 @contextmanager
2425 def _setup_test(mock_geteuid):
2426 mock_geteuid.return_value = 0 # lie and say we're root
2427 fname = 'numeric-owner-testfile'
2428 dirname = 'dir'
2429
2430 # the names we want stored in the tarfile
2431 filename_1 = fname
2432 dirname_1 = dirname
2433 filename_2 = os.path.join(dirname, fname)
2434
2435 # create the tarfile with the contents we're after
2436 tar_filename = NumericOwnerTest._make_test_archive(filename_1,
2437 dirname_1,
2438 filename_2)
2439
2440 # open the tarfile for reading. yield it and the names of the items
2441 # we stored into the file
2442 with tarfile.open(tar_filename) as tarfl:
2443 yield tarfl, filename_1, dirname_1, filename_2
2444
2445 @unittest.mock.patch('os.chown')
2446 @unittest.mock.patch('os.chmod')
2447 @unittest.mock.patch('os.geteuid')
2448 def test_extract_with_numeric_owner(self, mock_geteuid, mock_chmod,
2449 mock_chown):
2450 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _,
2451 filename_2):
2452 tarfl.extract(filename_1, TEMPDIR, numeric_owner=True)
2453 tarfl.extract(filename_2 , TEMPDIR, numeric_owner=True)
2454
2455 # convert to filesystem paths
2456 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2457 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2458
2459 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2460 unittest.mock.call(f_filename_2, 88, 87),
2461 ],
2462 any_order=True)
2463
2464 @unittest.mock.patch('os.chown')
2465 @unittest.mock.patch('os.chmod')
2466 @unittest.mock.patch('os.geteuid')
2467 def test_extractall_with_numeric_owner(self, mock_geteuid, mock_chmod,
2468 mock_chown):
2469 with self._setup_test(mock_geteuid) as (tarfl, filename_1, dirname_1,
2470 filename_2):
2471 tarfl.extractall(TEMPDIR, numeric_owner=True)
2472
2473 # convert to filesystem paths
2474 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2475 f_dirname_1 = os.path.join(TEMPDIR, dirname_1)
2476 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2477
2478 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2479 unittest.mock.call(f_dirname_1, 77, 76),
2480 unittest.mock.call(f_filename_2, 88, 87),
2481 ],
2482 any_order=True)
2483
2484 # this test requires that uid=0 and gid=0 really be named 'root'. that's
2485 # because the uname and gname in the test file are 'root', and extract()
2486 # will look them up using pwd and grp to find their uid and gid, which we
2487 # test here to be 0.
2488 @unittest.skipUnless(root_is_uid_gid_0(),
2489 'uid=0,gid=0 must be named "root"')
2490 @unittest.mock.patch('os.chown')
2491 @unittest.mock.patch('os.chmod')
2492 @unittest.mock.patch('os.geteuid')
2493 def test_extract_without_numeric_owner(self, mock_geteuid, mock_chmod,
2494 mock_chown):
2495 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2496 tarfl.extract(filename_1, TEMPDIR, numeric_owner=False)
2497
2498 # convert to filesystem paths
2499 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2500
2501 mock_chown.assert_called_with(f_filename_1, 0, 0)
2502
2503 @unittest.mock.patch('os.geteuid')
2504 def test_keyword_only(self, mock_geteuid):
2505 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2506 self.assertRaises(TypeError,
2507 tarfl.extract, filename_1, TEMPDIR, False, True)
2508
2509
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002510def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002511 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002512 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002513
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002514 global testtarnames
2515 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002516 with open(tarname, "rb") as fobj:
2517 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002518
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002519 # Create compressed tarfiles.
2520 for c in GzipTest, Bz2Test, LzmaTest:
2521 if c.open:
2522 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002523 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002524 with c.open(c.tarname, "wb") as tar:
2525 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002526
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002527def tearDownModule():
2528 if os.path.exists(TEMPDIR):
Tim Goldene0bd2c52014-05-06 13:24:26 +01002529 support.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002530
Neal Norwitz996acf12003-02-17 14:51:41 +00002531if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002532 unittest.main()