blob: abfb34dfb812d810eba3f116764801c25ea11c99 [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
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00006
7import unittest
Eric V. Smith7a803892015-04-15 10:27:58 -04008import unittest.mock
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00009import tarfile
10
Berker Peksagce643912015-05-06 06:33:17 +030011from test import support
12from test.support import script_helper
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000013
14# Check for our compression modules.
15try:
16 import gzip
Brett Cannon260fbe82013-07-04 18:16:15 -040017except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000018 gzip = None
19try:
20 import bz2
Brett Cannon260fbe82013-07-04 18:16:15 -040021except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000022 bz2 = None
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010023try:
24 import lzma
Brett Cannon260fbe82013-07-04 18:16:15 -040025except ImportError:
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010026 lzma = None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000027
Guido van Rossumd8faa362007-04-27 19:54:29 +000028def md5sum(data):
Guido van Rossuma8add0e2007-05-14 22:03:55 +000029 return md5(data).hexdigest()
Guido van Rossumd8faa362007-04-27 19:54:29 +000030
Antoine Pitrouab58b5f2010-09-23 19:39:35 +000031TEMPDIR = os.path.abspath(support.TESTFN) + "-tardir"
Serhiy Storchakad27b4552013-11-24 01:53:29 +020032tarextdir = TEMPDIR + '-extract-test'
Antoine Pitrou941ee882009-11-11 20:59:38 +000033tarname = support.findfile("testtar.tar")
Guido van Rossumd8faa362007-04-27 19:54:29 +000034gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
35bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010036xzname = os.path.join(TEMPDIR, "testtar.tar.xz")
Guido van Rossumd8faa362007-04-27 19:54:29 +000037tmpname = os.path.join(TEMPDIR, "tmp.tar")
Serhiy Storchakad27b4552013-11-24 01:53:29 +020038dotlessname = os.path.join(TEMPDIR, "testtar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000039
Guido van Rossumd8faa362007-04-27 19:54:29 +000040md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
41md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000042
43
Serhiy Storchaka8b562922013-06-17 15:38:50 +030044class TarTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +000045 tarname = tarname
Serhiy Storchaka8b562922013-06-17 15:38:50 +030046 suffix = ''
47 open = io.FileIO
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020048 taropen = tarfile.TarFile.taropen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030049
50 @property
51 def mode(self):
52 return self.prefix + self.suffix
53
54@support.requires_gzip
55class GzipTest:
56 tarname = gzipname
57 suffix = 'gz'
58 open = gzip.GzipFile if gzip else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020059 taropen = tarfile.TarFile.gzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030060
61@support.requires_bz2
62class Bz2Test:
63 tarname = bz2name
64 suffix = 'bz2'
65 open = bz2.BZ2File if bz2 else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020066 taropen = tarfile.TarFile.bz2open
Serhiy Storchaka8b562922013-06-17 15:38:50 +030067
68@support.requires_lzma
69class LzmaTest:
70 tarname = xzname
71 suffix = 'xz'
72 open = lzma.LZMAFile if lzma else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020073 taropen = tarfile.TarFile.xzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030074
75
76class ReadTest(TarTest):
77
78 prefix = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000079
80 def setUp(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +030081 self.tar = tarfile.open(self.tarname, mode=self.mode,
82 encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000083
84 def tearDown(self):
85 self.tar.close()
86
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000087
Serhiy Storchaka8b562922013-06-17 15:38:50 +030088class UstarReadTest(ReadTest, unittest.TestCase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000089
Guido van Rossumd8faa362007-04-27 19:54:29 +000090 def test_fileobj_regular_file(self):
91 tarinfo = self.tar.getmember("ustar/regtype")
Lars Gustäbel7a919e92012-05-05 18:15:03 +020092 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000093 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +030094 self.assertEqual(len(data), tarinfo.size,
95 "regular file extraction failed")
96 self.assertEqual(md5sum(data), md5_regtype,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000097 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000098
Guido van Rossumd8faa362007-04-27 19:54:29 +000099 def test_fileobj_readlines(self):
100 self.tar.extract("ustar/regtype", TEMPDIR)
101 tarinfo = self.tar.getmember("ustar/regtype")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000102 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
103 lines1 = fobj1.readlines()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000104
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200105 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000106 fobj2 = io.TextIOWrapper(fobj)
107 lines2 = fobj2.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300108 self.assertEqual(lines1, lines2,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000109 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300110 self.assertEqual(len(lines2), 114,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000111 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300112 self.assertEqual(lines2[83],
113 "I will gladly admit that Python is not the fastest "
114 "running scripting language.\n",
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000115 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000116
Guido van Rossumd8faa362007-04-27 19:54:29 +0000117 def test_fileobj_iter(self):
118 self.tar.extract("ustar/regtype", TEMPDIR)
119 tarinfo = self.tar.getmember("ustar/regtype")
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200120 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000121 lines1 = fobj1.readlines()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200122 with self.tar.extractfile(tarinfo) as fobj2:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000123 lines2 = list(io.TextIOWrapper(fobj2))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300124 self.assertEqual(lines1, lines2,
125 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +0000126
Guido van Rossumd8faa362007-04-27 19:54:29 +0000127 def test_fileobj_seek(self):
128 self.tar.extract("ustar/regtype", TEMPDIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000129 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
130 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +0000131
Guido van Rossumd8faa362007-04-27 19:54:29 +0000132 tarinfo = self.tar.getmember("ustar/regtype")
133 fobj = self.tar.extractfile(tarinfo)
134
135 text = fobj.read()
136 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000137 self.assertEqual(0, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000138 "seek() to file's start failed")
139 fobj.seek(2048, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000140 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000141 "seek() to absolute position failed")
142 fobj.seek(-1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000143 self.assertEqual(1024, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000144 "seek() to negative relative position failed")
145 fobj.seek(1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000146 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147 "seek() to positive relative position failed")
148 s = fobj.read(10)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300149 self.assertEqual(s, data[2048:2058],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000150 "read() after seek failed")
151 fobj.seek(0, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000152 self.assertEqual(tarinfo.size, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000153 "seek() to file's end failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300154 self.assertEqual(fobj.read(), b"",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155 "read() at file's end did not return empty string")
156 fobj.seek(-tarinfo.size, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000157 self.assertEqual(0, fobj.tell(),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000158 "relative seek() to file's end failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000159 fobj.seek(512)
160 s1 = fobj.readlines()
161 fobj.seek(512)
162 s2 = fobj.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300163 self.assertEqual(s1, s2,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000164 "readlines() after seek failed")
165 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000166 self.assertEqual(len(fobj.readline()), fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000167 "tell() after readline() failed")
168 fobj.seek(512)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300169 self.assertEqual(len(fobj.readline()) + 512, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000170 "tell() after seek() and readline() failed")
171 fobj.seek(0)
172 line = fobj.readline()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000173 self.assertEqual(fobj.read(), data[len(line):],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000174 "read() after readline() failed")
175 fobj.close()
176
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200177 def test_fileobj_text(self):
178 with self.tar.extractfile("ustar/regtype") as fobj:
179 fobj = io.TextIOWrapper(fobj)
180 data = fobj.read().encode("iso8859-1")
181 self.assertEqual(md5sum(data), md5_regtype)
182 try:
183 fobj.seek(100)
184 except AttributeError:
185 # Issue #13815: seek() complained about a missing
186 # flush() method.
187 self.fail("seeking failed in text mode")
188
Lars Gustäbel1b512722010-06-03 12:45:16 +0000189 # Test if symbolic and hard links are resolved by extractfile(). The
190 # test link members each point to a regular member whose data is
191 # supposed to be exported.
192 def _test_fileobj_link(self, lnktype, regtype):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300193 with self.tar.extractfile(lnktype) as a, \
194 self.tar.extractfile(regtype) as b:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000195 self.assertEqual(a.name, b.name)
Lars Gustäbel1b512722010-06-03 12:45:16 +0000196
197 def test_fileobj_link1(self):
198 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
199
200 def test_fileobj_link2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300201 self._test_fileobj_link("./ustar/linktest2/lnktype",
202 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000203
204 def test_fileobj_symlink1(self):
205 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
206
207 def test_fileobj_symlink2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300208 self._test_fileobj_link("./ustar/linktest2/symtype",
209 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000210
Lars Gustäbel1ef9eda2012-04-24 21:04:40 +0200211 def test_issue14160(self):
212 self._test_fileobj_link("symtype2", "ustar/regtype")
213
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300214class GzipUstarReadTest(GzipTest, UstarReadTest):
215 pass
216
217class Bz2UstarReadTest(Bz2Test, UstarReadTest):
218 pass
219
220class LzmaUstarReadTest(LzmaTest, UstarReadTest):
221 pass
222
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200224class ListTest(ReadTest, unittest.TestCase):
225
226 # Override setUp to use default encoding (UTF-8)
227 def setUp(self):
228 self.tar = tarfile.open(self.tarname, mode=self.mode)
229
230 def test_list(self):
231 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
232 with support.swap_attr(sys, 'stdout', tio):
233 self.tar.list(verbose=False)
234 out = tio.detach().getvalue()
235 self.assertIn(b'ustar/conttype', out)
236 self.assertIn(b'ustar/regtype', out)
237 self.assertIn(b'ustar/lnktype', out)
238 self.assertIn(b'ustar' + (b'/12345' * 40) + b'67/longname', out)
239 self.assertIn(b'./ustar/linktest2/symtype', out)
240 self.assertIn(b'./ustar/linktest2/lnktype', out)
241 # Make sure it puts trailing slash for directory
242 self.assertIn(b'ustar/dirtype/', out)
243 self.assertIn(b'ustar/dirtype-with-size/', out)
244 # Make sure it is able to print unencodable characters
Serhiy Storchaka162c4772014-02-19 18:44:12 +0200245 def conv(b):
246 s = b.decode(self.tar.encoding, 'surrogateescape')
247 return s.encode('ascii', 'backslashreplace')
248 self.assertIn(conv(b'ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
249 self.assertIn(conv(b'misc/regtype-hpux-signed-chksum-'
250 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
251 self.assertIn(conv(b'misc/regtype-old-v7-signed-chksum-'
252 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
253 self.assertIn(conv(b'pax/bad-pax-\xe4\xf6\xfc'), out)
254 self.assertIn(conv(b'pax/hdrcharset-\xe4\xf6\xfc'), out)
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200255 # Make sure it prints files separated by one newline without any
256 # 'ls -l'-like accessories if verbose flag is not being used
257 # ...
258 # ustar/conttype
259 # ustar/regtype
260 # ...
261 self.assertRegex(out, br'ustar/conttype ?\r?\n'
262 br'ustar/regtype ?\r?\n')
263 # Make sure it does not print the source of link without verbose flag
264 self.assertNotIn(b'link to', out)
265 self.assertNotIn(b'->', out)
266
267 def test_list_verbose(self):
268 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
269 with support.swap_attr(sys, 'stdout', tio):
270 self.tar.list(verbose=True)
271 out = tio.detach().getvalue()
272 # Make sure it prints files separated by one newline with 'ls -l'-like
273 # accessories if verbose flag is being used
274 # ...
275 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
276 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
277 # ...
Serhiy Storchaka255493c2014-02-05 20:54:43 +0200278 self.assertRegex(out, (br'\?rw-r--r-- tarfile/tarfile\s+7011 '
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200279 br'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
280 br'ustar/\w+type ?\r?\n') * 2)
281 # Make sure it prints the source of link with verbose flag
282 self.assertIn(b'ustar/symtype -> regtype', out)
283 self.assertIn(b'./ustar/linktest2/symtype -> ../linktest1/regtype', out)
284 self.assertIn(b'./ustar/linktest2/lnktype link to '
285 b'./ustar/linktest1/regtype', out)
286 self.assertIn(b'gnu' + (b'/123' * 125) + b'/longlink link to gnu' +
287 (b'/123' * 125) + b'/longname', out)
288 self.assertIn(b'pax' + (b'/123' * 125) + b'/longlink link to pax' +
289 (b'/123' * 125) + b'/longname', out)
290
Serhiy Storchakaa7eb7462014-08-21 10:01:16 +0300291 def test_list_members(self):
292 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
293 def members(tar):
294 for tarinfo in tar.getmembers():
295 if 'reg' in tarinfo.name:
296 yield tarinfo
297 with support.swap_attr(sys, 'stdout', tio):
298 self.tar.list(verbose=False, members=members(self.tar))
299 out = tio.detach().getvalue()
300 self.assertIn(b'ustar/regtype', out)
301 self.assertNotIn(b'ustar/conttype', out)
302
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200303
304class GzipListTest(GzipTest, ListTest):
305 pass
306
307
308class Bz2ListTest(Bz2Test, ListTest):
309 pass
310
311
312class LzmaListTest(LzmaTest, ListTest):
313 pass
314
315
Lars Gustäbel9520a432009-11-22 18:48:49 +0000316class CommonReadTest(ReadTest):
317
318 def test_empty_tarfile(self):
319 # Test for issue6123: Allow opening empty archives.
320 # This test checks if tarfile.open() is able to open an empty tar
321 # archive successfully. Note that an empty tar archive is not the
322 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000323 with tarfile.open(tmpname, self.mode.replace("r", "w")):
324 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000325 try:
326 tar = tarfile.open(tmpname, self.mode)
327 tar.getnames()
328 except tarfile.ReadError:
329 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000330 else:
331 self.assertListEqual(tar.getmembers(), [])
332 finally:
333 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000334
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200335 def test_non_existent_tarfile(self):
336 # Test for issue11513: prevent non-existent gzipped tarfiles raising
337 # multiple exceptions.
338 with self.assertRaisesRegex(FileNotFoundError, "xxx"):
339 tarfile.open("xxx", self.mode)
340
Lars Gustäbel9520a432009-11-22 18:48:49 +0000341 def test_null_tarfile(self):
342 # Test for issue6123: Allow opening empty archives.
343 # This test guarantees that tarfile.open() does not treat an empty
344 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000345 with open(tmpname, "wb"):
346 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000347 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
348 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
349
350 def test_ignore_zeros(self):
351 # Test TarFile's ignore_zeros option.
Lars Gustäbel9520a432009-11-22 18:48:49 +0000352 for char in (b'\0', b'a'):
353 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
354 # are ignored correctly.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300355 with self.open(tmpname, "w") as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000356 fobj.write(char * 1024)
357 fobj.write(tarfile.TarInfo("foo").tobuf())
Lars Gustäbel9520a432009-11-22 18:48:49 +0000358
359 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000360 try:
361 self.assertListEqual(tar.getnames(), ["foo"],
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300362 "ignore_zeros=True should have skipped the %r-blocks" %
363 char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000364 finally:
365 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000366
Lars Gustäbel03572682015-07-06 09:27:24 +0200367 def test_premature_end_of_archive(self):
368 for size in (512, 600, 1024, 1200):
369 with tarfile.open(tmpname, "w:") as tar:
370 t = tarfile.TarInfo("foo")
371 t.size = 1024
372 tar.addfile(t, io.BytesIO(b"a" * 1024))
373
374 with open(tmpname, "r+b") as fobj:
375 fobj.truncate(size)
376
377 with tarfile.open(tmpname) as tar:
378 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
379 for t in tar:
380 pass
381
382 with tarfile.open(tmpname) as tar:
383 t = tar.next()
384
385 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
386 tar.extract(t, TEMPDIR)
387
388 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
389 tar.extractfile(t).read()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000390
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300391class MiscReadTestBase(CommonReadTest):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300392 def requires_name_attribute(self):
393 pass
394
Thomas Woutersed03b412007-08-28 21:37:11 +0000395 def test_no_name_argument(self):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300396 self.requires_name_attribute()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000397 with open(self.tarname, "rb") as fobj:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300398 self.assertIsInstance(fobj.name, str)
399 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
400 self.assertIsInstance(tar.name, str)
401 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000402
Thomas Woutersed03b412007-08-28 21:37:11 +0000403 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000404 with open(self.tarname, "rb") as fobj:
405 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000406 fobj = io.BytesIO(data)
407 self.assertRaises(AttributeError, getattr, fobj, "name")
408 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300409 self.assertIsNone(tar.name)
Thomas Woutersed03b412007-08-28 21:37:11 +0000410
411 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000412 with open(self.tarname, "rb") as fobj:
413 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000414 fobj = io.BytesIO(data)
415 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000416 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300417 self.assertIsNone(tar.name)
418
419 def test_int_name_attribute(self):
420 # Issue 21044: tarfile.open() should handle fileobj with an integer
421 # 'name' attribute.
422 fd = os.open(self.tarname, os.O_RDONLY)
423 with open(fd, 'rb') as fobj:
424 self.assertIsInstance(fobj.name, int)
425 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
426 self.assertIsNone(tar.name)
427
428 def test_bytes_name_attribute(self):
429 self.requires_name_attribute()
430 tarname = os.fsencode(self.tarname)
431 with open(tarname, 'rb') as fobj:
432 self.assertIsInstance(fobj.name, bytes)
433 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
434 self.assertIsInstance(tar.name, bytes)
435 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Thomas Woutersed03b412007-08-28 21:37:11 +0000436
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +0200437 def test_illegal_mode_arg(self):
438 with open(tmpname, 'wb'):
439 pass
440 with self.assertRaisesRegex(ValueError, 'mode must be '):
441 tar = self.taropen(tmpname, 'q')
442 with self.assertRaisesRegex(ValueError, 'mode must be '):
443 tar = self.taropen(tmpname, 'rw')
444 with self.assertRaisesRegex(ValueError, 'mode must be '):
445 tar = self.taropen(tmpname, '')
446
Christian Heimesd8654cf2007-12-02 15:22:16 +0000447 def test_fileobj_with_offset(self):
448 # Skip the first member and store values from the second member
449 # of the testtar.
450 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000451 try:
452 tar.next()
453 t = tar.next()
454 name = t.name
455 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200456 with tar.extractfile(t) as f:
457 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000458 finally:
459 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000460
461 # Open the testtar and seek to the offset of the second member.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300462 with self.open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000463 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000464
Antoine Pitrou95f55602010-09-23 18:36:46 +0000465 # Test if the tarfile starts with the second member.
466 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
467 t = tar.next()
468 self.assertEqual(t.name, name)
469 # Read to the end of fileobj and test if seeking back to the
470 # beginning works.
471 tar.getmembers()
472 self.assertEqual(tar.extractfile(t).read(), data,
473 "seek back did not work")
474 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000475
Guido van Rossumd8faa362007-04-27 19:54:29 +0000476 def test_fail_comp(self):
477 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000478 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000479 with open(tarname, "rb") as fobj:
480 self.assertRaises(tarfile.ReadError, tarfile.open,
481 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482
483 def test_v7_dirtype(self):
484 # Test old style dirtype member (bug #1336623):
485 # Old V7 tars create directory members using an AREGTYPE
486 # header with a "/" appended to the filename field.
487 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300488 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000489 "v7 dirtype failed")
490
Christian Heimes126d29a2008-02-11 22:57:17 +0000491 def test_xstar_type(self):
492 # The xstar format stores extra atime and ctime fields inside the
493 # space reserved for the prefix field. The prefix field must be
494 # ignored in this case, otherwise it will mess up the name.
495 try:
496 self.tar.getmember("misc/regtype-xstar")
497 except KeyError:
498 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
499
Guido van Rossumd8faa362007-04-27 19:54:29 +0000500 def test_check_members(self):
501 for tarinfo in self.tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300502 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000503 "wrong mtime for %s" % tarinfo.name)
504 if not tarinfo.name.startswith("ustar/"):
505 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300506 self.assertEqual(tarinfo.uname, "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000507 "wrong uname for %s" % tarinfo.name)
508
509 def test_find_members(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300510 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000511 "could not find all members")
512
Brian Curtin74e45612010-07-09 15:58:59 +0000513 @unittest.skipUnless(hasattr(os, "link"),
514 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000515 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000516 def test_extract_hardlink(self):
517 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200518 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000519 tar.extract("ustar/regtype", TEMPDIR)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100520 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000521
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200522 tar.extract("ustar/lnktype", TEMPDIR)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100523 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000524 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
525 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000526 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000527
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200528 tar.extract("ustar/symtype", TEMPDIR)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100529 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000530 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
531 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000532 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000533
Christian Heimesfaf2f632008-01-06 16:59:19 +0000534 def test_extractall(self):
535 # Test if extractall() correctly restores directory permissions
536 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000537 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000538 DIR = os.path.join(TEMPDIR, "extractall")
539 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000540 try:
541 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000542 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000543 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000544 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000545 if sys.platform != "win32":
546 # Win32 has no support for fine grained permissions.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300547 self.assertEqual(tarinfo.mode & 0o777,
548 os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000549 def format_mtime(mtime):
550 if isinstance(mtime, float):
551 return "{} ({})".format(mtime, mtime.hex())
552 else:
553 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000554 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000555 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
556 format_mtime(tarinfo.mtime),
557 format_mtime(file_mtime),
558 path)
559 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000560 finally:
561 tar.close()
Tim Goldene0bd2c52014-05-06 13:24:26 +0100562 support.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000563
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000564 def test_extract_directory(self):
565 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000566 DIR = os.path.join(TEMPDIR, "extractdir")
567 os.mkdir(DIR)
568 try:
569 with tarfile.open(tarname, encoding="iso8859-1") as tar:
570 tarinfo = tar.getmember(dirtype)
571 tar.extract(tarinfo, path=DIR)
572 extracted = os.path.join(DIR, dirtype)
573 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
574 if sys.platform != "win32":
575 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
576 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +0100577 support.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000578
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000579 def test_init_close_fobj(self):
580 # Issue #7341: Close the internal file object in the TarFile
581 # constructor in case of an error. For the test we rely on
582 # the fact that opening an empty file raises a ReadError.
583 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000584 with open(empty, "wb") as fobj:
585 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000586
587 try:
588 tar = object.__new__(tarfile.TarFile)
589 try:
590 tar.__init__(empty)
591 except tarfile.ReadError:
592 self.assertTrue(tar.fileobj.closed)
593 else:
594 self.fail("ReadError not raised")
595 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000596 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000597
Serhiy Storchaka263fab92013-05-09 14:22:26 +0300598 def test_parallel_iteration(self):
599 # Issue #16601: Restarting iteration over tarfile continued
600 # from where it left off.
601 with tarfile.open(self.tarname) as tar:
602 for m1, m2 in zip(tar, tar):
603 self.assertEqual(m1.offset, m2.offset)
604 self.assertEqual(m1.get_info(), m2.get_info())
605
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300606class MiscReadTest(MiscReadTestBase, unittest.TestCase):
607 test_fail_comp = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000608
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300609class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200610 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000611
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300612class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300613 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300614 self.skipTest("BZ2File have no name attribute")
615
616class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300617 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300618 self.skipTest("LZMAFile have no name attribute")
619
620
621class StreamReadTest(CommonReadTest, unittest.TestCase):
622
623 prefix="r|"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000624
Lars Gustäbeldd071042011-02-23 11:42:22 +0000625 def test_read_through(self):
626 # Issue #11224: A poorly designed _FileInFile.read() method
627 # caused seeking errors with stream tar files.
628 for tarinfo in self.tar:
629 if not tarinfo.isreg():
630 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200631 with self.tar.extractfile(tarinfo) as fobj:
632 while True:
633 try:
634 buf = fobj.read(512)
635 except tarfile.StreamError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300636 self.fail("simple read-through using "
637 "TarFile.extractfile() failed")
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200638 if not buf:
639 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000640
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641 def test_fileobj_regular_file(self):
642 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200643 with self.tar.extractfile(tarinfo) as fobj:
644 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300645 self.assertEqual(len(data), tarinfo.size,
646 "regular file extraction failed")
647 self.assertEqual(md5sum(data), md5_regtype,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000648 "regular file extraction failed")
649
650 def test_provoke_stream_error(self):
651 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200652 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
653 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000654
Guido van Rossumd8faa362007-04-27 19:54:29 +0000655 def test_compare_members(self):
656 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000657 try:
658 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000659
Antoine Pitrou95f55602010-09-23 18:36:46 +0000660 while True:
661 t1 = tar1.next()
662 t2 = tar2.next()
663 if t1 is None:
664 break
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300665 self.assertIsNotNone(t2, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000666
Antoine Pitrou95f55602010-09-23 18:36:46 +0000667 if t2.islnk() or t2.issym():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300668 with self.assertRaises(tarfile.StreamError):
669 tar2.extractfile(t2)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000670 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000671
Antoine Pitrou95f55602010-09-23 18:36:46 +0000672 v1 = tar1.extractfile(t1)
673 v2 = tar2.extractfile(t2)
674 if v1 is None:
675 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300676 self.assertIsNotNone(v2, "stream.extractfile() failed")
677 self.assertEqual(v1.read(), v2.read(),
678 "stream extraction failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000679 finally:
680 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000681
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300682class GzipStreamReadTest(GzipTest, StreamReadTest):
683 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000684
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300685class Bz2StreamReadTest(Bz2Test, StreamReadTest):
686 pass
Thomas Wouterscf297e42007-02-23 15:07:44 +0000687
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300688class LzmaStreamReadTest(LzmaTest, StreamReadTest):
689 pass
690
691
692class DetectReadTest(TarTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000693 def _testfunc_file(self, name, mode):
694 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000695 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000696 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000697 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000698 else:
699 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000700
Guido van Rossumd8faa362007-04-27 19:54:29 +0000701 def _testfunc_fileobj(self, name, mode):
702 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000703 with open(name, "rb") as f:
704 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000705 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000706 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000707 else:
708 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000709
710 def _test_modes(self, testfunc):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300711 if self.suffix:
712 with self.assertRaises(tarfile.ReadError):
713 tarfile.open(tarname, mode="r:" + self.suffix)
714 with self.assertRaises(tarfile.ReadError):
715 tarfile.open(tarname, mode="r|" + self.suffix)
716 with self.assertRaises(tarfile.ReadError):
717 tarfile.open(self.tarname, mode="r:")
718 with self.assertRaises(tarfile.ReadError):
719 tarfile.open(self.tarname, mode="r|")
720 testfunc(self.tarname, "r")
721 testfunc(self.tarname, "r:" + self.suffix)
722 testfunc(self.tarname, "r:*")
723 testfunc(self.tarname, "r|" + self.suffix)
724 testfunc(self.tarname, "r|*")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100725
Guido van Rossumd8faa362007-04-27 19:54:29 +0000726 def test_detect_file(self):
727 self._test_modes(self._testfunc_file)
728
729 def test_detect_fileobj(self):
730 self._test_modes(self._testfunc_fileobj)
731
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300732class GzipDetectReadTest(GzipTest, DetectReadTest):
733 pass
734
735class Bz2DetectReadTest(Bz2Test, DetectReadTest):
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100736 def test_detect_stream_bz2(self):
737 # Originally, tarfile's stream detection looked for the string
738 # "BZh91" at the start of the file. This is incorrect because
739 # the '9' represents the blocksize (900kB). If the file was
740 # compressed using another blocksize autodetection fails.
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100741 with open(tarname, "rb") as fobj:
742 data = fobj.read()
743
744 # Compress with blocksize 100kB, the file starts with "BZh11".
745 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
746 fobj.write(data)
747
748 self._testfunc_file(tmpname, "r|*")
749
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300750class LzmaDetectReadTest(LzmaTest, DetectReadTest):
751 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000752
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300753
754class MemberReadTest(ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000755
756 def _test_member(self, tarinfo, chksum=None, **kwargs):
757 if chksum is not None:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300758 with self.tar.extractfile(tarinfo) as f:
759 self.assertEqual(md5sum(f.read()), chksum,
760 "wrong md5sum for %s" % tarinfo.name)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000761
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000762 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763 kwargs["uid"] = 1000
764 kwargs["gid"] = 100
765 if "old-v7" not in tarinfo.name:
766 # V7 tar can't handle alphabetic owners.
767 kwargs["uname"] = "tarfile"
768 kwargs["gname"] = "tarfile"
769 for k, v in kwargs.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300770 self.assertEqual(getattr(tarinfo, k), v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000771 "wrong value in %s field of %s" % (k, tarinfo.name))
772
773 def test_find_regtype(self):
774 tarinfo = self.tar.getmember("ustar/regtype")
775 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
776
777 def test_find_conttype(self):
778 tarinfo = self.tar.getmember("ustar/conttype")
779 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
780
781 def test_find_dirtype(self):
782 tarinfo = self.tar.getmember("ustar/dirtype")
783 self._test_member(tarinfo, size=0)
784
785 def test_find_dirtype_with_size(self):
786 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
787 self._test_member(tarinfo, size=255)
788
789 def test_find_lnktype(self):
790 tarinfo = self.tar.getmember("ustar/lnktype")
791 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
792
793 def test_find_symtype(self):
794 tarinfo = self.tar.getmember("ustar/symtype")
795 self._test_member(tarinfo, size=0, linkname="regtype")
796
797 def test_find_blktype(self):
798 tarinfo = self.tar.getmember("ustar/blktype")
799 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
800
801 def test_find_chrtype(self):
802 tarinfo = self.tar.getmember("ustar/chrtype")
803 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
804
805 def test_find_fifotype(self):
806 tarinfo = self.tar.getmember("ustar/fifotype")
807 self._test_member(tarinfo, size=0)
808
809 def test_find_sparse(self):
810 tarinfo = self.tar.getmember("ustar/sparse")
811 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
812
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000813 def test_find_gnusparse(self):
814 tarinfo = self.tar.getmember("gnu/sparse")
815 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
816
817 def test_find_gnusparse_00(self):
818 tarinfo = self.tar.getmember("gnu/sparse-0.0")
819 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
820
821 def test_find_gnusparse_01(self):
822 tarinfo = self.tar.getmember("gnu/sparse-0.1")
823 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
824
825 def test_find_gnusparse_10(self):
826 tarinfo = self.tar.getmember("gnu/sparse-1.0")
827 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
828
Guido van Rossumd8faa362007-04-27 19:54:29 +0000829 def test_find_umlauts(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300830 tarinfo = self.tar.getmember("ustar/umlauts-"
831 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000832 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
833
834 def test_find_ustar_longname(self):
835 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000836 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000837
838 def test_find_regtype_oldv7(self):
839 tarinfo = self.tar.getmember("misc/regtype-old-v7")
840 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
841
842 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000843 self.tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300844 self.tar = tarfile.open(self.tarname, mode=self.mode,
845 encoding="iso8859-1")
846 tarinfo = self.tar.getmember("pax/umlauts-"
847 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000848 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
849
850
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300851class LongnameTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000852
853 def test_read_longname(self):
854 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000855 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000856 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000857 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000858 except KeyError:
859 self.fail("longname not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300860 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
861 "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000862
863 def test_read_longlink(self):
864 longname = self.subdir + "/" + "123/" * 125 + "longname"
865 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
866 try:
867 tarinfo = self.tar.getmember(longlink)
868 except KeyError:
869 self.fail("longlink not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300870 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000871
872 def test_truncated_longname(self):
873 longname = self.subdir + "/" + "123/" * 125 + "longname"
874 tarinfo = self.tar.getmember(longname)
875 offset = tarinfo.offset
876 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000877 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300878 with self.assertRaises(tarfile.ReadError):
879 tarfile.open(name="foo.tar", fileobj=fobj)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000880
Guido van Rossume7ba4952007-06-06 23:52:48 +0000881 def test_header_offset(self):
882 # Test if the start offset of the TarInfo object includes
883 # the preceding extended header.
884 longname = self.subdir + "/" + "123/" * 125 + "longname"
885 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000886 with open(tarname, "rb") as fobj:
887 fobj.seek(offset)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300888 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
889 "iso8859-1", "strict")
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000890 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000891
Guido van Rossumd8faa362007-04-27 19:54:29 +0000892
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300893class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000894
895 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000896 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000897
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000898 # Since 3.2 tarfile is supposed to accurately restore sparse members and
899 # produce files with holes. This is what we actually want to test here.
900 # Unfortunately, not all platforms/filesystems support sparse files, and
901 # even on platforms that do it is non-trivial to make reliable assertions
902 # about holes in files. Therefore, we first do one basic test which works
903 # an all platforms, and after that a test that will work only on
904 # platforms/filesystems that prove to support sparse files.
905 def _test_sparse_file(self, name):
906 self.tar.extract(name, TEMPDIR)
907 filename = os.path.join(TEMPDIR, name)
908 with open(filename, "rb") as fobj:
909 data = fobj.read()
910 self.assertEqual(md5sum(data), md5_sparse,
911 "wrong md5sum for %s" % name)
912
913 if self._fs_supports_holes():
914 s = os.stat(filename)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300915 self.assertLess(s.st_blocks * 512, s.st_size)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000916
917 def test_sparse_file_old(self):
918 self._test_sparse_file("gnu/sparse")
919
920 def test_sparse_file_00(self):
921 self._test_sparse_file("gnu/sparse-0.0")
922
923 def test_sparse_file_01(self):
924 self._test_sparse_file("gnu/sparse-0.1")
925
926 def test_sparse_file_10(self):
927 self._test_sparse_file("gnu/sparse-1.0")
928
929 @staticmethod
930 def _fs_supports_holes():
931 # Return True if the platform knows the st_blocks stat attribute and
932 # uses st_blocks units of 512 bytes, and if the filesystem is able to
933 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200934 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000935 # Linux evidentially has 512 byte st_blocks units.
936 name = os.path.join(TEMPDIR, "sparse-test")
937 with open(name, "wb") as fobj:
938 fobj.seek(4096)
939 fobj.truncate()
940 s = os.stat(name)
Tim Goldene0bd2c52014-05-06 13:24:26 +0100941 support.unlink(name)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000942 return s.st_blocks == 0
943 else:
944 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000945
946
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300947class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000948
949 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000950 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951
Guido van Rossume7ba4952007-06-06 23:52:48 +0000952 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000953 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000954 try:
955 tarinfo = tar.getmember("pax/regtype1")
956 self.assertEqual(tarinfo.uname, "foo")
957 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300958 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
959 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000960
Antoine Pitrou95f55602010-09-23 18:36:46 +0000961 tarinfo = tar.getmember("pax/regtype2")
962 self.assertEqual(tarinfo.uname, "")
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 Rossumd8faa362007-04-27 19:54:29 +0000966
Antoine Pitrou95f55602010-09-23 18:36:46 +0000967 tarinfo = tar.getmember("pax/regtype3")
968 self.assertEqual(tarinfo.uname, "tarfile")
969 self.assertEqual(tarinfo.gname, "tarfile")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300970 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
971 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000972 finally:
973 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000974
975 def test_pax_number_fields(self):
976 # All following number fields are read from the pax header.
977 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000978 try:
979 tarinfo = tar.getmember("pax/regtype4")
980 self.assertEqual(tarinfo.size, 7011)
981 self.assertEqual(tarinfo.uid, 123)
982 self.assertEqual(tarinfo.gid, 123)
983 self.assertEqual(tarinfo.mtime, 1041808783.0)
984 self.assertEqual(type(tarinfo.mtime), float)
985 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
986 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
987 finally:
988 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000989
990
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300991class WriteTestBase(TarTest):
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000992 # Put all write tests in here that are supposed to be tested
993 # in all possible mode combinations.
994
995 def test_fileobj_no_close(self):
996 fobj = io.BytesIO()
997 tar = tarfile.open(fileobj=fobj, mode=self.mode)
998 tar.addfile(tarfile.TarInfo("foo"))
999 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001000 self.assertFalse(fobj.closed, "external fileobjs must never closed")
Serhiy Storchaka9fbec7a2014-01-18 15:53:05 +02001001 # Issue #20238: Incomplete gzip output with mode="w:gz"
1002 data = fobj.getvalue()
1003 del tar
1004 support.gc_collect()
1005 self.assertFalse(fobj.closed)
1006 self.assertEqual(data, fobj.getvalue())
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001007
Lars Gustäbel20703c62015-05-27 12:53:44 +02001008 def test_eof_marker(self):
1009 # Make sure an end of archive marker is written (two zero blocks).
1010 # tarfile insists on aligning archives to a 20 * 512 byte recordsize.
1011 # So, we create an archive that has exactly 10240 bytes without the
1012 # marker, and has 20480 bytes once the marker is written.
1013 with tarfile.open(tmpname, self.mode) as tar:
1014 t = tarfile.TarInfo("foo")
1015 t.size = tarfile.RECORDSIZE - tarfile.BLOCKSIZE
1016 tar.addfile(t, io.BytesIO(b"a" * t.size))
1017
1018 with self.open(tmpname, "rb") as fobj:
1019 self.assertEqual(len(fobj.read()), tarfile.RECORDSIZE * 2)
1020
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001021
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001022class WriteTest(WriteTestBase, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001023
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001024 prefix = "w:"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001025
1026 def test_100_char_name(self):
1027 # The name field in a tar header stores strings of at most 100 chars.
1028 # If a string is shorter than 100 chars it has to be padded with '\0',
1029 # which implies that a string of exactly 100 chars is stored without
1030 # a trailing '\0'.
1031 name = "0123456789" * 10
1032 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001033 try:
1034 t = tarfile.TarInfo(name)
1035 tar.addfile(t)
1036 finally:
1037 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +00001038
Guido van Rossumd8faa362007-04-27 19:54:29 +00001039 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001040 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001041 self.assertEqual(tar.getnames()[0], name,
Antoine Pitrou95f55602010-09-23 18:36:46 +00001042 "failed to store 100 char filename")
1043 finally:
1044 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001045
Guido van Rossumd8faa362007-04-27 19:54:29 +00001046 def test_tar_size(self):
1047 # Test for bug #1013882.
1048 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001049 try:
1050 path = os.path.join(TEMPDIR, "file")
1051 with open(path, "wb") as fobj:
1052 fobj.write(b"aaa")
1053 tar.add(path)
1054 finally:
1055 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001056 self.assertGreater(os.path.getsize(tmpname), 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001057 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001058
Guido van Rossumd8faa362007-04-27 19:54:29 +00001059 # The test_*_size tests test for bug #1167128.
1060 def test_file_size(self):
1061 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001062 try:
1063 path = os.path.join(TEMPDIR, "file")
1064 with open(path, "wb"):
1065 pass
1066 tarinfo = tar.gettarinfo(path)
1067 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001068
Antoine Pitrou95f55602010-09-23 18:36:46 +00001069 with open(path, "wb") as fobj:
1070 fobj.write(b"aaa")
1071 tarinfo = tar.gettarinfo(path)
1072 self.assertEqual(tarinfo.size, 3)
1073 finally:
1074 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001075
1076 def test_directory_size(self):
1077 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001078 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001079 try:
1080 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001081 try:
1082 tarinfo = tar.gettarinfo(path)
1083 self.assertEqual(tarinfo.size, 0)
1084 finally:
1085 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001086 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001087 support.rmdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001088
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001089 @unittest.skipUnless(hasattr(os, "link"),
1090 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001091 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001092 link = os.path.join(TEMPDIR, "link")
1093 target = os.path.join(TEMPDIR, "link_target")
1094 with open(target, "wb") as fobj:
1095 fobj.write(b"aaa")
1096 os.link(target, link)
1097 try:
1098 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001099 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001100 # Record the link target in the inodes list.
1101 tar.gettarinfo(target)
1102 tarinfo = tar.gettarinfo(link)
1103 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001104 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001105 tar.close()
1106 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001107 support.unlink(target)
1108 support.unlink(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001109
Brian Curtin3b4499c2010-12-28 14:31:47 +00001110 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +00001111 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +00001112 path = os.path.join(TEMPDIR, "symlink")
1113 os.symlink("link_target", path)
1114 try:
1115 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001116 try:
1117 tarinfo = tar.gettarinfo(path)
1118 self.assertEqual(tarinfo.size, 0)
1119 finally:
1120 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +00001121 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001122 support.unlink(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001123
1124 def test_add_self(self):
1125 # Test for #1257255.
1126 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001127 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001128 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001129 self.assertEqual(tar.name, dstname,
1130 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001131 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001132 self.assertEqual(tar.getnames(), [],
1133 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001134
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001135 with support.change_cwd(TEMPDIR):
1136 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001137 self.assertEqual(tar.getnames(), [],
1138 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001139 finally:
1140 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001141
Guido van Rossum486364b2007-06-30 05:01:58 +00001142 def test_exclude(self):
1143 tempdir = os.path.join(TEMPDIR, "exclude")
1144 os.mkdir(tempdir)
1145 try:
1146 for name in ("foo", "bar", "baz"):
1147 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001148 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +00001149
Benjamin Peterson886af962010-03-21 23:13:07 +00001150 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +00001151
1152 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001153 try:
1154 with support.check_warnings(("use the filter argument",
1155 DeprecationWarning)):
1156 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
1157 finally:
1158 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001159
1160 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001161 try:
1162 self.assertEqual(len(tar.getmembers()), 1)
1163 self.assertEqual(tar.getnames()[0], "empty_dir")
1164 finally:
1165 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001166 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001167 support.rmtree(tempdir)
Guido van Rossum486364b2007-06-30 05:01:58 +00001168
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001169 def test_filter(self):
1170 tempdir = os.path.join(TEMPDIR, "filter")
1171 os.mkdir(tempdir)
1172 try:
1173 for name in ("foo", "bar", "baz"):
1174 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001175 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001176
1177 def filter(tarinfo):
1178 if os.path.basename(tarinfo.name) == "bar":
1179 return
1180 tarinfo.uid = 123
1181 tarinfo.uname = "foo"
1182 return tarinfo
1183
1184 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001185 try:
1186 tar.add(tempdir, arcname="empty_dir", filter=filter)
1187 finally:
1188 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001189
Raymond Hettingera63a3122011-01-26 20:34:14 +00001190 # Verify that filter is a keyword-only argument
1191 with self.assertRaises(TypeError):
1192 tar.add(tempdir, "empty_dir", True, None, filter)
1193
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001194 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001195 try:
1196 for tarinfo in tar:
1197 self.assertEqual(tarinfo.uid, 123)
1198 self.assertEqual(tarinfo.uname, "foo")
1199 self.assertEqual(len(tar.getmembers()), 3)
1200 finally:
1201 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001202 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001203 support.rmtree(tempdir)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001204
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001205 # Guarantee that stored pathnames are not modified. Don't
1206 # remove ./ or ../ or double slashes. Still make absolute
1207 # pathnames relative.
1208 # For details see bug #6054.
1209 def _test_pathname(self, path, cmp_path=None, dir=False):
1210 # Create a tarfile with an empty member named path
1211 # and compare the stored name with the original.
1212 foo = os.path.join(TEMPDIR, "foo")
1213 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001214 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001215 else:
1216 os.mkdir(foo)
1217
1218 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001219 try:
1220 tar.add(foo, arcname=path)
1221 finally:
1222 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001223
1224 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001225 try:
1226 t = tar.next()
1227 finally:
1228 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001229
1230 if not dir:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001231 support.unlink(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001232 else:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001233 support.rmdir(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001234
1235 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1236
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001237
1238 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001239 def test_extractall_symlinks(self):
1240 # Test if extractall works properly when tarfile contains symlinks
1241 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1242 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1243 os.mkdir(tempdir)
1244 try:
1245 source_file = os.path.join(tempdir,'source')
1246 target_file = os.path.join(tempdir,'symlink')
1247 with open(source_file,'w') as f:
1248 f.write('something\n')
1249 os.symlink(source_file, target_file)
1250 tar = tarfile.open(temparchive,'w')
1251 tar.add(source_file)
1252 tar.add(target_file)
1253 tar.close()
1254 # Let's extract it to the location which contains the symlink
1255 tar = tarfile.open(temparchive,'r')
1256 # this should not raise OSError: [Errno 17] File exists
1257 try:
1258 tar.extractall(path=tempdir)
1259 except OSError:
1260 self.fail("extractall failed with symlinked files")
1261 finally:
1262 tar.close()
1263 finally:
Tim Goldene0bd2c52014-05-06 13:24:26 +01001264 support.unlink(temparchive)
1265 support.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001266
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001267 def test_pathnames(self):
1268 self._test_pathname("foo")
1269 self._test_pathname(os.path.join("foo", ".", "bar"))
1270 self._test_pathname(os.path.join("foo", "..", "bar"))
1271 self._test_pathname(os.path.join(".", "foo"))
1272 self._test_pathname(os.path.join(".", "foo", "."))
1273 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1274 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1275 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1276 self._test_pathname(os.path.join("..", "foo"))
1277 self._test_pathname(os.path.join("..", "foo", ".."))
1278 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1279 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1280
1281 self._test_pathname("foo" + os.sep + os.sep + "bar")
1282 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1283
1284 def test_abs_pathnames(self):
1285 if sys.platform == "win32":
1286 self._test_pathname("C:\\foo", "foo")
1287 else:
1288 self._test_pathname("/foo", "foo")
1289 self._test_pathname("///foo", "foo")
1290
1291 def test_cwd(self):
1292 # Test adding the current working directory.
Serhiy Storchaka2a23adf2015-09-06 14:13:25 +03001293 with support.change_cwd(TEMPDIR):
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001294 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001295 try:
1296 tar.add(".")
1297 finally:
1298 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001299
1300 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001301 try:
1302 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001303 if t.name != ".":
1304 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001305 finally:
1306 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001307
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001308 def test_open_nonwritable_fileobj(self):
1309 for exctype in OSError, EOFError, RuntimeError:
1310 class BadFile(io.BytesIO):
1311 first = True
1312 def write(self, data):
1313 if self.first:
1314 self.first = False
1315 raise exctype
1316
1317 f = BadFile()
1318 with self.assertRaises(exctype):
1319 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1320 format=tarfile.PAX_FORMAT,
1321 pax_headers={'non': 'empty'})
1322 self.assertFalse(f.closed)
1323
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001324class GzipWriteTest(GzipTest, WriteTest):
1325 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001326
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001327class Bz2WriteTest(Bz2Test, WriteTest):
1328 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001329
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001330class LzmaWriteTest(LzmaTest, WriteTest):
1331 pass
1332
1333
1334class StreamWriteTest(WriteTestBase, unittest.TestCase):
1335
1336 prefix = "w|"
1337 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001338
Guido van Rossumd8faa362007-04-27 19:54:29 +00001339 def test_stream_padding(self):
1340 # Test for bug #1543303.
1341 tar = tarfile.open(tmpname, self.mode)
1342 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001343 if self.decompressor:
1344 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001345 with open(tmpname, "rb") as fobj:
1346 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001347 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001348 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001349 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001350 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001351 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001352 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1353 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001354
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001355 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1356 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001357 def test_file_mode(self):
1358 # Test for issue #8464: Create files with correct
1359 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001360 if os.path.exists(tmpname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001361 support.unlink(tmpname)
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001362
1363 original_umask = os.umask(0o022)
1364 try:
1365 tar = tarfile.open(tmpname, self.mode)
1366 tar.close()
1367 mode = os.stat(tmpname).st_mode & 0o777
1368 self.assertEqual(mode, 0o644, "wrong file permissions")
1369 finally:
1370 os.umask(original_umask)
1371
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001372class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1373 pass
1374
1375class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1376 decompressor = bz2.BZ2Decompressor if bz2 else None
1377
1378class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1379 decompressor = lzma.LZMADecompressor if lzma else None
1380
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001381
Guido van Rossumd8faa362007-04-27 19:54:29 +00001382class GNUWriteTest(unittest.TestCase):
1383 # This testcase checks for correct creation of GNU Longname
1384 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001385
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001386 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001387 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001388 return blocks * 512
1389
1390 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001391 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001392 count = 512
1393
1394 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001395 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001396 count += 512
1397 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001398 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001399 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001400 count += 512
1401 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001402 return count
1403
1404 def _test(self, name, link=None):
1405 tarinfo = tarfile.TarInfo(name)
1406 if link:
1407 tarinfo.linkname = link
1408 tarinfo.type = tarfile.LNKTYPE
1409
Guido van Rossumd8faa362007-04-27 19:54:29 +00001410 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001411 try:
1412 tar.format = tarfile.GNU_FORMAT
1413 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001414
Antoine Pitrou95f55602010-09-23 18:36:46 +00001415 v1 = self._calc_size(name, link)
1416 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001417 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001418 finally:
1419 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001420
Guido van Rossumd8faa362007-04-27 19:54:29 +00001421 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001422 try:
1423 member = tar.next()
1424 self.assertIsNotNone(member,
1425 "unable to read longname member")
1426 self.assertEqual(tarinfo.name, member.name,
1427 "unable to read longname member")
1428 self.assertEqual(tarinfo.linkname, member.linkname,
1429 "unable to read longname member")
1430 finally:
1431 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001432
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001433 def test_longname_1023(self):
1434 self._test(("longnam/" * 127) + "longnam")
1435
1436 def test_longname_1024(self):
1437 self._test(("longnam/" * 127) + "longname")
1438
1439 def test_longname_1025(self):
1440 self._test(("longnam/" * 127) + "longname_")
1441
1442 def test_longlink_1023(self):
1443 self._test("name", ("longlnk/" * 127) + "longlnk")
1444
1445 def test_longlink_1024(self):
1446 self._test("name", ("longlnk/" * 127) + "longlink")
1447
1448 def test_longlink_1025(self):
1449 self._test("name", ("longlnk/" * 127) + "longlink_")
1450
1451 def test_longnamelink_1023(self):
1452 self._test(("longnam/" * 127) + "longnam",
1453 ("longlnk/" * 127) + "longlnk")
1454
1455 def test_longnamelink_1024(self):
1456 self._test(("longnam/" * 127) + "longname",
1457 ("longlnk/" * 127) + "longlink")
1458
1459 def test_longnamelink_1025(self):
1460 self._test(("longnam/" * 127) + "longname_",
1461 ("longlnk/" * 127) + "longlink_")
1462
Guido van Rossumd8faa362007-04-27 19:54:29 +00001463
Lars Gustäbel20703c62015-05-27 12:53:44 +02001464class CreateTest(WriteTestBase, unittest.TestCase):
Berker Peksag0fe63252015-02-13 21:02:12 +02001465
1466 prefix = "x:"
1467
1468 file_path = os.path.join(TEMPDIR, "spameggs42")
1469
1470 def setUp(self):
1471 support.unlink(tmpname)
1472
1473 @classmethod
1474 def setUpClass(cls):
1475 with open(cls.file_path, "wb") as fobj:
1476 fobj.write(b"aaa")
1477
1478 @classmethod
1479 def tearDownClass(cls):
1480 support.unlink(cls.file_path)
1481
1482 def test_create(self):
1483 with tarfile.open(tmpname, self.mode) 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(self):
1492 with tarfile.open(tmpname, self.mode) as tobj:
1493 tobj.add(self.file_path)
1494
1495 with self.assertRaises(FileExistsError):
1496 tobj = tarfile.open(tmpname, self.mode)
1497
1498 with self.taropen(tmpname) as tobj:
1499 names = tobj.getnames()
1500 self.assertEqual(len(names), 1)
1501 self.assertIn('spameggs42', names[0])
1502
1503 def test_create_taropen(self):
1504 with self.taropen(tmpname, "x") as tobj:
1505 tobj.add(self.file_path)
1506
1507 with self.taropen(tmpname) as tobj:
1508 names = tobj.getnames()
1509 self.assertEqual(len(names), 1)
1510 self.assertIn('spameggs42', names[0])
1511
1512 def test_create_existing_taropen(self):
1513 with self.taropen(tmpname, "x") as tobj:
1514 tobj.add(self.file_path)
1515
1516 with self.assertRaises(FileExistsError):
1517 with self.taropen(tmpname, "x"):
1518 pass
1519
1520 with self.taropen(tmpname) as tobj:
1521 names = tobj.getnames()
1522 self.assertEqual(len(names), 1)
1523 self.assertIn("spameggs42", names[0])
1524
1525
1526class GzipCreateTest(GzipTest, CreateTest):
1527 pass
1528
1529
1530class Bz2CreateTest(Bz2Test, CreateTest):
1531 pass
1532
1533
1534class LzmaCreateTest(LzmaTest, CreateTest):
1535 pass
1536
1537
1538class CreateWithXModeTest(CreateTest):
1539
1540 prefix = "x"
1541
1542 test_create_taropen = None
1543 test_create_existing_taropen = None
1544
1545
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001546@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001547class HardlinkTest(unittest.TestCase):
1548 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001549
1550 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001551 self.foo = os.path.join(TEMPDIR, "foo")
1552 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001553
Antoine Pitrou95f55602010-09-23 18:36:46 +00001554 with open(self.foo, "wb") as fobj:
1555 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001556
Guido van Rossumd8faa362007-04-27 19:54:29 +00001557 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001558
Guido van Rossumd8faa362007-04-27 19:54:29 +00001559 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001560 self.tar.add(self.foo)
1561
Guido van Rossumd8faa362007-04-27 19:54:29 +00001562 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001563 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001564 support.unlink(self.foo)
1565 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001566
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001567 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001568 # The same name will be added as a REGTYPE every
1569 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001570 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001571 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001572 "add file as regular failed")
1573
1574 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001575 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001576 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001577 "add file as hardlink failed")
1578
1579 def test_dereference_hardlink(self):
1580 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001581 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001582 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001583 "dereferencing hardlink failed")
1584
Neal Norwitza4f651a2004-07-20 22:07:44 +00001585
Guido van Rossumd8faa362007-04-27 19:54:29 +00001586class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001587
Guido van Rossumd8faa362007-04-27 19:54:29 +00001588 def _test(self, name, link=None):
1589 # See GNUWriteTest.
1590 tarinfo = tarfile.TarInfo(name)
1591 if link:
1592 tarinfo.linkname = link
1593 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001594
Guido van Rossumd8faa362007-04-27 19:54:29 +00001595 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001596 try:
1597 tar.addfile(tarinfo)
1598 finally:
1599 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001600
Guido van Rossumd8faa362007-04-27 19:54:29 +00001601 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001602 try:
1603 if link:
1604 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001605 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001606 else:
1607 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001608 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001609 finally:
1610 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001611
Guido van Rossume7ba4952007-06-06 23:52:48 +00001612 def test_pax_global_header(self):
1613 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001614 "foo": "bar",
1615 "uid": "0",
1616 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001617 "test": "\xe4\xf6\xfc",
1618 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001619
Benjamin Peterson886af962010-03-21 23:13:07 +00001620 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001621 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001622 try:
1623 tar.addfile(tarfile.TarInfo("test"))
1624 finally:
1625 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001626
1627 # Test if the global header was written correctly.
1628 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001629 try:
1630 self.assertEqual(tar.pax_headers, pax_headers)
1631 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1632 # Test if all the fields are strings.
1633 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001634 self.assertIsNot(type(key), bytes)
1635 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001636 if key in tarfile.PAX_NUMBER_FIELDS:
1637 try:
1638 tarfile.PAX_NUMBER_FIELDS[key](val)
1639 except (TypeError, ValueError):
1640 self.fail("unable to convert pax header field")
1641 finally:
1642 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001643
1644 def test_pax_extended_header(self):
1645 # The fields from the pax header have priority over the
1646 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001647 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001648
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001649 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1650 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001651 try:
1652 t = tarfile.TarInfo()
1653 t.name = "\xe4\xf6\xfc" # non-ASCII
1654 t.uid = 8**8 # too large
1655 t.pax_headers = pax_headers
1656 tar.addfile(t)
1657 finally:
1658 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001659
1660 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001661 try:
1662 t = tar.getmembers()[0]
1663 self.assertEqual(t.pax_headers, pax_headers)
1664 self.assertEqual(t.name, "foo")
1665 self.assertEqual(t.uid, 123)
1666 finally:
1667 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001668
1669
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001670class UnicodeTest:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001671
1672 def test_iso8859_1_filename(self):
1673 self._test_unicode_filename("iso8859-1")
1674
1675 def test_utf7_filename(self):
1676 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001677
1678 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001679 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001680
Guido van Rossumd8faa362007-04-27 19:54:29 +00001681 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001682 tar = tarfile.open(tmpname, "w", format=self.format,
1683 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001684 try:
1685 name = "\xe4\xf6\xfc"
1686 tar.addfile(tarfile.TarInfo(name))
1687 finally:
1688 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001689
1690 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001691 try:
1692 self.assertEqual(tar.getmembers()[0].name, name)
1693 finally:
1694 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001695
1696 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001697 tar = tarfile.open(tmpname, "w", format=self.format,
1698 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001699 try:
1700 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001701
Antoine Pitrou95f55602010-09-23 18:36:46 +00001702 tarinfo.name = "\xe4\xf6\xfc"
1703 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001704
Antoine Pitrou95f55602010-09-23 18:36:46 +00001705 tarinfo.name = "foo"
1706 tarinfo.uname = "\xe4\xf6\xfc"
1707 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1708 finally:
1709 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001710
1711 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001712 tar = tarfile.open(tarname, "r",
1713 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001714 try:
1715 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001716 self.assertIs(type(t.name), str)
1717 self.assertIs(type(t.linkname), str)
1718 self.assertIs(type(t.uname), str)
1719 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001720 finally:
1721 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001722
Guido van Rossume7ba4952007-06-06 23:52:48 +00001723 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001724 t = tarfile.TarInfo("foo")
1725 t.uname = "\xe4\xf6\xfc"
1726 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001727
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001728 tar = tarfile.open(tmpname, mode="w", format=self.format,
1729 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001730 try:
1731 tar.addfile(t)
1732 finally:
1733 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001734
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001735 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001736 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001737 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001738 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1739 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1740
1741 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001742 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001743 tar = tarfile.open(tmpname, encoding="ascii")
1744 t = tar.getmember("foo")
1745 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1746 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1747 finally:
1748 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001749
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001750
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001751class UstarUnicodeTest(UnicodeTest, unittest.TestCase):
1752
1753 format = tarfile.USTAR_FORMAT
1754
1755 # Test whether the utf-8 encoded version of a filename exceeds the 100
1756 # bytes name field limit (every occurrence of '\xff' will be expanded to 2
1757 # bytes).
1758 def test_unicode_name1(self):
1759 self._test_ustar_name("0123456789" * 10)
1760 self._test_ustar_name("0123456789" * 10 + "0", ValueError)
1761 self._test_ustar_name("0123456789" * 9 + "01234567\xff")
1762 self._test_ustar_name("0123456789" * 9 + "012345678\xff", ValueError)
1763
1764 def test_unicode_name2(self):
1765 self._test_ustar_name("0123456789" * 9 + "012345\xff\xff")
1766 self._test_ustar_name("0123456789" * 9 + "0123456\xff\xff", ValueError)
1767
1768 # Test whether the utf-8 encoded version of a filename exceeds the 155
1769 # bytes prefix + '/' + 100 bytes name limit.
1770 def test_unicode_longname1(self):
1771 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 10)
1772 self._test_ustar_name("0123456789" * 15 + "0123/4" + "0123456789" * 10, ValueError)
1773 self._test_ustar_name("0123456789" * 15 + "012\xff/" + "0123456789" * 10)
1774 self._test_ustar_name("0123456789" * 15 + "0123\xff/" + "0123456789" * 10, ValueError)
1775
1776 def test_unicode_longname2(self):
1777 self._test_ustar_name("0123456789" * 15 + "01\xff/2" + "0123456789" * 10, ValueError)
1778 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/" + "0123456789" * 10, ValueError)
1779
1780 def test_unicode_longname3(self):
1781 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/2" + "0123456789" * 10, ValueError)
1782 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "01234567\xff")
1783 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345678\xff", ValueError)
1784
1785 def test_unicode_longname4(self):
1786 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345\xff\xff")
1787 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "0123456\xff\xff", ValueError)
1788
1789 def _test_ustar_name(self, name, exc=None):
1790 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1791 t = tarfile.TarInfo(name)
1792 if exc is None:
1793 tar.addfile(t)
1794 else:
1795 self.assertRaises(exc, tar.addfile, t)
1796
1797 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001798 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001799 for t in tar:
1800 self.assertEqual(name, t.name)
1801 break
1802
1803 # Test the same as above for the 100 bytes link field.
1804 def test_unicode_link1(self):
1805 self._test_ustar_link("0123456789" * 10)
1806 self._test_ustar_link("0123456789" * 10 + "0", ValueError)
1807 self._test_ustar_link("0123456789" * 9 + "01234567\xff")
1808 self._test_ustar_link("0123456789" * 9 + "012345678\xff", ValueError)
1809
1810 def test_unicode_link2(self):
1811 self._test_ustar_link("0123456789" * 9 + "012345\xff\xff")
1812 self._test_ustar_link("0123456789" * 9 + "0123456\xff\xff", ValueError)
1813
1814 def _test_ustar_link(self, name, exc=None):
1815 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
1816 t = tarfile.TarInfo("foo")
1817 t.linkname = name
1818 if exc is None:
1819 tar.addfile(t)
1820 else:
1821 self.assertRaises(exc, tar.addfile, t)
1822
1823 if exc is None:
Lars Gustäbelddd99172016-04-19 11:58:41 +02001824 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001825 for t in tar:
1826 self.assertEqual(name, t.linkname)
1827 break
1828
1829
1830class GNUUnicodeTest(UnicodeTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001831
Guido van Rossume7ba4952007-06-06 23:52:48 +00001832 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001833
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001834 def test_bad_pax_header(self):
1835 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1836 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001837 for encoding, name in (
1838 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001839 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001840 with tarfile.open(tarname, encoding=encoding,
1841 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001842 try:
1843 t = tar.getmember(name)
1844 except KeyError:
1845 self.fail("unable to read bad GNU tar pax header")
1846
Guido van Rossumd8faa362007-04-27 19:54:29 +00001847
Lars Gustäbel0f450ab2016-04-19 08:43:17 +02001848class PAXUnicodeTest(UnicodeTest, unittest.TestCase):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001849
1850 format = tarfile.PAX_FORMAT
1851
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001852 # PAX_FORMAT ignores encoding in write mode.
1853 test_unicode_filename_error = None
1854
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001855 def test_binary_header(self):
1856 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001857 for encoding, name in (
1858 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001859 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001860 with tarfile.open(tarname, encoding=encoding,
1861 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001862 try:
1863 t = tar.getmember(name)
1864 except KeyError:
1865 self.fail("unable to read POSIX.1-2008 binary header")
1866
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001867
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001868class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001869 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001870
Guido van Rossumd8faa362007-04-27 19:54:29 +00001871 def setUp(self):
1872 self.tarname = tmpname
1873 if os.path.exists(self.tarname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001874 support.unlink(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001875
Guido van Rossumd8faa362007-04-27 19:54:29 +00001876 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001877 with tarfile.open(tarname, encoding="iso8859-1") as src:
1878 t = src.getmember("ustar/regtype")
1879 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001880 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001881 with tarfile.open(self.tarname, mode) as tar:
1882 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001883
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001884 def test_append_compressed(self):
1885 self._create_testtar("w:" + self.suffix)
1886 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1887
1888class AppendTest(AppendTestBase, unittest.TestCase):
1889 test_append_compressed = None
1890
1891 def _add_testfile(self, fileobj=None):
1892 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1893 tar.addfile(tarfile.TarInfo("bar"))
1894
Guido van Rossumd8faa362007-04-27 19:54:29 +00001895 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001896 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1897 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001898
1899 def test_non_existing(self):
1900 self._add_testfile()
1901 self._test()
1902
1903 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001904 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001905 self._add_testfile()
1906 self._test()
1907
1908 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001909 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001910 self._add_testfile(fobj)
1911 fobj.seek(0)
1912 self._test(fileobj=fobj)
1913
1914 def test_fileobj(self):
1915 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001916 with open(self.tarname, "rb") as fobj:
1917 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001918 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001919 self._add_testfile(fobj)
1920 fobj.seek(0)
1921 self._test(names=["foo", "bar"], fileobj=fobj)
1922
1923 def test_existing(self):
1924 self._create_testtar()
1925 self._add_testfile()
1926 self._test(names=["foo", "bar"])
1927
Lars Gustäbel9520a432009-11-22 18:48:49 +00001928 # Append mode is supposed to fail if the tarfile to append to
1929 # does not end with a zero block.
1930 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001931 with open(self.tarname, "wb") as fobj:
1932 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001933 self.assertRaises(tarfile.ReadError, self._add_testfile)
1934
1935 def test_null(self):
1936 self._test_error(b"")
1937
1938 def test_incomplete(self):
1939 self._test_error(b"\0" * 13)
1940
1941 def test_premature_eof(self):
1942 data = tarfile.TarInfo("foo").tobuf()
1943 self._test_error(data)
1944
1945 def test_trailing_garbage(self):
1946 data = tarfile.TarInfo("foo").tobuf()
1947 self._test_error(data + b"\0" * 13)
1948
1949 def test_invalid(self):
1950 self._test_error(b"a" * 512)
1951
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001952class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
1953 pass
1954
1955class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
1956 pass
1957
1958class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
1959 pass
1960
Guido van Rossumd8faa362007-04-27 19:54:29 +00001961
1962class LimitsTest(unittest.TestCase):
1963
1964 def test_ustar_limits(self):
1965 # 100 char name
1966 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001967 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001968
1969 # 101 char name that cannot be stored
1970 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001971 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001972
1973 # 256 char name with a slash at pos 156
1974 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001975 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001976
1977 # 256 char name that cannot be stored
1978 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001979 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001980
1981 # 512 char name
1982 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001983 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001984
1985 # 512 char linkname
1986 tarinfo = tarfile.TarInfo("longlink")
1987 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001988 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001989
1990 # uid > 8 digits
1991 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001992 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001993 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001994
1995 def test_gnu_limits(self):
1996 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001997 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001998
1999 tarinfo = tarfile.TarInfo("longlink")
2000 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002001 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002002
2003 # uid >= 256 ** 7
2004 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002005 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002006 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002007
2008 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002009 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00002010 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002011
2012 tarinfo = tarfile.TarInfo("longlink")
2013 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00002014 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002015
2016 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002017 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00002018 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002019
2020
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002021class MiscTest(unittest.TestCase):
2022
2023 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002024 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
2025 b"foo\0\0\0\0\0")
2026 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
2027 b"foo")
2028 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
2029 "foo")
2030 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
2031 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002032
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002033 def test_read_number_fields(self):
2034 # Issue 13158: Test if GNU tar specific base-256 number fields
2035 # are decoded correctly.
2036 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
2037 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002038 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
2039 0o10000000)
2040 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
2041 0xffffffff)
2042 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
2043 -1)
2044 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
2045 -100)
2046 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
2047 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002048
Lars Gustäbelb7a688b2015-07-02 19:38:38 +02002049 # Issue 24514: Test if empty number fields are converted to zero.
2050 self.assertEqual(tarfile.nti(b"\0"), 0)
2051 self.assertEqual(tarfile.nti(b" \0"), 0)
2052
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002053 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002054 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002055 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002056 self.assertEqual(tarfile.itn(0o10000000),
2057 b"\x80\x00\x00\x00\x00\x20\x00\x00")
2058 self.assertEqual(tarfile.itn(0xffffffff),
2059 b"\x80\x00\x00\x00\xff\xff\xff\xff")
2060 self.assertEqual(tarfile.itn(-1),
2061 b"\xff\xff\xff\xff\xff\xff\xff\xff")
2062 self.assertEqual(tarfile.itn(-100),
2063 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
2064 self.assertEqual(tarfile.itn(-0x100000000000000),
2065 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02002066
2067 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002068 with self.assertRaises(ValueError):
2069 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
2070 with self.assertRaises(ValueError):
2071 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
2072 with self.assertRaises(ValueError):
2073 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
2074 with self.assertRaises(ValueError):
2075 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002076
2077
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002078class CommandLineTest(unittest.TestCase):
2079
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002080 def tarfilecmd(self, *args, **kwargs):
2081 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
2082 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01002083 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002084
2085 def tarfilecmd_failure(self, *args):
2086 return script_helper.assert_python_failure('-m', 'tarfile', *args)
2087
2088 def make_simple_tarfile(self, tar_name):
2089 files = [support.findfile('tokenize_tests.txt'),
2090 support.findfile('tokenize_tests-no-coding-cookie-'
2091 'and-utf8-bom-sig-only.txt')]
2092 self.addCleanup(support.unlink, tar_name)
2093 with tarfile.open(tar_name, 'w') as tf:
2094 for tardata in files:
2095 tf.add(tardata, arcname=os.path.basename(tardata))
2096
2097 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002098 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002099 for opt in '-t', '--test':
2100 out = self.tarfilecmd(opt, tar_name)
2101 self.assertEqual(out, b'')
2102
2103 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002104 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002105 for opt in '-v', '--verbose':
2106 out = self.tarfilecmd(opt, '-t', tar_name)
2107 self.assertIn(b'is a tar archive.\n', out)
2108
2109 def test_test_command_invalid_file(self):
2110 zipname = support.findfile('zipdir.zip')
2111 rc, out, err = self.tarfilecmd_failure('-t', zipname)
2112 self.assertIn(b' is not a tar archive.', err)
2113 self.assertEqual(out, b'')
2114 self.assertEqual(rc, 1)
2115
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002116 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002117 with self.subTest(tar_name=tar_name):
2118 with open(tar_name, 'rb') as f:
2119 data = f.read()
2120 try:
2121 with open(tmpname, 'wb') as f:
2122 f.write(data[:511])
2123 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
2124 self.assertEqual(out, b'')
2125 self.assertEqual(rc, 1)
2126 finally:
2127 support.unlink(tmpname)
2128
2129 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002130 for tar_name in testtarnames:
2131 with support.captured_stdout() as t:
2132 with tarfile.open(tar_name, 'r') as tf:
2133 tf.list(verbose=False)
2134 expected = t.getvalue().encode('ascii', 'backslashreplace')
2135 for opt in '-l', '--list':
2136 out = self.tarfilecmd(opt, tar_name,
2137 PYTHONIOENCODING='ascii')
2138 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002139
2140 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002141 for tar_name in testtarnames:
2142 with support.captured_stdout() as t:
2143 with tarfile.open(tar_name, 'r') as tf:
2144 tf.list(verbose=True)
2145 expected = t.getvalue().encode('ascii', 'backslashreplace')
2146 for opt in '-v', '--verbose':
2147 out = self.tarfilecmd(opt, '-l', tar_name,
2148 PYTHONIOENCODING='ascii')
2149 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002150
2151 def test_list_command_invalid_file(self):
2152 zipname = support.findfile('zipdir.zip')
2153 rc, out, err = self.tarfilecmd_failure('-l', zipname)
2154 self.assertIn(b' is not a tar archive.', err)
2155 self.assertEqual(out, b'')
2156 self.assertEqual(rc, 1)
2157
2158 def test_create_command(self):
2159 files = [support.findfile('tokenize_tests.txt'),
2160 support.findfile('tokenize_tests-no-coding-cookie-'
2161 'and-utf8-bom-sig-only.txt')]
2162 for opt in '-c', '--create':
2163 try:
2164 out = self.tarfilecmd(opt, tmpname, *files)
2165 self.assertEqual(out, b'')
2166 with tarfile.open(tmpname) as tar:
2167 tar.getmembers()
2168 finally:
2169 support.unlink(tmpname)
2170
2171 def test_create_command_verbose(self):
2172 files = [support.findfile('tokenize_tests.txt'),
2173 support.findfile('tokenize_tests-no-coding-cookie-'
2174 'and-utf8-bom-sig-only.txt')]
2175 for opt in '-v', '--verbose':
2176 try:
2177 out = self.tarfilecmd(opt, '-c', tmpname, *files)
2178 self.assertIn(b' file created.', out)
2179 with tarfile.open(tmpname) as tar:
2180 tar.getmembers()
2181 finally:
2182 support.unlink(tmpname)
2183
2184 def test_create_command_dotless_filename(self):
2185 files = [support.findfile('tokenize_tests.txt')]
2186 try:
2187 out = self.tarfilecmd('-c', dotlessname, *files)
2188 self.assertEqual(out, b'')
2189 with tarfile.open(dotlessname) as tar:
2190 tar.getmembers()
2191 finally:
2192 support.unlink(dotlessname)
2193
2194 def test_create_command_dot_started_filename(self):
2195 tar_name = os.path.join(TEMPDIR, ".testtar")
2196 files = [support.findfile('tokenize_tests.txt')]
2197 try:
2198 out = self.tarfilecmd('-c', tar_name, *files)
2199 self.assertEqual(out, b'')
2200 with tarfile.open(tar_name) as tar:
2201 tar.getmembers()
2202 finally:
2203 support.unlink(tar_name)
2204
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002205 def test_create_command_compressed(self):
2206 files = [support.findfile('tokenize_tests.txt'),
2207 support.findfile('tokenize_tests-no-coding-cookie-'
2208 'and-utf8-bom-sig-only.txt')]
2209 for filetype in (GzipTest, Bz2Test, LzmaTest):
2210 if not filetype.open:
2211 continue
2212 try:
2213 tar_name = tmpname + '.' + filetype.suffix
2214 out = self.tarfilecmd('-c', tar_name, *files)
2215 with filetype.taropen(tar_name) as tar:
2216 tar.getmembers()
2217 finally:
2218 support.unlink(tar_name)
2219
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002220 def test_extract_command(self):
2221 self.make_simple_tarfile(tmpname)
2222 for opt in '-e', '--extract':
2223 try:
2224 with support.temp_cwd(tarextdir):
2225 out = self.tarfilecmd(opt, tmpname)
2226 self.assertEqual(out, b'')
2227 finally:
2228 support.rmtree(tarextdir)
2229
2230 def test_extract_command_verbose(self):
2231 self.make_simple_tarfile(tmpname)
2232 for opt in '-v', '--verbose':
2233 try:
2234 with support.temp_cwd(tarextdir):
2235 out = self.tarfilecmd(opt, '-e', tmpname)
2236 self.assertIn(b' file is extracted.', out)
2237 finally:
2238 support.rmtree(tarextdir)
2239
2240 def test_extract_command_different_directory(self):
2241 self.make_simple_tarfile(tmpname)
2242 try:
2243 with support.temp_cwd(tarextdir):
2244 out = self.tarfilecmd('-e', tmpname, 'spamdir')
2245 self.assertEqual(out, b'')
2246 finally:
2247 support.rmtree(tarextdir)
2248
2249 def test_extract_command_invalid_file(self):
2250 zipname = support.findfile('zipdir.zip')
2251 with support.temp_cwd(tarextdir):
2252 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2253 self.assertIn(b' is not a tar archive.', err)
2254 self.assertEqual(out, b'')
2255 self.assertEqual(rc, 1)
2256
2257
Lars Gustäbel01385812010-03-03 12:08:54 +00002258class ContextManagerTest(unittest.TestCase):
2259
2260 def test_basic(self):
2261 with tarfile.open(tarname) as tar:
2262 self.assertFalse(tar.closed, "closed inside runtime context")
2263 self.assertTrue(tar.closed, "context manager failed")
2264
2265 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002266 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002267 # if the TarFile object is already closed.
2268 tar = tarfile.open(tarname)
2269 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002270 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002271 with tar:
2272 pass
2273
2274 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002275 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002276 with self.assertRaises(Exception) as exc:
2277 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002278 raise OSError
2279 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002280 "wrong exception raised in context manager")
2281 self.assertTrue(tar.closed, "context manager failed")
2282
2283 def test_no_eof(self):
2284 # __exit__() must not write end-of-archive blocks if an
2285 # exception was raised.
2286 try:
2287 with tarfile.open(tmpname, "w") as tar:
2288 raise Exception
2289 except:
2290 pass
2291 self.assertEqual(os.path.getsize(tmpname), 0,
2292 "context manager wrote an end-of-archive block")
2293 self.assertTrue(tar.closed, "context manager failed")
2294
2295 def test_eof(self):
2296 # __exit__() must write end-of-archive blocks, i.e. call
2297 # TarFile.close() if there was no error.
2298 with tarfile.open(tmpname, "w"):
2299 pass
2300 self.assertNotEqual(os.path.getsize(tmpname), 0,
2301 "context manager wrote no end-of-archive block")
2302
2303 def test_fileobj(self):
2304 # Test that __exit__() did not close the external file
2305 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002306 with open(tmpname, "wb") as fobj:
2307 try:
2308 with tarfile.open(fileobj=fobj, mode="w") as tar:
2309 raise Exception
2310 except:
2311 pass
2312 self.assertFalse(fobj.closed, "external file object was closed")
2313 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002314
2315
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002316@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2317class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002318
2319 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002320 # symbolic or hard links tarfile tries to extract these types of members
2321 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002322 def _test_link_extraction(self, name):
2323 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002324 with open(os.path.join(TEMPDIR, name), "rb") as f:
2325 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002326 self.assertEqual(md5sum(data), md5_regtype)
2327
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002328 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002329 @unittest.skipIf(hasattr(os.path, "islink"),
2330 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002331 def test_hardlink_extraction1(self):
2332 self._test_link_extraction("ustar/lnktype")
2333
Brian Curtind40e6f72010-07-08 21:39:08 +00002334 @unittest.skipIf(hasattr(os.path, "islink"),
2335 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002336 def test_hardlink_extraction2(self):
2337 self._test_link_extraction("./ustar/linktest2/lnktype")
2338
Brian Curtin74e45612010-07-09 15:58:59 +00002339 @unittest.skipIf(hasattr(os, "symlink"),
2340 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002341 def test_symlink_extraction1(self):
2342 self._test_link_extraction("ustar/symtype")
2343
Brian Curtin74e45612010-07-09 15:58:59 +00002344 @unittest.skipIf(hasattr(os, "symlink"),
2345 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002346 def test_symlink_extraction2(self):
2347 self._test_link_extraction("./ustar/linktest2/symtype")
2348
2349
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002350class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002351 # Issue5068: The _BZ2Proxy.read() method loops forever
2352 # on an empty or partial bzipped file.
2353
2354 def _test_partial_input(self, mode):
2355 class MyBytesIO(io.BytesIO):
2356 hit_eof = False
2357 def read(self, n):
2358 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002359 raise AssertionError("infinite loop detected in "
2360 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002361 self.hit_eof = self.tell() == len(self.getvalue())
2362 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002363 def seek(self, *args):
2364 self.hit_eof = False
2365 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002366
2367 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2368 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002369 try:
2370 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2371 except tarfile.ReadError:
2372 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002373
2374 def test_partial_input(self):
2375 self._test_partial_input("r")
2376
2377 def test_partial_input_bz2(self):
2378 self._test_partial_input("r:bz2")
2379
2380
Eric V. Smith7a803892015-04-15 10:27:58 -04002381def root_is_uid_gid_0():
2382 try:
2383 import pwd, grp
2384 except ImportError:
2385 return False
2386 if pwd.getpwuid(0)[0] != 'root':
2387 return False
2388 if grp.getgrgid(0)[0] != 'root':
2389 return False
2390 return True
2391
2392
Zachary Waread3e27a2015-05-12 23:57:21 -05002393@unittest.skipUnless(hasattr(os, 'chown'), "missing os.chown")
2394@unittest.skipUnless(hasattr(os, 'geteuid'), "missing os.geteuid")
Eric V. Smith7a803892015-04-15 10:27:58 -04002395class NumericOwnerTest(unittest.TestCase):
2396 # mock the following:
2397 # os.chown: so we can test what's being called
2398 # os.chmod: so the modes are not actually changed. if they are, we can't
2399 # delete the files/directories
2400 # os.geteuid: so we can lie and say we're root (uid = 0)
2401
2402 @staticmethod
2403 def _make_test_archive(filename_1, dirname_1, filename_2):
2404 # the file contents to write
2405 fobj = io.BytesIO(b"content")
2406
2407 # create a tar file with a file, a directory, and a file within that
2408 # directory. Assign various .uid/.gid values to them
2409 items = [(filename_1, 99, 98, tarfile.REGTYPE, fobj),
2410 (dirname_1, 77, 76, tarfile.DIRTYPE, None),
2411 (filename_2, 88, 87, tarfile.REGTYPE, fobj),
2412 ]
2413 with tarfile.open(tmpname, 'w') as tarfl:
2414 for name, uid, gid, typ, contents in items:
2415 t = tarfile.TarInfo(name)
2416 t.uid = uid
2417 t.gid = gid
2418 t.uname = 'root'
2419 t.gname = 'root'
2420 t.type = typ
2421 tarfl.addfile(t, contents)
2422
2423 # return the full pathname to the tar file
2424 return tmpname
2425
2426 @staticmethod
2427 @contextmanager
2428 def _setup_test(mock_geteuid):
2429 mock_geteuid.return_value = 0 # lie and say we're root
2430 fname = 'numeric-owner-testfile'
2431 dirname = 'dir'
2432
2433 # the names we want stored in the tarfile
2434 filename_1 = fname
2435 dirname_1 = dirname
2436 filename_2 = os.path.join(dirname, fname)
2437
2438 # create the tarfile with the contents we're after
2439 tar_filename = NumericOwnerTest._make_test_archive(filename_1,
2440 dirname_1,
2441 filename_2)
2442
2443 # open the tarfile for reading. yield it and the names of the items
2444 # we stored into the file
2445 with tarfile.open(tar_filename) as tarfl:
2446 yield tarfl, filename_1, dirname_1, filename_2
2447
2448 @unittest.mock.patch('os.chown')
2449 @unittest.mock.patch('os.chmod')
2450 @unittest.mock.patch('os.geteuid')
2451 def test_extract_with_numeric_owner(self, mock_geteuid, mock_chmod,
2452 mock_chown):
2453 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _,
2454 filename_2):
2455 tarfl.extract(filename_1, TEMPDIR, numeric_owner=True)
2456 tarfl.extract(filename_2 , TEMPDIR, numeric_owner=True)
2457
2458 # convert to filesystem paths
2459 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2460 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2461
2462 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2463 unittest.mock.call(f_filename_2, 88, 87),
2464 ],
2465 any_order=True)
2466
2467 @unittest.mock.patch('os.chown')
2468 @unittest.mock.patch('os.chmod')
2469 @unittest.mock.patch('os.geteuid')
2470 def test_extractall_with_numeric_owner(self, mock_geteuid, mock_chmod,
2471 mock_chown):
2472 with self._setup_test(mock_geteuid) as (tarfl, filename_1, dirname_1,
2473 filename_2):
2474 tarfl.extractall(TEMPDIR, numeric_owner=True)
2475
2476 # convert to filesystem paths
2477 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2478 f_dirname_1 = os.path.join(TEMPDIR, dirname_1)
2479 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2480
2481 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2482 unittest.mock.call(f_dirname_1, 77, 76),
2483 unittest.mock.call(f_filename_2, 88, 87),
2484 ],
2485 any_order=True)
2486
2487 # this test requires that uid=0 and gid=0 really be named 'root'. that's
2488 # because the uname and gname in the test file are 'root', and extract()
2489 # will look them up using pwd and grp to find their uid and gid, which we
2490 # test here to be 0.
2491 @unittest.skipUnless(root_is_uid_gid_0(),
2492 'uid=0,gid=0 must be named "root"')
2493 @unittest.mock.patch('os.chown')
2494 @unittest.mock.patch('os.chmod')
2495 @unittest.mock.patch('os.geteuid')
2496 def test_extract_without_numeric_owner(self, mock_geteuid, mock_chmod,
2497 mock_chown):
2498 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2499 tarfl.extract(filename_1, TEMPDIR, numeric_owner=False)
2500
2501 # convert to filesystem paths
2502 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2503
2504 mock_chown.assert_called_with(f_filename_1, 0, 0)
2505
2506 @unittest.mock.patch('os.geteuid')
2507 def test_keyword_only(self, mock_geteuid):
2508 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2509 self.assertRaises(TypeError,
2510 tarfl.extract, filename_1, TEMPDIR, False, True)
2511
2512
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002513def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002514 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002515 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002516
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002517 global testtarnames
2518 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002519 with open(tarname, "rb") as fobj:
2520 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002521
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002522 # Create compressed tarfiles.
2523 for c in GzipTest, Bz2Test, LzmaTest:
2524 if c.open:
2525 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002526 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002527 with c.open(c.tarname, "wb") as tar:
2528 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002529
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002530def tearDownModule():
2531 if os.path.exists(TEMPDIR):
Tim Goldene0bd2c52014-05-06 13:24:26 +01002532 support.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002533
Neal Norwitz996acf12003-02-17 14:51:41 +00002534if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002535 unittest.main()