blob: 03875abe84d7a895d8eb1b76ebbd156e59e49471 [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
1670class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001671
1672 format = tarfile.USTAR_FORMAT
1673
1674 def test_iso8859_1_filename(self):
1675 self._test_unicode_filename("iso8859-1")
1676
1677 def test_utf7_filename(self):
1678 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001679
1680 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001681 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001682
Guido van Rossumd8faa362007-04-27 19:54:29 +00001683 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001684 tar = tarfile.open(tmpname, "w", format=self.format,
1685 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001686 try:
1687 name = "\xe4\xf6\xfc"
1688 tar.addfile(tarfile.TarInfo(name))
1689 finally:
1690 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001691
1692 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001693 try:
1694 self.assertEqual(tar.getmembers()[0].name, name)
1695 finally:
1696 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001697
1698 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001699 tar = tarfile.open(tmpname, "w", format=self.format,
1700 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001701 try:
1702 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001703
Antoine Pitrou95f55602010-09-23 18:36:46 +00001704 tarinfo.name = "\xe4\xf6\xfc"
1705 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001706
Antoine Pitrou95f55602010-09-23 18:36:46 +00001707 tarinfo.name = "foo"
1708 tarinfo.uname = "\xe4\xf6\xfc"
1709 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1710 finally:
1711 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001712
1713 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001714 tar = tarfile.open(tarname, "r",
1715 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001716 try:
1717 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001718 self.assertIs(type(t.name), str)
1719 self.assertIs(type(t.linkname), str)
1720 self.assertIs(type(t.uname), str)
1721 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001722 finally:
1723 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001724
Guido van Rossume7ba4952007-06-06 23:52:48 +00001725 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001726 t = tarfile.TarInfo("foo")
1727 t.uname = "\xe4\xf6\xfc"
1728 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001729
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001730 tar = tarfile.open(tmpname, mode="w", format=self.format,
1731 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001732 try:
1733 tar.addfile(t)
1734 finally:
1735 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001736
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001737 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001738 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001739 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001740 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1741 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1742
1743 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001744 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001745 tar = tarfile.open(tmpname, encoding="ascii")
1746 t = tar.getmember("foo")
1747 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1748 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1749 finally:
1750 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001751
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001752
Guido van Rossume7ba4952007-06-06 23:52:48 +00001753class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001754
Guido van Rossume7ba4952007-06-06 23:52:48 +00001755 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001756
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001757 def test_bad_pax_header(self):
1758 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1759 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001760 for encoding, name in (
1761 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001762 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001763 with tarfile.open(tarname, encoding=encoding,
1764 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001765 try:
1766 t = tar.getmember(name)
1767 except KeyError:
1768 self.fail("unable to read bad GNU tar pax header")
1769
Guido van Rossumd8faa362007-04-27 19:54:29 +00001770
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001771class PAXUnicodeTest(UstarUnicodeTest):
1772
1773 format = tarfile.PAX_FORMAT
1774
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001775 # PAX_FORMAT ignores encoding in write mode.
1776 test_unicode_filename_error = None
1777
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001778 def test_binary_header(self):
1779 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001780 for encoding, name in (
1781 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001782 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001783 with tarfile.open(tarname, encoding=encoding,
1784 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001785 try:
1786 t = tar.getmember(name)
1787 except KeyError:
1788 self.fail("unable to read POSIX.1-2008 binary header")
1789
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001790
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001791class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001792 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001793
Guido van Rossumd8faa362007-04-27 19:54:29 +00001794 def setUp(self):
1795 self.tarname = tmpname
1796 if os.path.exists(self.tarname):
Tim Goldene0bd2c52014-05-06 13:24:26 +01001797 support.unlink(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001798
Guido van Rossumd8faa362007-04-27 19:54:29 +00001799 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001800 with tarfile.open(tarname, encoding="iso8859-1") as src:
1801 t = src.getmember("ustar/regtype")
1802 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001803 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001804 with tarfile.open(self.tarname, mode) as tar:
1805 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001806
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001807 def test_append_compressed(self):
1808 self._create_testtar("w:" + self.suffix)
1809 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1810
1811class AppendTest(AppendTestBase, unittest.TestCase):
1812 test_append_compressed = None
1813
1814 def _add_testfile(self, fileobj=None):
1815 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1816 tar.addfile(tarfile.TarInfo("bar"))
1817
Guido van Rossumd8faa362007-04-27 19:54:29 +00001818 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001819 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1820 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001821
1822 def test_non_existing(self):
1823 self._add_testfile()
1824 self._test()
1825
1826 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001827 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001828 self._add_testfile()
1829 self._test()
1830
1831 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001832 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001833 self._add_testfile(fobj)
1834 fobj.seek(0)
1835 self._test(fileobj=fobj)
1836
1837 def test_fileobj(self):
1838 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001839 with open(self.tarname, "rb") as fobj:
1840 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001841 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001842 self._add_testfile(fobj)
1843 fobj.seek(0)
1844 self._test(names=["foo", "bar"], fileobj=fobj)
1845
1846 def test_existing(self):
1847 self._create_testtar()
1848 self._add_testfile()
1849 self._test(names=["foo", "bar"])
1850
Lars Gustäbel9520a432009-11-22 18:48:49 +00001851 # Append mode is supposed to fail if the tarfile to append to
1852 # does not end with a zero block.
1853 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001854 with open(self.tarname, "wb") as fobj:
1855 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001856 self.assertRaises(tarfile.ReadError, self._add_testfile)
1857
1858 def test_null(self):
1859 self._test_error(b"")
1860
1861 def test_incomplete(self):
1862 self._test_error(b"\0" * 13)
1863
1864 def test_premature_eof(self):
1865 data = tarfile.TarInfo("foo").tobuf()
1866 self._test_error(data)
1867
1868 def test_trailing_garbage(self):
1869 data = tarfile.TarInfo("foo").tobuf()
1870 self._test_error(data + b"\0" * 13)
1871
1872 def test_invalid(self):
1873 self._test_error(b"a" * 512)
1874
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001875class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
1876 pass
1877
1878class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
1879 pass
1880
1881class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
1882 pass
1883
Guido van Rossumd8faa362007-04-27 19:54:29 +00001884
1885class LimitsTest(unittest.TestCase):
1886
1887 def test_ustar_limits(self):
1888 # 100 char name
1889 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001890 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001891
1892 # 101 char name that cannot be stored
1893 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001894 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001895
1896 # 256 char name with a slash at pos 156
1897 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001898 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001899
1900 # 256 char name that cannot be stored
1901 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001902 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001903
1904 # 512 char name
1905 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001906 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001907
1908 # 512 char linkname
1909 tarinfo = tarfile.TarInfo("longlink")
1910 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001911 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001912
1913 # uid > 8 digits
1914 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001915 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001916 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001917
1918 def test_gnu_limits(self):
1919 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001920 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001921
1922 tarinfo = tarfile.TarInfo("longlink")
1923 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001924 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001925
1926 # uid >= 256 ** 7
1927 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001928 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001929 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001930
1931 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001932 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001933 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001934
1935 tarinfo = tarfile.TarInfo("longlink")
1936 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001937 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001938
1939 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001940 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001941 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001942
1943
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001944class MiscTest(unittest.TestCase):
1945
1946 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001947 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
1948 b"foo\0\0\0\0\0")
1949 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
1950 b"foo")
1951 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
1952 "foo")
1953 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
1954 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001955
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001956 def test_read_number_fields(self):
1957 # Issue 13158: Test if GNU tar specific base-256 number fields
1958 # are decoded correctly.
1959 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1960 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001961 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
1962 0o10000000)
1963 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
1964 0xffffffff)
1965 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
1966 -1)
1967 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
1968 -100)
1969 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
1970 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001971
Lars Gustäbelb7a688b2015-07-02 19:38:38 +02001972 # Issue 24514: Test if empty number fields are converted to zero.
1973 self.assertEqual(tarfile.nti(b"\0"), 0)
1974 self.assertEqual(tarfile.nti(b" \0"), 0)
1975
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001976 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001977 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001978 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001979 self.assertEqual(tarfile.itn(0o10000000),
1980 b"\x80\x00\x00\x00\x00\x20\x00\x00")
1981 self.assertEqual(tarfile.itn(0xffffffff),
1982 b"\x80\x00\x00\x00\xff\xff\xff\xff")
1983 self.assertEqual(tarfile.itn(-1),
1984 b"\xff\xff\xff\xff\xff\xff\xff\xff")
1985 self.assertEqual(tarfile.itn(-100),
1986 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1987 self.assertEqual(tarfile.itn(-0x100000000000000),
1988 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001989
1990 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001991 with self.assertRaises(ValueError):
1992 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
1993 with self.assertRaises(ValueError):
1994 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
1995 with self.assertRaises(ValueError):
1996 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
1997 with self.assertRaises(ValueError):
1998 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001999
Martin Panter104dcda2016-01-16 06:59:13 +00002000 def test__all__(self):
Martin Panter5318d102016-01-16 11:01:14 +00002001 blacklist = {'version', 'grp', 'pwd', 'symlink_exception',
Martin Panter104dcda2016-01-16 06:59:13 +00002002 'NUL', 'BLOCKSIZE', 'RECORDSIZE', 'GNU_MAGIC',
2003 'POSIX_MAGIC', 'LENGTH_NAME', 'LENGTH_LINK',
2004 'LENGTH_PREFIX', 'REGTYPE', 'AREGTYPE', 'LNKTYPE',
2005 'SYMTYPE', 'CHRTYPE', 'BLKTYPE', 'DIRTYPE', 'FIFOTYPE',
2006 'CONTTYPE', 'GNUTYPE_LONGNAME', 'GNUTYPE_LONGLINK',
2007 'GNUTYPE_SPARSE', 'XHDTYPE', 'XGLTYPE', 'SOLARIS_XHDTYPE',
2008 'SUPPORTED_TYPES', 'REGULAR_TYPES', 'GNU_TYPES',
2009 'PAX_FIELDS', 'PAX_NAME_FIELDS', 'PAX_NUMBER_FIELDS',
2010 'stn', 'nts', 'nti', 'itn', 'calc_chksums', 'copyfileobj',
2011 'filemode',
2012 'EmptyHeaderError', 'TruncatedHeaderError',
2013 'EOFHeaderError', 'InvalidHeaderError',
Serhiy Storchaka2c1d3e32016-01-16 11:05:11 +02002014 'SubsequentHeaderError', 'ExFileObject',
Martin Panter104dcda2016-01-16 06:59:13 +00002015 'main'}
2016 support.check__all__(self, tarfile, blacklist=blacklist)
2017
Lars Gustäbelb506dc32007-08-07 18:36:16 +00002018
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002019class CommandLineTest(unittest.TestCase):
2020
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002021 def tarfilecmd(self, *args, **kwargs):
2022 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
2023 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01002024 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002025
2026 def tarfilecmd_failure(self, *args):
2027 return script_helper.assert_python_failure('-m', 'tarfile', *args)
2028
2029 def make_simple_tarfile(self, tar_name):
2030 files = [support.findfile('tokenize_tests.txt'),
2031 support.findfile('tokenize_tests-no-coding-cookie-'
2032 'and-utf8-bom-sig-only.txt')]
2033 self.addCleanup(support.unlink, tar_name)
2034 with tarfile.open(tar_name, 'w') as tf:
2035 for tardata in files:
2036 tf.add(tardata, arcname=os.path.basename(tardata))
2037
2038 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002039 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002040 for opt in '-t', '--test':
2041 out = self.tarfilecmd(opt, tar_name)
2042 self.assertEqual(out, b'')
2043
2044 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002045 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002046 for opt in '-v', '--verbose':
2047 out = self.tarfilecmd(opt, '-t', tar_name)
2048 self.assertIn(b'is a tar archive.\n', out)
2049
2050 def test_test_command_invalid_file(self):
2051 zipname = support.findfile('zipdir.zip')
2052 rc, out, err = self.tarfilecmd_failure('-t', zipname)
2053 self.assertIn(b' is not a tar archive.', err)
2054 self.assertEqual(out, b'')
2055 self.assertEqual(rc, 1)
2056
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002057 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002058 with self.subTest(tar_name=tar_name):
2059 with open(tar_name, 'rb') as f:
2060 data = f.read()
2061 try:
2062 with open(tmpname, 'wb') as f:
2063 f.write(data[:511])
2064 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
2065 self.assertEqual(out, b'')
2066 self.assertEqual(rc, 1)
2067 finally:
2068 support.unlink(tmpname)
2069
2070 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002071 for tar_name in testtarnames:
2072 with support.captured_stdout() as t:
2073 with tarfile.open(tar_name, 'r') as tf:
2074 tf.list(verbose=False)
2075 expected = t.getvalue().encode('ascii', 'backslashreplace')
2076 for opt in '-l', '--list':
2077 out = self.tarfilecmd(opt, tar_name,
2078 PYTHONIOENCODING='ascii')
2079 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002080
2081 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02002082 for tar_name in testtarnames:
2083 with support.captured_stdout() as t:
2084 with tarfile.open(tar_name, 'r') as tf:
2085 tf.list(verbose=True)
2086 expected = t.getvalue().encode('ascii', 'backslashreplace')
2087 for opt in '-v', '--verbose':
2088 out = self.tarfilecmd(opt, '-l', tar_name,
2089 PYTHONIOENCODING='ascii')
2090 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002091
2092 def test_list_command_invalid_file(self):
2093 zipname = support.findfile('zipdir.zip')
2094 rc, out, err = self.tarfilecmd_failure('-l', zipname)
2095 self.assertIn(b' is not a tar archive.', err)
2096 self.assertEqual(out, b'')
2097 self.assertEqual(rc, 1)
2098
2099 def test_create_command(self):
2100 files = [support.findfile('tokenize_tests.txt'),
2101 support.findfile('tokenize_tests-no-coding-cookie-'
2102 'and-utf8-bom-sig-only.txt')]
2103 for opt in '-c', '--create':
2104 try:
2105 out = self.tarfilecmd(opt, tmpname, *files)
2106 self.assertEqual(out, b'')
2107 with tarfile.open(tmpname) as tar:
2108 tar.getmembers()
2109 finally:
2110 support.unlink(tmpname)
2111
2112 def test_create_command_verbose(self):
2113 files = [support.findfile('tokenize_tests.txt'),
2114 support.findfile('tokenize_tests-no-coding-cookie-'
2115 'and-utf8-bom-sig-only.txt')]
2116 for opt in '-v', '--verbose':
2117 try:
2118 out = self.tarfilecmd(opt, '-c', tmpname, *files)
2119 self.assertIn(b' file created.', out)
2120 with tarfile.open(tmpname) as tar:
2121 tar.getmembers()
2122 finally:
2123 support.unlink(tmpname)
2124
2125 def test_create_command_dotless_filename(self):
2126 files = [support.findfile('tokenize_tests.txt')]
2127 try:
2128 out = self.tarfilecmd('-c', dotlessname, *files)
2129 self.assertEqual(out, b'')
2130 with tarfile.open(dotlessname) as tar:
2131 tar.getmembers()
2132 finally:
2133 support.unlink(dotlessname)
2134
2135 def test_create_command_dot_started_filename(self):
2136 tar_name = os.path.join(TEMPDIR, ".testtar")
2137 files = [support.findfile('tokenize_tests.txt')]
2138 try:
2139 out = self.tarfilecmd('-c', tar_name, *files)
2140 self.assertEqual(out, b'')
2141 with tarfile.open(tar_name) as tar:
2142 tar.getmembers()
2143 finally:
2144 support.unlink(tar_name)
2145
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002146 def test_create_command_compressed(self):
2147 files = [support.findfile('tokenize_tests.txt'),
2148 support.findfile('tokenize_tests-no-coding-cookie-'
2149 'and-utf8-bom-sig-only.txt')]
2150 for filetype in (GzipTest, Bz2Test, LzmaTest):
2151 if not filetype.open:
2152 continue
2153 try:
2154 tar_name = tmpname + '.' + filetype.suffix
2155 out = self.tarfilecmd('-c', tar_name, *files)
2156 with filetype.taropen(tar_name) as tar:
2157 tar.getmembers()
2158 finally:
2159 support.unlink(tar_name)
2160
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002161 def test_extract_command(self):
2162 self.make_simple_tarfile(tmpname)
2163 for opt in '-e', '--extract':
2164 try:
2165 with support.temp_cwd(tarextdir):
2166 out = self.tarfilecmd(opt, tmpname)
2167 self.assertEqual(out, b'')
2168 finally:
2169 support.rmtree(tarextdir)
2170
2171 def test_extract_command_verbose(self):
2172 self.make_simple_tarfile(tmpname)
2173 for opt in '-v', '--verbose':
2174 try:
2175 with support.temp_cwd(tarextdir):
2176 out = self.tarfilecmd(opt, '-e', tmpname)
2177 self.assertIn(b' file is extracted.', out)
2178 finally:
2179 support.rmtree(tarextdir)
2180
2181 def test_extract_command_different_directory(self):
2182 self.make_simple_tarfile(tmpname)
2183 try:
2184 with support.temp_cwd(tarextdir):
2185 out = self.tarfilecmd('-e', tmpname, 'spamdir')
2186 self.assertEqual(out, b'')
2187 finally:
2188 support.rmtree(tarextdir)
2189
2190 def test_extract_command_invalid_file(self):
2191 zipname = support.findfile('zipdir.zip')
2192 with support.temp_cwd(tarextdir):
2193 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2194 self.assertIn(b' is not a tar archive.', err)
2195 self.assertEqual(out, b'')
2196 self.assertEqual(rc, 1)
2197
2198
Lars Gustäbel01385812010-03-03 12:08:54 +00002199class ContextManagerTest(unittest.TestCase):
2200
2201 def test_basic(self):
2202 with tarfile.open(tarname) as tar:
2203 self.assertFalse(tar.closed, "closed inside runtime context")
2204 self.assertTrue(tar.closed, "context manager failed")
2205
2206 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002207 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002208 # if the TarFile object is already closed.
2209 tar = tarfile.open(tarname)
2210 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002211 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002212 with tar:
2213 pass
2214
2215 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002216 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002217 with self.assertRaises(Exception) as exc:
2218 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002219 raise OSError
2220 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002221 "wrong exception raised in context manager")
2222 self.assertTrue(tar.closed, "context manager failed")
2223
2224 def test_no_eof(self):
2225 # __exit__() must not write end-of-archive blocks if an
2226 # exception was raised.
2227 try:
2228 with tarfile.open(tmpname, "w") as tar:
2229 raise Exception
2230 except:
2231 pass
2232 self.assertEqual(os.path.getsize(tmpname), 0,
2233 "context manager wrote an end-of-archive block")
2234 self.assertTrue(tar.closed, "context manager failed")
2235
2236 def test_eof(self):
2237 # __exit__() must write end-of-archive blocks, i.e. call
2238 # TarFile.close() if there was no error.
2239 with tarfile.open(tmpname, "w"):
2240 pass
2241 self.assertNotEqual(os.path.getsize(tmpname), 0,
2242 "context manager wrote no end-of-archive block")
2243
2244 def test_fileobj(self):
2245 # Test that __exit__() did not close the external file
2246 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002247 with open(tmpname, "wb") as fobj:
2248 try:
2249 with tarfile.open(fileobj=fobj, mode="w") as tar:
2250 raise Exception
2251 except:
2252 pass
2253 self.assertFalse(fobj.closed, "external file object was closed")
2254 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002255
2256
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002257@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2258class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002259
2260 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002261 # symbolic or hard links tarfile tries to extract these types of members
2262 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002263 def _test_link_extraction(self, name):
2264 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002265 with open(os.path.join(TEMPDIR, name), "rb") as f:
2266 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002267 self.assertEqual(md5sum(data), md5_regtype)
2268
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002269 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002270 @unittest.skipIf(hasattr(os.path, "islink"),
2271 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002272 def test_hardlink_extraction1(self):
2273 self._test_link_extraction("ustar/lnktype")
2274
Brian Curtind40e6f72010-07-08 21:39:08 +00002275 @unittest.skipIf(hasattr(os.path, "islink"),
2276 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002277 def test_hardlink_extraction2(self):
2278 self._test_link_extraction("./ustar/linktest2/lnktype")
2279
Brian Curtin74e45612010-07-09 15:58:59 +00002280 @unittest.skipIf(hasattr(os, "symlink"),
2281 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002282 def test_symlink_extraction1(self):
2283 self._test_link_extraction("ustar/symtype")
2284
Brian Curtin74e45612010-07-09 15:58:59 +00002285 @unittest.skipIf(hasattr(os, "symlink"),
2286 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002287 def test_symlink_extraction2(self):
2288 self._test_link_extraction("./ustar/linktest2/symtype")
2289
2290
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002291class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002292 # Issue5068: The _BZ2Proxy.read() method loops forever
2293 # on an empty or partial bzipped file.
2294
2295 def _test_partial_input(self, mode):
2296 class MyBytesIO(io.BytesIO):
2297 hit_eof = False
2298 def read(self, n):
2299 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002300 raise AssertionError("infinite loop detected in "
2301 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002302 self.hit_eof = self.tell() == len(self.getvalue())
2303 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002304 def seek(self, *args):
2305 self.hit_eof = False
2306 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002307
2308 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2309 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002310 try:
2311 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2312 except tarfile.ReadError:
2313 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002314
2315 def test_partial_input(self):
2316 self._test_partial_input("r")
2317
2318 def test_partial_input_bz2(self):
2319 self._test_partial_input("r:bz2")
2320
2321
Eric V. Smith7a803892015-04-15 10:27:58 -04002322def root_is_uid_gid_0():
2323 try:
2324 import pwd, grp
2325 except ImportError:
2326 return False
2327 if pwd.getpwuid(0)[0] != 'root':
2328 return False
2329 if grp.getgrgid(0)[0] != 'root':
2330 return False
2331 return True
2332
2333
Zachary Waread3e27a2015-05-12 23:57:21 -05002334@unittest.skipUnless(hasattr(os, 'chown'), "missing os.chown")
2335@unittest.skipUnless(hasattr(os, 'geteuid'), "missing os.geteuid")
Eric V. Smith7a803892015-04-15 10:27:58 -04002336class NumericOwnerTest(unittest.TestCase):
2337 # mock the following:
2338 # os.chown: so we can test what's being called
2339 # os.chmod: so the modes are not actually changed. if they are, we can't
2340 # delete the files/directories
2341 # os.geteuid: so we can lie and say we're root (uid = 0)
2342
2343 @staticmethod
2344 def _make_test_archive(filename_1, dirname_1, filename_2):
2345 # the file contents to write
2346 fobj = io.BytesIO(b"content")
2347
2348 # create a tar file with a file, a directory, and a file within that
2349 # directory. Assign various .uid/.gid values to them
2350 items = [(filename_1, 99, 98, tarfile.REGTYPE, fobj),
2351 (dirname_1, 77, 76, tarfile.DIRTYPE, None),
2352 (filename_2, 88, 87, tarfile.REGTYPE, fobj),
2353 ]
2354 with tarfile.open(tmpname, 'w') as tarfl:
2355 for name, uid, gid, typ, contents in items:
2356 t = tarfile.TarInfo(name)
2357 t.uid = uid
2358 t.gid = gid
2359 t.uname = 'root'
2360 t.gname = 'root'
2361 t.type = typ
2362 tarfl.addfile(t, contents)
2363
2364 # return the full pathname to the tar file
2365 return tmpname
2366
2367 @staticmethod
2368 @contextmanager
2369 def _setup_test(mock_geteuid):
2370 mock_geteuid.return_value = 0 # lie and say we're root
2371 fname = 'numeric-owner-testfile'
2372 dirname = 'dir'
2373
2374 # the names we want stored in the tarfile
2375 filename_1 = fname
2376 dirname_1 = dirname
2377 filename_2 = os.path.join(dirname, fname)
2378
2379 # create the tarfile with the contents we're after
2380 tar_filename = NumericOwnerTest._make_test_archive(filename_1,
2381 dirname_1,
2382 filename_2)
2383
2384 # open the tarfile for reading. yield it and the names of the items
2385 # we stored into the file
2386 with tarfile.open(tar_filename) as tarfl:
2387 yield tarfl, filename_1, dirname_1, filename_2
2388
2389 @unittest.mock.patch('os.chown')
2390 @unittest.mock.patch('os.chmod')
2391 @unittest.mock.patch('os.geteuid')
2392 def test_extract_with_numeric_owner(self, mock_geteuid, mock_chmod,
2393 mock_chown):
2394 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _,
2395 filename_2):
2396 tarfl.extract(filename_1, TEMPDIR, numeric_owner=True)
2397 tarfl.extract(filename_2 , TEMPDIR, numeric_owner=True)
2398
2399 # convert to filesystem paths
2400 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2401 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2402
2403 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2404 unittest.mock.call(f_filename_2, 88, 87),
2405 ],
2406 any_order=True)
2407
2408 @unittest.mock.patch('os.chown')
2409 @unittest.mock.patch('os.chmod')
2410 @unittest.mock.patch('os.geteuid')
2411 def test_extractall_with_numeric_owner(self, mock_geteuid, mock_chmod,
2412 mock_chown):
2413 with self._setup_test(mock_geteuid) as (tarfl, filename_1, dirname_1,
2414 filename_2):
2415 tarfl.extractall(TEMPDIR, numeric_owner=True)
2416
2417 # convert to filesystem paths
2418 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2419 f_dirname_1 = os.path.join(TEMPDIR, dirname_1)
2420 f_filename_2 = os.path.join(TEMPDIR, filename_2)
2421
2422 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
2423 unittest.mock.call(f_dirname_1, 77, 76),
2424 unittest.mock.call(f_filename_2, 88, 87),
2425 ],
2426 any_order=True)
2427
2428 # this test requires that uid=0 and gid=0 really be named 'root'. that's
2429 # because the uname and gname in the test file are 'root', and extract()
2430 # will look them up using pwd and grp to find their uid and gid, which we
2431 # test here to be 0.
2432 @unittest.skipUnless(root_is_uid_gid_0(),
2433 'uid=0,gid=0 must be named "root"')
2434 @unittest.mock.patch('os.chown')
2435 @unittest.mock.patch('os.chmod')
2436 @unittest.mock.patch('os.geteuid')
2437 def test_extract_without_numeric_owner(self, mock_geteuid, mock_chmod,
2438 mock_chown):
2439 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2440 tarfl.extract(filename_1, TEMPDIR, numeric_owner=False)
2441
2442 # convert to filesystem paths
2443 f_filename_1 = os.path.join(TEMPDIR, filename_1)
2444
2445 mock_chown.assert_called_with(f_filename_1, 0, 0)
2446
2447 @unittest.mock.patch('os.geteuid')
2448 def test_keyword_only(self, mock_geteuid):
2449 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
2450 self.assertRaises(TypeError,
2451 tarfl.extract, filename_1, TEMPDIR, False, True)
2452
2453
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002454def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002455 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002456 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002457
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002458 global testtarnames
2459 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002460 with open(tarname, "rb") as fobj:
2461 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002462
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002463 # Create compressed tarfiles.
2464 for c in GzipTest, Bz2Test, LzmaTest:
2465 if c.open:
2466 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002467 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002468 with c.open(c.tarname, "wb") as tar:
2469 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002470
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002471def tearDownModule():
2472 if os.path.exists(TEMPDIR):
Tim Goldene0bd2c52014-05-06 13:24:26 +01002473 support.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002474
Neal Norwitz996acf12003-02-17 14:51:41 +00002475if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002476 unittest.main()