blob: 8ab757592791e20a9fd1f161edff465d7dc4c3f5 [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
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00005
6import unittest
7import tarfile
8
Serhiy Storchakad27b4552013-11-24 01:53:29 +02009from test import support, script_helper
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000010
11# Check for our compression modules.
12try:
13 import gzip
Brett Cannon260fbe82013-07-04 18:16:15 -040014except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000015 gzip = None
16try:
17 import bz2
Brett Cannon260fbe82013-07-04 18:16:15 -040018except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000019 bz2 = None
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010020try:
21 import lzma
Brett Cannon260fbe82013-07-04 18:16:15 -040022except ImportError:
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010023 lzma = None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000024
Guido van Rossumd8faa362007-04-27 19:54:29 +000025def md5sum(data):
Guido van Rossuma8add0e2007-05-14 22:03:55 +000026 return md5(data).hexdigest()
Guido van Rossumd8faa362007-04-27 19:54:29 +000027
Antoine Pitrouab58b5f2010-09-23 19:39:35 +000028TEMPDIR = os.path.abspath(support.TESTFN) + "-tardir"
Serhiy Storchakad27b4552013-11-24 01:53:29 +020029tarextdir = TEMPDIR + '-extract-test'
Antoine Pitrou941ee882009-11-11 20:59:38 +000030tarname = support.findfile("testtar.tar")
Guido van Rossumd8faa362007-04-27 19:54:29 +000031gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
32bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010033xzname = os.path.join(TEMPDIR, "testtar.tar.xz")
Guido van Rossumd8faa362007-04-27 19:54:29 +000034tmpname = os.path.join(TEMPDIR, "tmp.tar")
Serhiy Storchakad27b4552013-11-24 01:53:29 +020035dotlessname = os.path.join(TEMPDIR, "testtar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000036
Guido van Rossumd8faa362007-04-27 19:54:29 +000037md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
38md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000039
40
Serhiy Storchaka8b562922013-06-17 15:38:50 +030041class TarTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +000042 tarname = tarname
Serhiy Storchaka8b562922013-06-17 15:38:50 +030043 suffix = ''
44 open = io.FileIO
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020045 taropen = tarfile.TarFile.taropen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030046
47 @property
48 def mode(self):
49 return self.prefix + self.suffix
50
51@support.requires_gzip
52class GzipTest:
53 tarname = gzipname
54 suffix = 'gz'
55 open = gzip.GzipFile if gzip else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020056 taropen = tarfile.TarFile.gzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030057
58@support.requires_bz2
59class Bz2Test:
60 tarname = bz2name
61 suffix = 'bz2'
62 open = bz2.BZ2File if bz2 else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020063 taropen = tarfile.TarFile.bz2open
Serhiy Storchaka8b562922013-06-17 15:38:50 +030064
65@support.requires_lzma
66class LzmaTest:
67 tarname = xzname
68 suffix = 'xz'
69 open = lzma.LZMAFile if lzma else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020070 taropen = tarfile.TarFile.xzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030071
72
73class ReadTest(TarTest):
74
75 prefix = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000076
77 def setUp(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +030078 self.tar = tarfile.open(self.tarname, mode=self.mode,
79 encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000080
81 def tearDown(self):
82 self.tar.close()
83
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000084
Serhiy Storchaka8b562922013-06-17 15:38:50 +030085class UstarReadTest(ReadTest, unittest.TestCase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000086
Guido van Rossumd8faa362007-04-27 19:54:29 +000087 def test_fileobj_regular_file(self):
88 tarinfo = self.tar.getmember("ustar/regtype")
Lars Gustäbel7a919e92012-05-05 18:15:03 +020089 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000090 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +030091 self.assertEqual(len(data), tarinfo.size,
92 "regular file extraction failed")
93 self.assertEqual(md5sum(data), md5_regtype,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000094 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000095
Guido van Rossumd8faa362007-04-27 19:54:29 +000096 def test_fileobj_readlines(self):
97 self.tar.extract("ustar/regtype", TEMPDIR)
98 tarinfo = self.tar.getmember("ustar/regtype")
Antoine Pitrou95f55602010-09-23 18:36:46 +000099 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
100 lines1 = fobj1.readlines()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000101
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200102 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000103 fobj2 = io.TextIOWrapper(fobj)
104 lines2 = fobj2.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300105 self.assertEqual(lines1, lines2,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000106 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300107 self.assertEqual(len(lines2), 114,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000108 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300109 self.assertEqual(lines2[83],
110 "I will gladly admit that Python is not the fastest "
111 "running scripting language.\n",
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000112 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000113
Guido van Rossumd8faa362007-04-27 19:54:29 +0000114 def test_fileobj_iter(self):
115 self.tar.extract("ustar/regtype", TEMPDIR)
116 tarinfo = self.tar.getmember("ustar/regtype")
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200117 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000118 lines1 = fobj1.readlines()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200119 with self.tar.extractfile(tarinfo) as fobj2:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000120 lines2 = list(io.TextIOWrapper(fobj2))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300121 self.assertEqual(lines1, lines2,
122 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +0000123
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124 def test_fileobj_seek(self):
125 self.tar.extract("ustar/regtype", TEMPDIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000126 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
127 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +0000128
Guido van Rossumd8faa362007-04-27 19:54:29 +0000129 tarinfo = self.tar.getmember("ustar/regtype")
130 fobj = self.tar.extractfile(tarinfo)
131
132 text = fobj.read()
133 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000134 self.assertEqual(0, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000135 "seek() to file's start failed")
136 fobj.seek(2048, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000137 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000138 "seek() to absolute position failed")
139 fobj.seek(-1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000140 self.assertEqual(1024, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000141 "seek() to negative relative position failed")
142 fobj.seek(1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000143 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000144 "seek() to positive relative position failed")
145 s = fobj.read(10)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300146 self.assertEqual(s, data[2048:2058],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147 "read() after seek failed")
148 fobj.seek(0, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000149 self.assertEqual(tarinfo.size, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000150 "seek() to file's end failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300151 self.assertEqual(fobj.read(), b"",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000152 "read() at file's end did not return empty string")
153 fobj.seek(-tarinfo.size, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000154 self.assertEqual(0, fobj.tell(),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000155 "relative seek() to file's end failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156 fobj.seek(512)
157 s1 = fobj.readlines()
158 fobj.seek(512)
159 s2 = fobj.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300160 self.assertEqual(s1, s2,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161 "readlines() after seek failed")
162 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000163 self.assertEqual(len(fobj.readline()), fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000164 "tell() after readline() failed")
165 fobj.seek(512)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300166 self.assertEqual(len(fobj.readline()) + 512, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000167 "tell() after seek() and readline() failed")
168 fobj.seek(0)
169 line = fobj.readline()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000170 self.assertEqual(fobj.read(), data[len(line):],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000171 "read() after readline() failed")
172 fobj.close()
173
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200174 def test_fileobj_text(self):
175 with self.tar.extractfile("ustar/regtype") as fobj:
176 fobj = io.TextIOWrapper(fobj)
177 data = fobj.read().encode("iso8859-1")
178 self.assertEqual(md5sum(data), md5_regtype)
179 try:
180 fobj.seek(100)
181 except AttributeError:
182 # Issue #13815: seek() complained about a missing
183 # flush() method.
184 self.fail("seeking failed in text mode")
185
Lars Gustäbel1b512722010-06-03 12:45:16 +0000186 # Test if symbolic and hard links are resolved by extractfile(). The
187 # test link members each point to a regular member whose data is
188 # supposed to be exported.
189 def _test_fileobj_link(self, lnktype, regtype):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300190 with self.tar.extractfile(lnktype) as a, \
191 self.tar.extractfile(regtype) as b:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000192 self.assertEqual(a.name, b.name)
Lars Gustäbel1b512722010-06-03 12:45:16 +0000193
194 def test_fileobj_link1(self):
195 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
196
197 def test_fileobj_link2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300198 self._test_fileobj_link("./ustar/linktest2/lnktype",
199 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000200
201 def test_fileobj_symlink1(self):
202 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
203
204 def test_fileobj_symlink2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300205 self._test_fileobj_link("./ustar/linktest2/symtype",
206 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000207
Lars Gustäbel1ef9eda2012-04-24 21:04:40 +0200208 def test_issue14160(self):
209 self._test_fileobj_link("symtype2", "ustar/regtype")
210
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300211class GzipUstarReadTest(GzipTest, UstarReadTest):
212 pass
213
214class Bz2UstarReadTest(Bz2Test, UstarReadTest):
215 pass
216
217class LzmaUstarReadTest(LzmaTest, UstarReadTest):
218 pass
219
Guido van Rossumd8faa362007-04-27 19:54:29 +0000220
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200221class ListTest(ReadTest, unittest.TestCase):
222
223 # Override setUp to use default encoding (UTF-8)
224 def setUp(self):
225 self.tar = tarfile.open(self.tarname, mode=self.mode)
226
227 def test_list(self):
228 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
229 with support.swap_attr(sys, 'stdout', tio):
230 self.tar.list(verbose=False)
231 out = tio.detach().getvalue()
232 self.assertIn(b'ustar/conttype', out)
233 self.assertIn(b'ustar/regtype', out)
234 self.assertIn(b'ustar/lnktype', out)
235 self.assertIn(b'ustar' + (b'/12345' * 40) + b'67/longname', out)
236 self.assertIn(b'./ustar/linktest2/symtype', out)
237 self.assertIn(b'./ustar/linktest2/lnktype', out)
238 # Make sure it puts trailing slash for directory
239 self.assertIn(b'ustar/dirtype/', out)
240 self.assertIn(b'ustar/dirtype-with-size/', out)
241 # Make sure it is able to print unencodable characters
Serhiy Storchaka162c4772014-02-19 18:44:12 +0200242 def conv(b):
243 s = b.decode(self.tar.encoding, 'surrogateescape')
244 return s.encode('ascii', 'backslashreplace')
245 self.assertIn(conv(b'ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
246 self.assertIn(conv(b'misc/regtype-hpux-signed-chksum-'
247 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
248 self.assertIn(conv(b'misc/regtype-old-v7-signed-chksum-'
249 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
250 self.assertIn(conv(b'pax/bad-pax-\xe4\xf6\xfc'), out)
251 self.assertIn(conv(b'pax/hdrcharset-\xe4\xf6\xfc'), out)
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200252 # Make sure it prints files separated by one newline without any
253 # 'ls -l'-like accessories if verbose flag is not being used
254 # ...
255 # ustar/conttype
256 # ustar/regtype
257 # ...
258 self.assertRegex(out, br'ustar/conttype ?\r?\n'
259 br'ustar/regtype ?\r?\n')
260 # Make sure it does not print the source of link without verbose flag
261 self.assertNotIn(b'link to', out)
262 self.assertNotIn(b'->', out)
263
264 def test_list_verbose(self):
265 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
266 with support.swap_attr(sys, 'stdout', tio):
267 self.tar.list(verbose=True)
268 out = tio.detach().getvalue()
269 # Make sure it prints files separated by one newline with 'ls -l'-like
270 # accessories if verbose flag is being used
271 # ...
272 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
273 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
274 # ...
Serhiy Storchaka255493c2014-02-05 20:54:43 +0200275 self.assertRegex(out, (br'\?rw-r--r-- tarfile/tarfile\s+7011 '
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200276 br'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
277 br'ustar/\w+type ?\r?\n') * 2)
278 # Make sure it prints the source of link with verbose flag
279 self.assertIn(b'ustar/symtype -> regtype', out)
280 self.assertIn(b'./ustar/linktest2/symtype -> ../linktest1/regtype', out)
281 self.assertIn(b'./ustar/linktest2/lnktype link to '
282 b'./ustar/linktest1/regtype', out)
283 self.assertIn(b'gnu' + (b'/123' * 125) + b'/longlink link to gnu' +
284 (b'/123' * 125) + b'/longname', out)
285 self.assertIn(b'pax' + (b'/123' * 125) + b'/longlink link to pax' +
286 (b'/123' * 125) + b'/longname', out)
287
288
289class GzipListTest(GzipTest, ListTest):
290 pass
291
292
293class Bz2ListTest(Bz2Test, ListTest):
294 pass
295
296
297class LzmaListTest(LzmaTest, ListTest):
298 pass
299
300
Lars Gustäbel9520a432009-11-22 18:48:49 +0000301class CommonReadTest(ReadTest):
302
303 def test_empty_tarfile(self):
304 # Test for issue6123: Allow opening empty archives.
305 # This test checks if tarfile.open() is able to open an empty tar
306 # archive successfully. Note that an empty tar archive is not the
307 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000308 with tarfile.open(tmpname, self.mode.replace("r", "w")):
309 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000310 try:
311 tar = tarfile.open(tmpname, self.mode)
312 tar.getnames()
313 except tarfile.ReadError:
314 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000315 else:
316 self.assertListEqual(tar.getmembers(), [])
317 finally:
318 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000319
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200320 def test_non_existent_tarfile(self):
321 # Test for issue11513: prevent non-existent gzipped tarfiles raising
322 # multiple exceptions.
323 with self.assertRaisesRegex(FileNotFoundError, "xxx"):
324 tarfile.open("xxx", self.mode)
325
Lars Gustäbel9520a432009-11-22 18:48:49 +0000326 def test_null_tarfile(self):
327 # Test for issue6123: Allow opening empty archives.
328 # This test guarantees that tarfile.open() does not treat an empty
329 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000330 with open(tmpname, "wb"):
331 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000332 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
333 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
334
335 def test_ignore_zeros(self):
336 # Test TarFile's ignore_zeros option.
Lars Gustäbel9520a432009-11-22 18:48:49 +0000337 for char in (b'\0', b'a'):
338 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
339 # are ignored correctly.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300340 with self.open(tmpname, "w") as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000341 fobj.write(char * 1024)
342 fobj.write(tarfile.TarInfo("foo").tobuf())
Lars Gustäbel9520a432009-11-22 18:48:49 +0000343
344 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000345 try:
346 self.assertListEqual(tar.getnames(), ["foo"],
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300347 "ignore_zeros=True should have skipped the %r-blocks" %
348 char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000349 finally:
350 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000351
Lars Gustäbel03572682015-07-06 09:27:24 +0200352 def test_premature_end_of_archive(self):
353 for size in (512, 600, 1024, 1200):
354 with tarfile.open(tmpname, "w:") as tar:
355 t = tarfile.TarInfo("foo")
356 t.size = 1024
357 tar.addfile(t, io.BytesIO(b"a" * 1024))
358
359 with open(tmpname, "r+b") as fobj:
360 fobj.truncate(size)
361
362 with tarfile.open(tmpname) as tar:
363 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
364 for t in tar:
365 pass
366
367 with tarfile.open(tmpname) as tar:
368 t = tar.next()
369
370 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
371 tar.extract(t, TEMPDIR)
372
373 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
374 tar.extractfile(t).read()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000375
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300376class MiscReadTestBase(CommonReadTest):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300377 def requires_name_attribute(self):
378 pass
379
Thomas Woutersed03b412007-08-28 21:37:11 +0000380 def test_no_name_argument(self):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300381 self.requires_name_attribute()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000382 with open(self.tarname, "rb") as fobj:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300383 self.assertIsInstance(fobj.name, str)
384 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
385 self.assertIsInstance(tar.name, str)
386 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000387
Thomas Woutersed03b412007-08-28 21:37:11 +0000388 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000389 with open(self.tarname, "rb") as fobj:
390 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000391 fobj = io.BytesIO(data)
392 self.assertRaises(AttributeError, getattr, fobj, "name")
393 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300394 self.assertIsNone(tar.name)
Thomas Woutersed03b412007-08-28 21:37:11 +0000395
396 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000397 with open(self.tarname, "rb") as fobj:
398 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000399 fobj = io.BytesIO(data)
400 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000401 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300402 self.assertIsNone(tar.name)
403
404 def test_int_name_attribute(self):
405 # Issue 21044: tarfile.open() should handle fileobj with an integer
406 # 'name' attribute.
407 fd = os.open(self.tarname, os.O_RDONLY)
408 with open(fd, 'rb') as fobj:
409 self.assertIsInstance(fobj.name, int)
410 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
411 self.assertIsNone(tar.name)
412
413 def test_bytes_name_attribute(self):
414 self.requires_name_attribute()
415 tarname = os.fsencode(self.tarname)
416 with open(tarname, 'rb') as fobj:
417 self.assertIsInstance(fobj.name, bytes)
418 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
419 self.assertIsInstance(tar.name, bytes)
420 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Thomas Woutersed03b412007-08-28 21:37:11 +0000421
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +0200422 def test_illegal_mode_arg(self):
423 with open(tmpname, 'wb'):
424 pass
425 with self.assertRaisesRegex(ValueError, 'mode must be '):
426 tar = self.taropen(tmpname, 'q')
427 with self.assertRaisesRegex(ValueError, 'mode must be '):
428 tar = self.taropen(tmpname, 'rw')
429 with self.assertRaisesRegex(ValueError, 'mode must be '):
430 tar = self.taropen(tmpname, '')
431
Christian Heimesd8654cf2007-12-02 15:22:16 +0000432 def test_fileobj_with_offset(self):
433 # Skip the first member and store values from the second member
434 # of the testtar.
435 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000436 try:
437 tar.next()
438 t = tar.next()
439 name = t.name
440 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200441 with tar.extractfile(t) as f:
442 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000443 finally:
444 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000445
446 # Open the testtar and seek to the offset of the second member.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300447 with self.open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000448 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000449
Antoine Pitrou95f55602010-09-23 18:36:46 +0000450 # Test if the tarfile starts with the second member.
451 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
452 t = tar.next()
453 self.assertEqual(t.name, name)
454 # Read to the end of fileobj and test if seeking back to the
455 # beginning works.
456 tar.getmembers()
457 self.assertEqual(tar.extractfile(t).read(), data,
458 "seek back did not work")
459 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000460
Guido van Rossumd8faa362007-04-27 19:54:29 +0000461 def test_fail_comp(self):
462 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000463 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000464 with open(tarname, "rb") as fobj:
465 self.assertRaises(tarfile.ReadError, tarfile.open,
466 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000467
468 def test_v7_dirtype(self):
469 # Test old style dirtype member (bug #1336623):
470 # Old V7 tars create directory members using an AREGTYPE
471 # header with a "/" appended to the filename field.
472 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300473 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000474 "v7 dirtype failed")
475
Christian Heimes126d29a2008-02-11 22:57:17 +0000476 def test_xstar_type(self):
477 # The xstar format stores extra atime and ctime fields inside the
478 # space reserved for the prefix field. The prefix field must be
479 # ignored in this case, otherwise it will mess up the name.
480 try:
481 self.tar.getmember("misc/regtype-xstar")
482 except KeyError:
483 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
484
Guido van Rossumd8faa362007-04-27 19:54:29 +0000485 def test_check_members(self):
486 for tarinfo in self.tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300487 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000488 "wrong mtime for %s" % tarinfo.name)
489 if not tarinfo.name.startswith("ustar/"):
490 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300491 self.assertEqual(tarinfo.uname, "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000492 "wrong uname for %s" % tarinfo.name)
493
494 def test_find_members(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300495 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000496 "could not find all members")
497
Brian Curtin74e45612010-07-09 15:58:59 +0000498 @unittest.skipUnless(hasattr(os, "link"),
499 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000500 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 def test_extract_hardlink(self):
502 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200503 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000504 tar.extract("ustar/regtype", TEMPDIR)
Victor Stinner57004c62014-09-04 00:49:01 +0200505 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000506
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200507 tar.extract("ustar/lnktype", TEMPDIR)
Victor Stinner57004c62014-09-04 00:49:01 +0200508 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000509 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
510 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000511 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000512
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200513 tar.extract("ustar/symtype", TEMPDIR)
Victor Stinner57004c62014-09-04 00:49:01 +0200514 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000515 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
516 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000517 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518
Christian Heimesfaf2f632008-01-06 16:59:19 +0000519 def test_extractall(self):
520 # Test if extractall() correctly restores directory permissions
521 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000522 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000523 DIR = os.path.join(TEMPDIR, "extractall")
524 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000525 try:
526 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000527 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000528 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000529 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000530 if sys.platform != "win32":
531 # Win32 has no support for fine grained permissions.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300532 self.assertEqual(tarinfo.mode & 0o777,
533 os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000534 def format_mtime(mtime):
535 if isinstance(mtime, float):
536 return "{} ({})".format(mtime, mtime.hex())
537 else:
538 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000539 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000540 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
541 format_mtime(tarinfo.mtime),
542 format_mtime(file_mtime),
543 path)
544 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000545 finally:
546 tar.close()
Victor Stinner57004c62014-09-04 00:49:01 +0200547 support.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000548
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000549 def test_extract_directory(self):
550 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000551 DIR = os.path.join(TEMPDIR, "extractdir")
552 os.mkdir(DIR)
553 try:
554 with tarfile.open(tarname, encoding="iso8859-1") as tar:
555 tarinfo = tar.getmember(dirtype)
556 tar.extract(tarinfo, path=DIR)
557 extracted = os.path.join(DIR, dirtype)
558 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
559 if sys.platform != "win32":
560 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
561 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200562 support.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000563
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000564 def test_init_close_fobj(self):
565 # Issue #7341: Close the internal file object in the TarFile
566 # constructor in case of an error. For the test we rely on
567 # the fact that opening an empty file raises a ReadError.
568 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000569 with open(empty, "wb") as fobj:
570 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000571
572 try:
573 tar = object.__new__(tarfile.TarFile)
574 try:
575 tar.__init__(empty)
576 except tarfile.ReadError:
577 self.assertTrue(tar.fileobj.closed)
578 else:
579 self.fail("ReadError not raised")
580 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000581 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000582
Serhiy Storchaka263fab92013-05-09 14:22:26 +0300583 def test_parallel_iteration(self):
584 # Issue #16601: Restarting iteration over tarfile continued
585 # from where it left off.
586 with tarfile.open(self.tarname) as tar:
587 for m1, m2 in zip(tar, tar):
588 self.assertEqual(m1.offset, m2.offset)
589 self.assertEqual(m1.get_info(), m2.get_info())
590
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300591class MiscReadTest(MiscReadTestBase, unittest.TestCase):
592 test_fail_comp = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000593
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300594class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200595 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000596
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300597class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300598 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300599 self.skipTest("BZ2File have no name attribute")
600
601class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300602 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300603 self.skipTest("LZMAFile have no name attribute")
604
605
606class StreamReadTest(CommonReadTest, unittest.TestCase):
607
608 prefix="r|"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000609
Lars Gustäbeldd071042011-02-23 11:42:22 +0000610 def test_read_through(self):
611 # Issue #11224: A poorly designed _FileInFile.read() method
612 # caused seeking errors with stream tar files.
613 for tarinfo in self.tar:
614 if not tarinfo.isreg():
615 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200616 with self.tar.extractfile(tarinfo) as fobj:
617 while True:
618 try:
619 buf = fobj.read(512)
620 except tarfile.StreamError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300621 self.fail("simple read-through using "
622 "TarFile.extractfile() failed")
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200623 if not buf:
624 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000625
Guido van Rossumd8faa362007-04-27 19:54:29 +0000626 def test_fileobj_regular_file(self):
627 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200628 with self.tar.extractfile(tarinfo) as fobj:
629 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300630 self.assertEqual(len(data), tarinfo.size,
631 "regular file extraction failed")
632 self.assertEqual(md5sum(data), md5_regtype,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633 "regular file extraction failed")
634
635 def test_provoke_stream_error(self):
636 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200637 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
638 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000639
Guido van Rossumd8faa362007-04-27 19:54:29 +0000640 def test_compare_members(self):
641 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000642 try:
643 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000644
Antoine Pitrou95f55602010-09-23 18:36:46 +0000645 while True:
646 t1 = tar1.next()
647 t2 = tar2.next()
648 if t1 is None:
649 break
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300650 self.assertIsNotNone(t2, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000651
Antoine Pitrou95f55602010-09-23 18:36:46 +0000652 if t2.islnk() or t2.issym():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300653 with self.assertRaises(tarfile.StreamError):
654 tar2.extractfile(t2)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000655 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000656
Antoine Pitrou95f55602010-09-23 18:36:46 +0000657 v1 = tar1.extractfile(t1)
658 v2 = tar2.extractfile(t2)
659 if v1 is None:
660 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300661 self.assertIsNotNone(v2, "stream.extractfile() failed")
662 self.assertEqual(v1.read(), v2.read(),
663 "stream extraction failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000664 finally:
665 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000666
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300667class GzipStreamReadTest(GzipTest, StreamReadTest):
668 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000669
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300670class Bz2StreamReadTest(Bz2Test, StreamReadTest):
671 pass
Thomas Wouterscf297e42007-02-23 15:07:44 +0000672
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300673class LzmaStreamReadTest(LzmaTest, StreamReadTest):
674 pass
675
676
677class DetectReadTest(TarTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000678 def _testfunc_file(self, name, mode):
679 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000680 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000681 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000682 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000683 else:
684 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000685
Guido van Rossumd8faa362007-04-27 19:54:29 +0000686 def _testfunc_fileobj(self, name, mode):
687 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000688 with open(name, "rb") as f:
689 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000690 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000692 else:
693 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000694
695 def _test_modes(self, testfunc):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300696 if self.suffix:
697 with self.assertRaises(tarfile.ReadError):
698 tarfile.open(tarname, mode="r:" + self.suffix)
699 with self.assertRaises(tarfile.ReadError):
700 tarfile.open(tarname, mode="r|" + self.suffix)
701 with self.assertRaises(tarfile.ReadError):
702 tarfile.open(self.tarname, mode="r:")
703 with self.assertRaises(tarfile.ReadError):
704 tarfile.open(self.tarname, mode="r|")
705 testfunc(self.tarname, "r")
706 testfunc(self.tarname, "r:" + self.suffix)
707 testfunc(self.tarname, "r:*")
708 testfunc(self.tarname, "r|" + self.suffix)
709 testfunc(self.tarname, "r|*")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100710
Guido van Rossumd8faa362007-04-27 19:54:29 +0000711 def test_detect_file(self):
712 self._test_modes(self._testfunc_file)
713
714 def test_detect_fileobj(self):
715 self._test_modes(self._testfunc_fileobj)
716
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300717class GzipDetectReadTest(GzipTest, DetectReadTest):
718 pass
719
720class Bz2DetectReadTest(Bz2Test, DetectReadTest):
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100721 def test_detect_stream_bz2(self):
722 # Originally, tarfile's stream detection looked for the string
723 # "BZh91" at the start of the file. This is incorrect because
724 # the '9' represents the blocksize (900kB). If the file was
725 # compressed using another blocksize autodetection fails.
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100726 with open(tarname, "rb") as fobj:
727 data = fobj.read()
728
729 # Compress with blocksize 100kB, the file starts with "BZh11".
730 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
731 fobj.write(data)
732
733 self._testfunc_file(tmpname, "r|*")
734
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300735class LzmaDetectReadTest(LzmaTest, DetectReadTest):
736 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300738
739class MemberReadTest(ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000740
741 def _test_member(self, tarinfo, chksum=None, **kwargs):
742 if chksum is not None:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300743 with self.tar.extractfile(tarinfo) as f:
744 self.assertEqual(md5sum(f.read()), chksum,
745 "wrong md5sum for %s" % tarinfo.name)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000746
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000747 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000748 kwargs["uid"] = 1000
749 kwargs["gid"] = 100
750 if "old-v7" not in tarinfo.name:
751 # V7 tar can't handle alphabetic owners.
752 kwargs["uname"] = "tarfile"
753 kwargs["gname"] = "tarfile"
754 for k, v in kwargs.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300755 self.assertEqual(getattr(tarinfo, k), v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756 "wrong value in %s field of %s" % (k, tarinfo.name))
757
758 def test_find_regtype(self):
759 tarinfo = self.tar.getmember("ustar/regtype")
760 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
761
762 def test_find_conttype(self):
763 tarinfo = self.tar.getmember("ustar/conttype")
764 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
765
766 def test_find_dirtype(self):
767 tarinfo = self.tar.getmember("ustar/dirtype")
768 self._test_member(tarinfo, size=0)
769
770 def test_find_dirtype_with_size(self):
771 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
772 self._test_member(tarinfo, size=255)
773
774 def test_find_lnktype(self):
775 tarinfo = self.tar.getmember("ustar/lnktype")
776 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
777
778 def test_find_symtype(self):
779 tarinfo = self.tar.getmember("ustar/symtype")
780 self._test_member(tarinfo, size=0, linkname="regtype")
781
782 def test_find_blktype(self):
783 tarinfo = self.tar.getmember("ustar/blktype")
784 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
785
786 def test_find_chrtype(self):
787 tarinfo = self.tar.getmember("ustar/chrtype")
788 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
789
790 def test_find_fifotype(self):
791 tarinfo = self.tar.getmember("ustar/fifotype")
792 self._test_member(tarinfo, size=0)
793
794 def test_find_sparse(self):
795 tarinfo = self.tar.getmember("ustar/sparse")
796 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
797
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000798 def test_find_gnusparse(self):
799 tarinfo = self.tar.getmember("gnu/sparse")
800 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
801
802 def test_find_gnusparse_00(self):
803 tarinfo = self.tar.getmember("gnu/sparse-0.0")
804 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
805
806 def test_find_gnusparse_01(self):
807 tarinfo = self.tar.getmember("gnu/sparse-0.1")
808 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
809
810 def test_find_gnusparse_10(self):
811 tarinfo = self.tar.getmember("gnu/sparse-1.0")
812 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
813
Guido van Rossumd8faa362007-04-27 19:54:29 +0000814 def test_find_umlauts(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300815 tarinfo = self.tar.getmember("ustar/umlauts-"
816 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000817 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
818
819 def test_find_ustar_longname(self):
820 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000821 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000822
823 def test_find_regtype_oldv7(self):
824 tarinfo = self.tar.getmember("misc/regtype-old-v7")
825 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
826
827 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000828 self.tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300829 self.tar = tarfile.open(self.tarname, mode=self.mode,
830 encoding="iso8859-1")
831 tarinfo = self.tar.getmember("pax/umlauts-"
832 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000833 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
834
835
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300836class LongnameTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000837
838 def test_read_longname(self):
839 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000840 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000841 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000842 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000843 except KeyError:
844 self.fail("longname not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300845 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
846 "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000847
848 def test_read_longlink(self):
849 longname = self.subdir + "/" + "123/" * 125 + "longname"
850 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
851 try:
852 tarinfo = self.tar.getmember(longlink)
853 except KeyError:
854 self.fail("longlink not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300855 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000856
857 def test_truncated_longname(self):
858 longname = self.subdir + "/" + "123/" * 125 + "longname"
859 tarinfo = self.tar.getmember(longname)
860 offset = tarinfo.offset
861 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000862 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300863 with self.assertRaises(tarfile.ReadError):
864 tarfile.open(name="foo.tar", fileobj=fobj)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000865
Guido van Rossume7ba4952007-06-06 23:52:48 +0000866 def test_header_offset(self):
867 # Test if the start offset of the TarInfo object includes
868 # the preceding extended header.
869 longname = self.subdir + "/" + "123/" * 125 + "longname"
870 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000871 with open(tarname, "rb") as fobj:
872 fobj.seek(offset)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300873 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
874 "iso8859-1", "strict")
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000875 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000876
Guido van Rossumd8faa362007-04-27 19:54:29 +0000877
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300878class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000879
880 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000881 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000882
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000883 # Since 3.2 tarfile is supposed to accurately restore sparse members and
884 # produce files with holes. This is what we actually want to test here.
885 # Unfortunately, not all platforms/filesystems support sparse files, and
886 # even on platforms that do it is non-trivial to make reliable assertions
887 # about holes in files. Therefore, we first do one basic test which works
888 # an all platforms, and after that a test that will work only on
889 # platforms/filesystems that prove to support sparse files.
890 def _test_sparse_file(self, name):
891 self.tar.extract(name, TEMPDIR)
892 filename = os.path.join(TEMPDIR, name)
893 with open(filename, "rb") as fobj:
894 data = fobj.read()
895 self.assertEqual(md5sum(data), md5_sparse,
896 "wrong md5sum for %s" % name)
897
898 if self._fs_supports_holes():
899 s = os.stat(filename)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300900 self.assertLess(s.st_blocks * 512, s.st_size)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000901
902 def test_sparse_file_old(self):
903 self._test_sparse_file("gnu/sparse")
904
905 def test_sparse_file_00(self):
906 self._test_sparse_file("gnu/sparse-0.0")
907
908 def test_sparse_file_01(self):
909 self._test_sparse_file("gnu/sparse-0.1")
910
911 def test_sparse_file_10(self):
912 self._test_sparse_file("gnu/sparse-1.0")
913
914 @staticmethod
915 def _fs_supports_holes():
916 # Return True if the platform knows the st_blocks stat attribute and
917 # uses st_blocks units of 512 bytes, and if the filesystem is able to
918 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200919 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000920 # Linux evidentially has 512 byte st_blocks units.
921 name = os.path.join(TEMPDIR, "sparse-test")
922 with open(name, "wb") as fobj:
923 fobj.seek(4096)
924 fobj.truncate()
925 s = os.stat(name)
Victor Stinner57004c62014-09-04 00:49:01 +0200926 support.unlink(name)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000927 return s.st_blocks == 0
928 else:
929 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000930
931
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300932class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000933
934 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000935 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000936
Guido van Rossume7ba4952007-06-06 23:52:48 +0000937 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000938 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000939 try:
940 tarinfo = tar.getmember("pax/regtype1")
941 self.assertEqual(tarinfo.uname, "foo")
942 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300943 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
944 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000945
Antoine Pitrou95f55602010-09-23 18:36:46 +0000946 tarinfo = tar.getmember("pax/regtype2")
947 self.assertEqual(tarinfo.uname, "")
948 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300949 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
950 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951
Antoine Pitrou95f55602010-09-23 18:36:46 +0000952 tarinfo = tar.getmember("pax/regtype3")
953 self.assertEqual(tarinfo.uname, "tarfile")
954 self.assertEqual(tarinfo.gname, "tarfile")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300955 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
956 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000957 finally:
958 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000959
960 def test_pax_number_fields(self):
961 # All following number fields are read from the pax header.
962 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000963 try:
964 tarinfo = tar.getmember("pax/regtype4")
965 self.assertEqual(tarinfo.size, 7011)
966 self.assertEqual(tarinfo.uid, 123)
967 self.assertEqual(tarinfo.gid, 123)
968 self.assertEqual(tarinfo.mtime, 1041808783.0)
969 self.assertEqual(type(tarinfo.mtime), float)
970 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
971 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
972 finally:
973 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000974
975
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300976class WriteTestBase(TarTest):
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000977 # Put all write tests in here that are supposed to be tested
978 # in all possible mode combinations.
979
980 def test_fileobj_no_close(self):
981 fobj = io.BytesIO()
982 tar = tarfile.open(fileobj=fobj, mode=self.mode)
983 tar.addfile(tarfile.TarInfo("foo"))
984 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300985 self.assertFalse(fobj.closed, "external fileobjs must never closed")
Serhiy Storchaka9fbec7a2014-01-18 15:53:05 +0200986 # Issue #20238: Incomplete gzip output with mode="w:gz"
987 data = fobj.getvalue()
988 del tar
989 support.gc_collect()
990 self.assertFalse(fobj.closed)
991 self.assertEqual(data, fobj.getvalue())
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000992
993
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300994class WriteTest(WriteTestBase, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000995
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300996 prefix = "w:"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000997
998 def test_100_char_name(self):
999 # The name field in a tar header stores strings of at most 100 chars.
1000 # If a string is shorter than 100 chars it has to be padded with '\0',
1001 # which implies that a string of exactly 100 chars is stored without
1002 # a trailing '\0'.
1003 name = "0123456789" * 10
1004 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001005 try:
1006 t = tarfile.TarInfo(name)
1007 tar.addfile(t)
1008 finally:
1009 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +00001010
Guido van Rossumd8faa362007-04-27 19:54:29 +00001011 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001012 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001013 self.assertEqual(tar.getnames()[0], name,
Antoine Pitrou95f55602010-09-23 18:36:46 +00001014 "failed to store 100 char filename")
1015 finally:
1016 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001017
Guido van Rossumd8faa362007-04-27 19:54:29 +00001018 def test_tar_size(self):
1019 # Test for bug #1013882.
1020 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001021 try:
1022 path = os.path.join(TEMPDIR, "file")
1023 with open(path, "wb") as fobj:
1024 fobj.write(b"aaa")
1025 tar.add(path)
1026 finally:
1027 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001028 self.assertGreater(os.path.getsize(tmpname), 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001030
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031 # The test_*_size tests test for bug #1167128.
1032 def test_file_size(self):
1033 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001034 try:
1035 path = os.path.join(TEMPDIR, "file")
1036 with open(path, "wb"):
1037 pass
1038 tarinfo = tar.gettarinfo(path)
1039 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001040
Antoine Pitrou95f55602010-09-23 18:36:46 +00001041 with open(path, "wb") as fobj:
1042 fobj.write(b"aaa")
1043 tarinfo = tar.gettarinfo(path)
1044 self.assertEqual(tarinfo.size, 3)
1045 finally:
1046 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001047
1048 def test_directory_size(self):
1049 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001050 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001051 try:
1052 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001053 try:
1054 tarinfo = tar.gettarinfo(path)
1055 self.assertEqual(tarinfo.size, 0)
1056 finally:
1057 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001058 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001059 support.rmdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001060
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001061 @unittest.skipUnless(hasattr(os, "link"),
1062 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001063 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001064 link = os.path.join(TEMPDIR, "link")
1065 target = os.path.join(TEMPDIR, "link_target")
1066 with open(target, "wb") as fobj:
1067 fobj.write(b"aaa")
1068 os.link(target, link)
1069 try:
1070 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001071 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001072 # Record the link target in the inodes list.
1073 tar.gettarinfo(target)
1074 tarinfo = tar.gettarinfo(link)
1075 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001077 tar.close()
1078 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001079 support.unlink(target)
1080 support.unlink(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001081
Brian Curtin3b4499c2010-12-28 14:31:47 +00001082 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +00001083 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +00001084 path = os.path.join(TEMPDIR, "symlink")
1085 os.symlink("link_target", path)
1086 try:
1087 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001088 try:
1089 tarinfo = tar.gettarinfo(path)
1090 self.assertEqual(tarinfo.size, 0)
1091 finally:
1092 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +00001093 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001094 support.unlink(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001095
1096 def test_add_self(self):
1097 # Test for #1257255.
1098 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001099 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001100 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001101 self.assertEqual(tar.name, dstname,
1102 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001103 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001104 self.assertEqual(tar.getnames(), [],
1105 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001106
Antoine Pitrou95f55602010-09-23 18:36:46 +00001107 cwd = os.getcwd()
1108 os.chdir(TEMPDIR)
1109 tar.add(dstname)
1110 os.chdir(cwd)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001111 self.assertEqual(tar.getnames(), [],
1112 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001113 finally:
1114 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001115
Guido van Rossum486364b2007-06-30 05:01:58 +00001116 def test_exclude(self):
1117 tempdir = os.path.join(TEMPDIR, "exclude")
1118 os.mkdir(tempdir)
1119 try:
1120 for name in ("foo", "bar", "baz"):
1121 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001122 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +00001123
Benjamin Peterson886af962010-03-21 23:13:07 +00001124 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +00001125
1126 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001127 try:
1128 with support.check_warnings(("use the filter argument",
1129 DeprecationWarning)):
1130 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
1131 finally:
1132 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001133
1134 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001135 try:
1136 self.assertEqual(len(tar.getmembers()), 1)
1137 self.assertEqual(tar.getnames()[0], "empty_dir")
1138 finally:
1139 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001140 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001141 support.rmtree(tempdir)
Guido van Rossum486364b2007-06-30 05:01:58 +00001142
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001143 def test_filter(self):
1144 tempdir = os.path.join(TEMPDIR, "filter")
1145 os.mkdir(tempdir)
1146 try:
1147 for name in ("foo", "bar", "baz"):
1148 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001149 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001150
1151 def filter(tarinfo):
1152 if os.path.basename(tarinfo.name) == "bar":
1153 return
1154 tarinfo.uid = 123
1155 tarinfo.uname = "foo"
1156 return tarinfo
1157
1158 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001159 try:
1160 tar.add(tempdir, arcname="empty_dir", filter=filter)
1161 finally:
1162 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001163
Raymond Hettingera63a3122011-01-26 20:34:14 +00001164 # Verify that filter is a keyword-only argument
1165 with self.assertRaises(TypeError):
1166 tar.add(tempdir, "empty_dir", True, None, filter)
1167
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001168 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001169 try:
1170 for tarinfo in tar:
1171 self.assertEqual(tarinfo.uid, 123)
1172 self.assertEqual(tarinfo.uname, "foo")
1173 self.assertEqual(len(tar.getmembers()), 3)
1174 finally:
1175 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001176 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001177 support.rmtree(tempdir)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001178
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001179 # Guarantee that stored pathnames are not modified. Don't
1180 # remove ./ or ../ or double slashes. Still make absolute
1181 # pathnames relative.
1182 # For details see bug #6054.
1183 def _test_pathname(self, path, cmp_path=None, dir=False):
1184 # Create a tarfile with an empty member named path
1185 # and compare the stored name with the original.
1186 foo = os.path.join(TEMPDIR, "foo")
1187 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001188 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001189 else:
1190 os.mkdir(foo)
1191
1192 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001193 try:
1194 tar.add(foo, arcname=path)
1195 finally:
1196 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001197
1198 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001199 try:
1200 t = tar.next()
1201 finally:
1202 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001203
1204 if not dir:
Victor Stinner57004c62014-09-04 00:49:01 +02001205 support.unlink(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001206 else:
Victor Stinner57004c62014-09-04 00:49:01 +02001207 support.rmdir(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001208
1209 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1210
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001211
1212 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001213 def test_extractall_symlinks(self):
1214 # Test if extractall works properly when tarfile contains symlinks
1215 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1216 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1217 os.mkdir(tempdir)
1218 try:
1219 source_file = os.path.join(tempdir,'source')
1220 target_file = os.path.join(tempdir,'symlink')
1221 with open(source_file,'w') as f:
1222 f.write('something\n')
1223 os.symlink(source_file, target_file)
1224 tar = tarfile.open(temparchive,'w')
1225 tar.add(source_file)
1226 tar.add(target_file)
1227 tar.close()
1228 # Let's extract it to the location which contains the symlink
1229 tar = tarfile.open(temparchive,'r')
1230 # this should not raise OSError: [Errno 17] File exists
1231 try:
1232 tar.extractall(path=tempdir)
1233 except OSError:
1234 self.fail("extractall failed with symlinked files")
1235 finally:
1236 tar.close()
1237 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001238 support.unlink(temparchive)
1239 support.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001240
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001241 def test_pathnames(self):
1242 self._test_pathname("foo")
1243 self._test_pathname(os.path.join("foo", ".", "bar"))
1244 self._test_pathname(os.path.join("foo", "..", "bar"))
1245 self._test_pathname(os.path.join(".", "foo"))
1246 self._test_pathname(os.path.join(".", "foo", "."))
1247 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1248 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1249 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1250 self._test_pathname(os.path.join("..", "foo"))
1251 self._test_pathname(os.path.join("..", "foo", ".."))
1252 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1253 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1254
1255 self._test_pathname("foo" + os.sep + os.sep + "bar")
1256 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1257
1258 def test_abs_pathnames(self):
1259 if sys.platform == "win32":
1260 self._test_pathname("C:\\foo", "foo")
1261 else:
1262 self._test_pathname("/foo", "foo")
1263 self._test_pathname("///foo", "foo")
1264
1265 def test_cwd(self):
1266 # Test adding the current working directory.
1267 cwd = os.getcwd()
1268 os.chdir(TEMPDIR)
1269 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001270 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001271 try:
1272 tar.add(".")
1273 finally:
1274 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001275
1276 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001277 try:
1278 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001279 if t.name != ".":
1280 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001281 finally:
1282 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001283 finally:
1284 os.chdir(cwd)
1285
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001286 def test_open_nonwritable_fileobj(self):
1287 for exctype in OSError, EOFError, RuntimeError:
1288 class BadFile(io.BytesIO):
1289 first = True
1290 def write(self, data):
1291 if self.first:
1292 self.first = False
1293 raise exctype
1294
1295 f = BadFile()
1296 with self.assertRaises(exctype):
1297 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1298 format=tarfile.PAX_FORMAT,
1299 pax_headers={'non': 'empty'})
1300 self.assertFalse(f.closed)
1301
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001302class GzipWriteTest(GzipTest, WriteTest):
1303 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001304
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001305class Bz2WriteTest(Bz2Test, WriteTest):
1306 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001307
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001308class LzmaWriteTest(LzmaTest, WriteTest):
1309 pass
1310
1311
1312class StreamWriteTest(WriteTestBase, unittest.TestCase):
1313
1314 prefix = "w|"
1315 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001316
Guido van Rossumd8faa362007-04-27 19:54:29 +00001317 def test_stream_padding(self):
1318 # Test for bug #1543303.
1319 tar = tarfile.open(tmpname, self.mode)
1320 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001321 if self.decompressor:
1322 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001323 with open(tmpname, "rb") as fobj:
1324 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001325 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001326 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001327 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001328 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001329 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001330 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1331 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001332
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001333 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1334 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001335 def test_file_mode(self):
1336 # Test for issue #8464: Create files with correct
1337 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001338 if os.path.exists(tmpname):
Victor Stinner57004c62014-09-04 00:49:01 +02001339 support.unlink(tmpname)
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001340
1341 original_umask = os.umask(0o022)
1342 try:
1343 tar = tarfile.open(tmpname, self.mode)
1344 tar.close()
1345 mode = os.stat(tmpname).st_mode & 0o777
1346 self.assertEqual(mode, 0o644, "wrong file permissions")
1347 finally:
1348 os.umask(original_umask)
1349
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001350class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1351 pass
1352
1353class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1354 decompressor = bz2.BZ2Decompressor if bz2 else None
1355
1356class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1357 decompressor = lzma.LZMADecompressor if lzma else None
1358
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001359
Guido van Rossumd8faa362007-04-27 19:54:29 +00001360class GNUWriteTest(unittest.TestCase):
1361 # This testcase checks for correct creation of GNU Longname
1362 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001363
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001364 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001365 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001366 return blocks * 512
1367
1368 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001369 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001370 count = 512
1371
1372 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001373 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001374 count += 512
1375 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001376 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001377 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001378 count += 512
1379 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001380 return count
1381
1382 def _test(self, name, link=None):
1383 tarinfo = tarfile.TarInfo(name)
1384 if link:
1385 tarinfo.linkname = link
1386 tarinfo.type = tarfile.LNKTYPE
1387
Guido van Rossumd8faa362007-04-27 19:54:29 +00001388 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001389 try:
1390 tar.format = tarfile.GNU_FORMAT
1391 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001392
Antoine Pitrou95f55602010-09-23 18:36:46 +00001393 v1 = self._calc_size(name, link)
1394 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001395 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001396 finally:
1397 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001398
Guido van Rossumd8faa362007-04-27 19:54:29 +00001399 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001400 try:
1401 member = tar.next()
1402 self.assertIsNotNone(member,
1403 "unable to read longname member")
1404 self.assertEqual(tarinfo.name, member.name,
1405 "unable to read longname member")
1406 self.assertEqual(tarinfo.linkname, member.linkname,
1407 "unable to read longname member")
1408 finally:
1409 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001410
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001411 def test_longname_1023(self):
1412 self._test(("longnam/" * 127) + "longnam")
1413
1414 def test_longname_1024(self):
1415 self._test(("longnam/" * 127) + "longname")
1416
1417 def test_longname_1025(self):
1418 self._test(("longnam/" * 127) + "longname_")
1419
1420 def test_longlink_1023(self):
1421 self._test("name", ("longlnk/" * 127) + "longlnk")
1422
1423 def test_longlink_1024(self):
1424 self._test("name", ("longlnk/" * 127) + "longlink")
1425
1426 def test_longlink_1025(self):
1427 self._test("name", ("longlnk/" * 127) + "longlink_")
1428
1429 def test_longnamelink_1023(self):
1430 self._test(("longnam/" * 127) + "longnam",
1431 ("longlnk/" * 127) + "longlnk")
1432
1433 def test_longnamelink_1024(self):
1434 self._test(("longnam/" * 127) + "longname",
1435 ("longlnk/" * 127) + "longlink")
1436
1437 def test_longnamelink_1025(self):
1438 self._test(("longnam/" * 127) + "longname_",
1439 ("longlnk/" * 127) + "longlink_")
1440
Guido van Rossumd8faa362007-04-27 19:54:29 +00001441
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001442@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001443class HardlinkTest(unittest.TestCase):
1444 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001445
1446 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001447 self.foo = os.path.join(TEMPDIR, "foo")
1448 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001449
Antoine Pitrou95f55602010-09-23 18:36:46 +00001450 with open(self.foo, "wb") as fobj:
1451 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001452
Guido van Rossumd8faa362007-04-27 19:54:29 +00001453 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001454
Guido van Rossumd8faa362007-04-27 19:54:29 +00001455 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001456 self.tar.add(self.foo)
1457
Guido van Rossumd8faa362007-04-27 19:54:29 +00001458 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001459 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001460 support.unlink(self.foo)
1461 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001462
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001463 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001464 # The same name will be added as a REGTYPE every
1465 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001466 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001467 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001468 "add file as regular failed")
1469
1470 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001471 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001472 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001473 "add file as hardlink failed")
1474
1475 def test_dereference_hardlink(self):
1476 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001477 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001478 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001479 "dereferencing hardlink failed")
1480
Neal Norwitza4f651a2004-07-20 22:07:44 +00001481
Guido van Rossumd8faa362007-04-27 19:54:29 +00001482class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001483
Guido van Rossumd8faa362007-04-27 19:54:29 +00001484 def _test(self, name, link=None):
1485 # See GNUWriteTest.
1486 tarinfo = tarfile.TarInfo(name)
1487 if link:
1488 tarinfo.linkname = link
1489 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001490
Guido van Rossumd8faa362007-04-27 19:54:29 +00001491 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001492 try:
1493 tar.addfile(tarinfo)
1494 finally:
1495 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001496
Guido van Rossumd8faa362007-04-27 19:54:29 +00001497 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001498 try:
1499 if link:
1500 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001501 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001502 else:
1503 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001504 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001505 finally:
1506 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001507
Guido van Rossume7ba4952007-06-06 23:52:48 +00001508 def test_pax_global_header(self):
1509 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001510 "foo": "bar",
1511 "uid": "0",
1512 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001513 "test": "\xe4\xf6\xfc",
1514 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001515
Benjamin Peterson886af962010-03-21 23:13:07 +00001516 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001517 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001518 try:
1519 tar.addfile(tarfile.TarInfo("test"))
1520 finally:
1521 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001522
1523 # Test if the global header was written correctly.
1524 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001525 try:
1526 self.assertEqual(tar.pax_headers, pax_headers)
1527 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1528 # Test if all the fields are strings.
1529 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001530 self.assertIsNot(type(key), bytes)
1531 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001532 if key in tarfile.PAX_NUMBER_FIELDS:
1533 try:
1534 tarfile.PAX_NUMBER_FIELDS[key](val)
1535 except (TypeError, ValueError):
1536 self.fail("unable to convert pax header field")
1537 finally:
1538 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001539
1540 def test_pax_extended_header(self):
1541 # The fields from the pax header have priority over the
1542 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001543 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001544
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001545 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1546 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001547 try:
1548 t = tarfile.TarInfo()
1549 t.name = "\xe4\xf6\xfc" # non-ASCII
1550 t.uid = 8**8 # too large
1551 t.pax_headers = pax_headers
1552 tar.addfile(t)
1553 finally:
1554 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001555
1556 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001557 try:
1558 t = tar.getmembers()[0]
1559 self.assertEqual(t.pax_headers, pax_headers)
1560 self.assertEqual(t.name, "foo")
1561 self.assertEqual(t.uid, 123)
1562 finally:
1563 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001564
1565
1566class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001567
1568 format = tarfile.USTAR_FORMAT
1569
1570 def test_iso8859_1_filename(self):
1571 self._test_unicode_filename("iso8859-1")
1572
1573 def test_utf7_filename(self):
1574 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001575
1576 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001577 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001578
Guido van Rossumd8faa362007-04-27 19:54:29 +00001579 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001580 tar = tarfile.open(tmpname, "w", format=self.format,
1581 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001582 try:
1583 name = "\xe4\xf6\xfc"
1584 tar.addfile(tarfile.TarInfo(name))
1585 finally:
1586 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001587
1588 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001589 try:
1590 self.assertEqual(tar.getmembers()[0].name, name)
1591 finally:
1592 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001593
1594 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001595 tar = tarfile.open(tmpname, "w", format=self.format,
1596 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001597 try:
1598 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001599
Antoine Pitrou95f55602010-09-23 18:36:46 +00001600 tarinfo.name = "\xe4\xf6\xfc"
1601 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001602
Antoine Pitrou95f55602010-09-23 18:36:46 +00001603 tarinfo.name = "foo"
1604 tarinfo.uname = "\xe4\xf6\xfc"
1605 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1606 finally:
1607 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001608
1609 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001610 tar = tarfile.open(tarname, "r",
1611 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001612 try:
1613 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001614 self.assertIs(type(t.name), str)
1615 self.assertIs(type(t.linkname), str)
1616 self.assertIs(type(t.uname), str)
1617 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001618 finally:
1619 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001620
Guido van Rossume7ba4952007-06-06 23:52:48 +00001621 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001622 t = tarfile.TarInfo("foo")
1623 t.uname = "\xe4\xf6\xfc"
1624 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001625
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001626 tar = tarfile.open(tmpname, mode="w", format=self.format,
1627 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001628 try:
1629 tar.addfile(t)
1630 finally:
1631 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001632
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001633 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001634 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001635 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001636 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1637 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1638
1639 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001640 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001641 tar = tarfile.open(tmpname, encoding="ascii")
1642 t = tar.getmember("foo")
1643 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1644 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1645 finally:
1646 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001647
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001648
Guido van Rossume7ba4952007-06-06 23:52:48 +00001649class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001650
Guido van Rossume7ba4952007-06-06 23:52:48 +00001651 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001652
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001653 def test_bad_pax_header(self):
1654 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1655 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001656 for encoding, name in (
1657 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001658 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001659 with tarfile.open(tarname, encoding=encoding,
1660 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001661 try:
1662 t = tar.getmember(name)
1663 except KeyError:
1664 self.fail("unable to read bad GNU tar pax header")
1665
Guido van Rossumd8faa362007-04-27 19:54:29 +00001666
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001667class PAXUnicodeTest(UstarUnicodeTest):
1668
1669 format = tarfile.PAX_FORMAT
1670
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001671 # PAX_FORMAT ignores encoding in write mode.
1672 test_unicode_filename_error = None
1673
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001674 def test_binary_header(self):
1675 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001676 for encoding, name in (
1677 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001678 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001679 with tarfile.open(tarname, encoding=encoding,
1680 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001681 try:
1682 t = tar.getmember(name)
1683 except KeyError:
1684 self.fail("unable to read POSIX.1-2008 binary header")
1685
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001686
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001687class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001688 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001689
Guido van Rossumd8faa362007-04-27 19:54:29 +00001690 def setUp(self):
1691 self.tarname = tmpname
1692 if os.path.exists(self.tarname):
Victor Stinner57004c62014-09-04 00:49:01 +02001693 support.unlink(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001694
Guido van Rossumd8faa362007-04-27 19:54:29 +00001695 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001696 with tarfile.open(tarname, encoding="iso8859-1") as src:
1697 t = src.getmember("ustar/regtype")
1698 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001699 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001700 with tarfile.open(self.tarname, mode) as tar:
1701 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001702
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001703 def test_append_compressed(self):
1704 self._create_testtar("w:" + self.suffix)
1705 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1706
1707class AppendTest(AppendTestBase, unittest.TestCase):
1708 test_append_compressed = None
1709
1710 def _add_testfile(self, fileobj=None):
1711 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1712 tar.addfile(tarfile.TarInfo("bar"))
1713
Guido van Rossumd8faa362007-04-27 19:54:29 +00001714 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001715 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1716 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001717
1718 def test_non_existing(self):
1719 self._add_testfile()
1720 self._test()
1721
1722 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001723 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001724 self._add_testfile()
1725 self._test()
1726
1727 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001728 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001729 self._add_testfile(fobj)
1730 fobj.seek(0)
1731 self._test(fileobj=fobj)
1732
1733 def test_fileobj(self):
1734 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001735 with open(self.tarname, "rb") as fobj:
1736 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001737 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001738 self._add_testfile(fobj)
1739 fobj.seek(0)
1740 self._test(names=["foo", "bar"], fileobj=fobj)
1741
1742 def test_existing(self):
1743 self._create_testtar()
1744 self._add_testfile()
1745 self._test(names=["foo", "bar"])
1746
Lars Gustäbel9520a432009-11-22 18:48:49 +00001747 # Append mode is supposed to fail if the tarfile to append to
1748 # does not end with a zero block.
1749 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001750 with open(self.tarname, "wb") as fobj:
1751 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001752 self.assertRaises(tarfile.ReadError, self._add_testfile)
1753
1754 def test_null(self):
1755 self._test_error(b"")
1756
1757 def test_incomplete(self):
1758 self._test_error(b"\0" * 13)
1759
1760 def test_premature_eof(self):
1761 data = tarfile.TarInfo("foo").tobuf()
1762 self._test_error(data)
1763
1764 def test_trailing_garbage(self):
1765 data = tarfile.TarInfo("foo").tobuf()
1766 self._test_error(data + b"\0" * 13)
1767
1768 def test_invalid(self):
1769 self._test_error(b"a" * 512)
1770
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001771class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
1772 pass
1773
1774class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
1775 pass
1776
1777class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
1778 pass
1779
Guido van Rossumd8faa362007-04-27 19:54:29 +00001780
1781class LimitsTest(unittest.TestCase):
1782
1783 def test_ustar_limits(self):
1784 # 100 char name
1785 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001786 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001787
1788 # 101 char name that cannot be stored
1789 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001790 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001791
1792 # 256 char name with a slash at pos 156
1793 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001794 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001795
1796 # 256 char name that cannot be stored
1797 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001798 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001799
1800 # 512 char name
1801 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001802 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001803
1804 # 512 char linkname
1805 tarinfo = tarfile.TarInfo("longlink")
1806 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001807 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001808
1809 # uid > 8 digits
1810 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001811 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001812 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001813
1814 def test_gnu_limits(self):
1815 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001816 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001817
1818 tarinfo = tarfile.TarInfo("longlink")
1819 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001820 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001821
1822 # uid >= 256 ** 7
1823 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001824 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001825 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001826
1827 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001828 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001829 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001830
1831 tarinfo = tarfile.TarInfo("longlink")
1832 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001833 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001834
1835 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001836 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001837 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001838
1839
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001840class MiscTest(unittest.TestCase):
1841
1842 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001843 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
1844 b"foo\0\0\0\0\0")
1845 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
1846 b"foo")
1847 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
1848 "foo")
1849 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
1850 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001851
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001852 def test_read_number_fields(self):
1853 # Issue 13158: Test if GNU tar specific base-256 number fields
1854 # are decoded correctly.
1855 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1856 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001857 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
1858 0o10000000)
1859 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
1860 0xffffffff)
1861 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
1862 -1)
1863 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
1864 -100)
1865 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
1866 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001867
Lars Gustäbelb7a688b2015-07-02 19:38:38 +02001868 # Issue 24514: Test if empty number fields are converted to zero.
1869 self.assertEqual(tarfile.nti(b"\0"), 0)
1870 self.assertEqual(tarfile.nti(b" \0"), 0)
1871
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001872 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001873 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001874 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001875 self.assertEqual(tarfile.itn(0o10000000),
1876 b"\x80\x00\x00\x00\x00\x20\x00\x00")
1877 self.assertEqual(tarfile.itn(0xffffffff),
1878 b"\x80\x00\x00\x00\xff\xff\xff\xff")
1879 self.assertEqual(tarfile.itn(-1),
1880 b"\xff\xff\xff\xff\xff\xff\xff\xff")
1881 self.assertEqual(tarfile.itn(-100),
1882 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1883 self.assertEqual(tarfile.itn(-0x100000000000000),
1884 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001885
1886 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001887 with self.assertRaises(ValueError):
1888 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
1889 with self.assertRaises(ValueError):
1890 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
1891 with self.assertRaises(ValueError):
1892 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
1893 with self.assertRaises(ValueError):
1894 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001895
1896
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001897class CommandLineTest(unittest.TestCase):
1898
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001899 def tarfilecmd(self, *args, **kwargs):
1900 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
1901 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01001902 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001903
1904 def tarfilecmd_failure(self, *args):
1905 return script_helper.assert_python_failure('-m', 'tarfile', *args)
1906
1907 def make_simple_tarfile(self, tar_name):
1908 files = [support.findfile('tokenize_tests.txt'),
1909 support.findfile('tokenize_tests-no-coding-cookie-'
1910 'and-utf8-bom-sig-only.txt')]
1911 self.addCleanup(support.unlink, tar_name)
1912 with tarfile.open(tar_name, 'w') as tf:
1913 for tardata in files:
1914 tf.add(tardata, arcname=os.path.basename(tardata))
1915
1916 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001917 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001918 for opt in '-t', '--test':
1919 out = self.tarfilecmd(opt, tar_name)
1920 self.assertEqual(out, b'')
1921
1922 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001923 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001924 for opt in '-v', '--verbose':
1925 out = self.tarfilecmd(opt, '-t', tar_name)
1926 self.assertIn(b'is a tar archive.\n', out)
1927
1928 def test_test_command_invalid_file(self):
1929 zipname = support.findfile('zipdir.zip')
1930 rc, out, err = self.tarfilecmd_failure('-t', zipname)
1931 self.assertIn(b' is not a tar archive.', err)
1932 self.assertEqual(out, b'')
1933 self.assertEqual(rc, 1)
1934
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001935 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001936 with self.subTest(tar_name=tar_name):
1937 with open(tar_name, 'rb') as f:
1938 data = f.read()
1939 try:
1940 with open(tmpname, 'wb') as f:
1941 f.write(data[:511])
1942 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
1943 self.assertEqual(out, b'')
1944 self.assertEqual(rc, 1)
1945 finally:
1946 support.unlink(tmpname)
1947
1948 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001949 for tar_name in testtarnames:
1950 with support.captured_stdout() as t:
1951 with tarfile.open(tar_name, 'r') as tf:
1952 tf.list(verbose=False)
1953 expected = t.getvalue().encode('ascii', 'backslashreplace')
1954 for opt in '-l', '--list':
1955 out = self.tarfilecmd(opt, tar_name,
1956 PYTHONIOENCODING='ascii')
1957 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001958
1959 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001960 for tar_name in testtarnames:
1961 with support.captured_stdout() as t:
1962 with tarfile.open(tar_name, 'r') as tf:
1963 tf.list(verbose=True)
1964 expected = t.getvalue().encode('ascii', 'backslashreplace')
1965 for opt in '-v', '--verbose':
1966 out = self.tarfilecmd(opt, '-l', tar_name,
1967 PYTHONIOENCODING='ascii')
1968 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001969
1970 def test_list_command_invalid_file(self):
1971 zipname = support.findfile('zipdir.zip')
1972 rc, out, err = self.tarfilecmd_failure('-l', zipname)
1973 self.assertIn(b' is not a tar archive.', err)
1974 self.assertEqual(out, b'')
1975 self.assertEqual(rc, 1)
1976
1977 def test_create_command(self):
1978 files = [support.findfile('tokenize_tests.txt'),
1979 support.findfile('tokenize_tests-no-coding-cookie-'
1980 'and-utf8-bom-sig-only.txt')]
1981 for opt in '-c', '--create':
1982 try:
1983 out = self.tarfilecmd(opt, tmpname, *files)
1984 self.assertEqual(out, b'')
1985 with tarfile.open(tmpname) as tar:
1986 tar.getmembers()
1987 finally:
1988 support.unlink(tmpname)
1989
1990 def test_create_command_verbose(self):
1991 files = [support.findfile('tokenize_tests.txt'),
1992 support.findfile('tokenize_tests-no-coding-cookie-'
1993 'and-utf8-bom-sig-only.txt')]
1994 for opt in '-v', '--verbose':
1995 try:
1996 out = self.tarfilecmd(opt, '-c', tmpname, *files)
1997 self.assertIn(b' file created.', out)
1998 with tarfile.open(tmpname) as tar:
1999 tar.getmembers()
2000 finally:
2001 support.unlink(tmpname)
2002
2003 def test_create_command_dotless_filename(self):
2004 files = [support.findfile('tokenize_tests.txt')]
2005 try:
2006 out = self.tarfilecmd('-c', dotlessname, *files)
2007 self.assertEqual(out, b'')
2008 with tarfile.open(dotlessname) as tar:
2009 tar.getmembers()
2010 finally:
2011 support.unlink(dotlessname)
2012
2013 def test_create_command_dot_started_filename(self):
2014 tar_name = os.path.join(TEMPDIR, ".testtar")
2015 files = [support.findfile('tokenize_tests.txt')]
2016 try:
2017 out = self.tarfilecmd('-c', tar_name, *files)
2018 self.assertEqual(out, b'')
2019 with tarfile.open(tar_name) as tar:
2020 tar.getmembers()
2021 finally:
2022 support.unlink(tar_name)
2023
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002024 def test_create_command_compressed(self):
2025 files = [support.findfile('tokenize_tests.txt'),
2026 support.findfile('tokenize_tests-no-coding-cookie-'
2027 'and-utf8-bom-sig-only.txt')]
2028 for filetype in (GzipTest, Bz2Test, LzmaTest):
2029 if not filetype.open:
2030 continue
2031 try:
2032 tar_name = tmpname + '.' + filetype.suffix
2033 out = self.tarfilecmd('-c', tar_name, *files)
2034 with filetype.taropen(tar_name) as tar:
2035 tar.getmembers()
2036 finally:
2037 support.unlink(tar_name)
2038
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002039 def test_extract_command(self):
2040 self.make_simple_tarfile(tmpname)
2041 for opt in '-e', '--extract':
2042 try:
2043 with support.temp_cwd(tarextdir):
2044 out = self.tarfilecmd(opt, tmpname)
2045 self.assertEqual(out, b'')
2046 finally:
2047 support.rmtree(tarextdir)
2048
2049 def test_extract_command_verbose(self):
2050 self.make_simple_tarfile(tmpname)
2051 for opt in '-v', '--verbose':
2052 try:
2053 with support.temp_cwd(tarextdir):
2054 out = self.tarfilecmd(opt, '-e', tmpname)
2055 self.assertIn(b' file is extracted.', out)
2056 finally:
2057 support.rmtree(tarextdir)
2058
2059 def test_extract_command_different_directory(self):
2060 self.make_simple_tarfile(tmpname)
2061 try:
2062 with support.temp_cwd(tarextdir):
2063 out = self.tarfilecmd('-e', tmpname, 'spamdir')
2064 self.assertEqual(out, b'')
2065 finally:
2066 support.rmtree(tarextdir)
2067
2068 def test_extract_command_invalid_file(self):
2069 zipname = support.findfile('zipdir.zip')
2070 with support.temp_cwd(tarextdir):
2071 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2072 self.assertIn(b' is not a tar archive.', err)
2073 self.assertEqual(out, b'')
2074 self.assertEqual(rc, 1)
2075
2076
Lars Gustäbel01385812010-03-03 12:08:54 +00002077class ContextManagerTest(unittest.TestCase):
2078
2079 def test_basic(self):
2080 with tarfile.open(tarname) as tar:
2081 self.assertFalse(tar.closed, "closed inside runtime context")
2082 self.assertTrue(tar.closed, "context manager failed")
2083
2084 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002085 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002086 # if the TarFile object is already closed.
2087 tar = tarfile.open(tarname)
2088 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002089 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002090 with tar:
2091 pass
2092
2093 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002094 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002095 with self.assertRaises(Exception) as exc:
2096 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002097 raise OSError
2098 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002099 "wrong exception raised in context manager")
2100 self.assertTrue(tar.closed, "context manager failed")
2101
2102 def test_no_eof(self):
2103 # __exit__() must not write end-of-archive blocks if an
2104 # exception was raised.
2105 try:
2106 with tarfile.open(tmpname, "w") as tar:
2107 raise Exception
2108 except:
2109 pass
2110 self.assertEqual(os.path.getsize(tmpname), 0,
2111 "context manager wrote an end-of-archive block")
2112 self.assertTrue(tar.closed, "context manager failed")
2113
2114 def test_eof(self):
2115 # __exit__() must write end-of-archive blocks, i.e. call
2116 # TarFile.close() if there was no error.
2117 with tarfile.open(tmpname, "w"):
2118 pass
2119 self.assertNotEqual(os.path.getsize(tmpname), 0,
2120 "context manager wrote no end-of-archive block")
2121
2122 def test_fileobj(self):
2123 # Test that __exit__() did not close the external file
2124 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002125 with open(tmpname, "wb") as fobj:
2126 try:
2127 with tarfile.open(fileobj=fobj, mode="w") as tar:
2128 raise Exception
2129 except:
2130 pass
2131 self.assertFalse(fobj.closed, "external file object was closed")
2132 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002133
2134
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002135@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2136class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002137
2138 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002139 # symbolic or hard links tarfile tries to extract these types of members
2140 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002141 def _test_link_extraction(self, name):
2142 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002143 with open(os.path.join(TEMPDIR, name), "rb") as f:
2144 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002145 self.assertEqual(md5sum(data), md5_regtype)
2146
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002147 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002148 @unittest.skipIf(hasattr(os.path, "islink"),
2149 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002150 def test_hardlink_extraction1(self):
2151 self._test_link_extraction("ustar/lnktype")
2152
Brian Curtind40e6f72010-07-08 21:39:08 +00002153 @unittest.skipIf(hasattr(os.path, "islink"),
2154 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002155 def test_hardlink_extraction2(self):
2156 self._test_link_extraction("./ustar/linktest2/lnktype")
2157
Brian Curtin74e45612010-07-09 15:58:59 +00002158 @unittest.skipIf(hasattr(os, "symlink"),
2159 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002160 def test_symlink_extraction1(self):
2161 self._test_link_extraction("ustar/symtype")
2162
Brian Curtin74e45612010-07-09 15:58:59 +00002163 @unittest.skipIf(hasattr(os, "symlink"),
2164 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002165 def test_symlink_extraction2(self):
2166 self._test_link_extraction("./ustar/linktest2/symtype")
2167
2168
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002169class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002170 # Issue5068: The _BZ2Proxy.read() method loops forever
2171 # on an empty or partial bzipped file.
2172
2173 def _test_partial_input(self, mode):
2174 class MyBytesIO(io.BytesIO):
2175 hit_eof = False
2176 def read(self, n):
2177 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002178 raise AssertionError("infinite loop detected in "
2179 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002180 self.hit_eof = self.tell() == len(self.getvalue())
2181 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002182 def seek(self, *args):
2183 self.hit_eof = False
2184 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002185
2186 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2187 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002188 try:
2189 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2190 except tarfile.ReadError:
2191 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002192
2193 def test_partial_input(self):
2194 self._test_partial_input("r")
2195
2196 def test_partial_input_bz2(self):
2197 self._test_partial_input("r:bz2")
2198
2199
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002200def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002201 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002202 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002203
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002204 global testtarnames
2205 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002206 with open(tarname, "rb") as fobj:
2207 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002208
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002209 # Create compressed tarfiles.
2210 for c in GzipTest, Bz2Test, LzmaTest:
2211 if c.open:
2212 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002213 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002214 with c.open(c.tarname, "wb") as tar:
2215 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002216
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002217def tearDownModule():
2218 if os.path.exists(TEMPDIR):
Victor Stinner57004c62014-09-04 00:49:01 +02002219 support.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002220
Neal Norwitz996acf12003-02-17 14:51:41 +00002221if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002222 unittest.main()