blob: e527e403fa68365831b24102601c56b143053026 [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
352
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300353class MiscReadTestBase(CommonReadTest):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300354 def requires_name_attribute(self):
355 pass
356
Thomas Woutersed03b412007-08-28 21:37:11 +0000357 def test_no_name_argument(self):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300358 self.requires_name_attribute()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000359 with open(self.tarname, "rb") as fobj:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300360 self.assertIsInstance(fobj.name, str)
361 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
362 self.assertIsInstance(tar.name, str)
363 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000364
Thomas Woutersed03b412007-08-28 21:37:11 +0000365 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000366 with open(self.tarname, "rb") as fobj:
367 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000368 fobj = io.BytesIO(data)
369 self.assertRaises(AttributeError, getattr, fobj, "name")
370 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300371 self.assertIsNone(tar.name)
Thomas Woutersed03b412007-08-28 21:37:11 +0000372
373 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000374 with open(self.tarname, "rb") as fobj:
375 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000376 fobj = io.BytesIO(data)
377 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000378 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300379 self.assertIsNone(tar.name)
380
381 def test_int_name_attribute(self):
382 # Issue 21044: tarfile.open() should handle fileobj with an integer
383 # 'name' attribute.
384 fd = os.open(self.tarname, os.O_RDONLY)
385 with open(fd, 'rb') as fobj:
386 self.assertIsInstance(fobj.name, int)
387 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
388 self.assertIsNone(tar.name)
389
390 def test_bytes_name_attribute(self):
391 self.requires_name_attribute()
392 tarname = os.fsencode(self.tarname)
393 with open(tarname, 'rb') as fobj:
394 self.assertIsInstance(fobj.name, bytes)
395 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
396 self.assertIsInstance(tar.name, bytes)
397 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Thomas Woutersed03b412007-08-28 21:37:11 +0000398
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +0200399 def test_illegal_mode_arg(self):
400 with open(tmpname, 'wb'):
401 pass
402 with self.assertRaisesRegex(ValueError, 'mode must be '):
403 tar = self.taropen(tmpname, 'q')
404 with self.assertRaisesRegex(ValueError, 'mode must be '):
405 tar = self.taropen(tmpname, 'rw')
406 with self.assertRaisesRegex(ValueError, 'mode must be '):
407 tar = self.taropen(tmpname, '')
408
Christian Heimesd8654cf2007-12-02 15:22:16 +0000409 def test_fileobj_with_offset(self):
410 # Skip the first member and store values from the second member
411 # of the testtar.
412 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000413 try:
414 tar.next()
415 t = tar.next()
416 name = t.name
417 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200418 with tar.extractfile(t) as f:
419 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000420 finally:
421 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000422
423 # Open the testtar and seek to the offset of the second member.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300424 with self.open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000425 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000426
Antoine Pitrou95f55602010-09-23 18:36:46 +0000427 # Test if the tarfile starts with the second member.
428 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
429 t = tar.next()
430 self.assertEqual(t.name, name)
431 # Read to the end of fileobj and test if seeking back to the
432 # beginning works.
433 tar.getmembers()
434 self.assertEqual(tar.extractfile(t).read(), data,
435 "seek back did not work")
436 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000437
Guido van Rossumd8faa362007-04-27 19:54:29 +0000438 def test_fail_comp(self):
439 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000440 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000441 with open(tarname, "rb") as fobj:
442 self.assertRaises(tarfile.ReadError, tarfile.open,
443 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000444
445 def test_v7_dirtype(self):
446 # Test old style dirtype member (bug #1336623):
447 # Old V7 tars create directory members using an AREGTYPE
448 # header with a "/" appended to the filename field.
449 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300450 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000451 "v7 dirtype failed")
452
Christian Heimes126d29a2008-02-11 22:57:17 +0000453 def test_xstar_type(self):
454 # The xstar format stores extra atime and ctime fields inside the
455 # space reserved for the prefix field. The prefix field must be
456 # ignored in this case, otherwise it will mess up the name.
457 try:
458 self.tar.getmember("misc/regtype-xstar")
459 except KeyError:
460 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
461
Guido van Rossumd8faa362007-04-27 19:54:29 +0000462 def test_check_members(self):
463 for tarinfo in self.tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300464 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000465 "wrong mtime for %s" % tarinfo.name)
466 if not tarinfo.name.startswith("ustar/"):
467 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300468 self.assertEqual(tarinfo.uname, "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000469 "wrong uname for %s" % tarinfo.name)
470
471 def test_find_members(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300472 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000473 "could not find all members")
474
Brian Curtin74e45612010-07-09 15:58:59 +0000475 @unittest.skipUnless(hasattr(os, "link"),
476 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000477 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000478 def test_extract_hardlink(self):
479 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200480 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000481 tar.extract("ustar/regtype", TEMPDIR)
Victor Stinner57004c62014-09-04 00:49:01 +0200482 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000483
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200484 tar.extract("ustar/lnktype", TEMPDIR)
Victor Stinner57004c62014-09-04 00:49:01 +0200485 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000486 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
487 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000488 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000489
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200490 tar.extract("ustar/symtype", TEMPDIR)
Victor Stinner57004c62014-09-04 00:49:01 +0200491 self.addCleanup(support.unlink, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000492 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
493 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000494 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000495
Christian Heimesfaf2f632008-01-06 16:59:19 +0000496 def test_extractall(self):
497 # Test if extractall() correctly restores directory permissions
498 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000499 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000500 DIR = os.path.join(TEMPDIR, "extractall")
501 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000502 try:
503 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000504 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000505 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000506 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000507 if sys.platform != "win32":
508 # Win32 has no support for fine grained permissions.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300509 self.assertEqual(tarinfo.mode & 0o777,
510 os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000511 def format_mtime(mtime):
512 if isinstance(mtime, float):
513 return "{} ({})".format(mtime, mtime.hex())
514 else:
515 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000516 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000517 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
518 format_mtime(tarinfo.mtime),
519 format_mtime(file_mtime),
520 path)
521 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000522 finally:
523 tar.close()
Victor Stinner57004c62014-09-04 00:49:01 +0200524 support.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000525
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000526 def test_extract_directory(self):
527 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000528 DIR = os.path.join(TEMPDIR, "extractdir")
529 os.mkdir(DIR)
530 try:
531 with tarfile.open(tarname, encoding="iso8859-1") as tar:
532 tarinfo = tar.getmember(dirtype)
533 tar.extract(tarinfo, path=DIR)
534 extracted = os.path.join(DIR, dirtype)
535 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
536 if sys.platform != "win32":
537 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
538 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200539 support.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000540
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000541 def test_init_close_fobj(self):
542 # Issue #7341: Close the internal file object in the TarFile
543 # constructor in case of an error. For the test we rely on
544 # the fact that opening an empty file raises a ReadError.
545 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000546 with open(empty, "wb") as fobj:
547 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000548
549 try:
550 tar = object.__new__(tarfile.TarFile)
551 try:
552 tar.__init__(empty)
553 except tarfile.ReadError:
554 self.assertTrue(tar.fileobj.closed)
555 else:
556 self.fail("ReadError not raised")
557 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000558 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000559
Serhiy Storchaka263fab92013-05-09 14:22:26 +0300560 def test_parallel_iteration(self):
561 # Issue #16601: Restarting iteration over tarfile continued
562 # from where it left off.
563 with tarfile.open(self.tarname) as tar:
564 for m1, m2 in zip(tar, tar):
565 self.assertEqual(m1.offset, m2.offset)
566 self.assertEqual(m1.get_info(), m2.get_info())
567
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300568class MiscReadTest(MiscReadTestBase, unittest.TestCase):
569 test_fail_comp = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000570
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300571class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200572 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000573
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300574class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300575 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300576 self.skipTest("BZ2File have no name attribute")
577
578class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300579 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300580 self.skipTest("LZMAFile have no name attribute")
581
582
583class StreamReadTest(CommonReadTest, unittest.TestCase):
584
585 prefix="r|"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000586
Lars Gustäbeldd071042011-02-23 11:42:22 +0000587 def test_read_through(self):
588 # Issue #11224: A poorly designed _FileInFile.read() method
589 # caused seeking errors with stream tar files.
590 for tarinfo in self.tar:
591 if not tarinfo.isreg():
592 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200593 with self.tar.extractfile(tarinfo) as fobj:
594 while True:
595 try:
596 buf = fobj.read(512)
597 except tarfile.StreamError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300598 self.fail("simple read-through using "
599 "TarFile.extractfile() failed")
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200600 if not buf:
601 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000602
Guido van Rossumd8faa362007-04-27 19:54:29 +0000603 def test_fileobj_regular_file(self):
604 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200605 with self.tar.extractfile(tarinfo) as fobj:
606 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300607 self.assertEqual(len(data), tarinfo.size,
608 "regular file extraction failed")
609 self.assertEqual(md5sum(data), md5_regtype,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000610 "regular file extraction failed")
611
612 def test_provoke_stream_error(self):
613 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200614 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
615 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000616
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617 def test_compare_members(self):
618 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000619 try:
620 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000621
Antoine Pitrou95f55602010-09-23 18:36:46 +0000622 while True:
623 t1 = tar1.next()
624 t2 = tar2.next()
625 if t1 is None:
626 break
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300627 self.assertIsNotNone(t2, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000628
Antoine Pitrou95f55602010-09-23 18:36:46 +0000629 if t2.islnk() or t2.issym():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300630 with self.assertRaises(tarfile.StreamError):
631 tar2.extractfile(t2)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000632 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633
Antoine Pitrou95f55602010-09-23 18:36:46 +0000634 v1 = tar1.extractfile(t1)
635 v2 = tar2.extractfile(t2)
636 if v1 is None:
637 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300638 self.assertIsNotNone(v2, "stream.extractfile() failed")
639 self.assertEqual(v1.read(), v2.read(),
640 "stream extraction failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000641 finally:
642 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000643
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300644class GzipStreamReadTest(GzipTest, StreamReadTest):
645 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000646
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300647class Bz2StreamReadTest(Bz2Test, StreamReadTest):
648 pass
Thomas Wouterscf297e42007-02-23 15:07:44 +0000649
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300650class LzmaStreamReadTest(LzmaTest, StreamReadTest):
651 pass
652
653
654class DetectReadTest(TarTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000655 def _testfunc_file(self, name, mode):
656 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000657 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000658 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000659 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000660 else:
661 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000662
Guido van Rossumd8faa362007-04-27 19:54:29 +0000663 def _testfunc_fileobj(self, name, mode):
664 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000665 with open(name, "rb") as f:
666 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000667 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000668 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000669 else:
670 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000671
672 def _test_modes(self, testfunc):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300673 if self.suffix:
674 with self.assertRaises(tarfile.ReadError):
675 tarfile.open(tarname, mode="r:" + self.suffix)
676 with self.assertRaises(tarfile.ReadError):
677 tarfile.open(tarname, mode="r|" + self.suffix)
678 with self.assertRaises(tarfile.ReadError):
679 tarfile.open(self.tarname, mode="r:")
680 with self.assertRaises(tarfile.ReadError):
681 tarfile.open(self.tarname, mode="r|")
682 testfunc(self.tarname, "r")
683 testfunc(self.tarname, "r:" + self.suffix)
684 testfunc(self.tarname, "r:*")
685 testfunc(self.tarname, "r|" + self.suffix)
686 testfunc(self.tarname, "r|*")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100687
Guido van Rossumd8faa362007-04-27 19:54:29 +0000688 def test_detect_file(self):
689 self._test_modes(self._testfunc_file)
690
691 def test_detect_fileobj(self):
692 self._test_modes(self._testfunc_fileobj)
693
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300694class GzipDetectReadTest(GzipTest, DetectReadTest):
695 pass
696
697class Bz2DetectReadTest(Bz2Test, DetectReadTest):
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100698 def test_detect_stream_bz2(self):
699 # Originally, tarfile's stream detection looked for the string
700 # "BZh91" at the start of the file. This is incorrect because
701 # the '9' represents the blocksize (900kB). If the file was
702 # compressed using another blocksize autodetection fails.
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100703 with open(tarname, "rb") as fobj:
704 data = fobj.read()
705
706 # Compress with blocksize 100kB, the file starts with "BZh11".
707 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
708 fobj.write(data)
709
710 self._testfunc_file(tmpname, "r|*")
711
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300712class LzmaDetectReadTest(LzmaTest, DetectReadTest):
713 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000714
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300715
716class MemberReadTest(ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000717
718 def _test_member(self, tarinfo, chksum=None, **kwargs):
719 if chksum is not None:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300720 with self.tar.extractfile(tarinfo) as f:
721 self.assertEqual(md5sum(f.read()), chksum,
722 "wrong md5sum for %s" % tarinfo.name)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000724 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000725 kwargs["uid"] = 1000
726 kwargs["gid"] = 100
727 if "old-v7" not in tarinfo.name:
728 # V7 tar can't handle alphabetic owners.
729 kwargs["uname"] = "tarfile"
730 kwargs["gname"] = "tarfile"
731 for k, v in kwargs.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300732 self.assertEqual(getattr(tarinfo, k), v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000733 "wrong value in %s field of %s" % (k, tarinfo.name))
734
735 def test_find_regtype(self):
736 tarinfo = self.tar.getmember("ustar/regtype")
737 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
738
739 def test_find_conttype(self):
740 tarinfo = self.tar.getmember("ustar/conttype")
741 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
742
743 def test_find_dirtype(self):
744 tarinfo = self.tar.getmember("ustar/dirtype")
745 self._test_member(tarinfo, size=0)
746
747 def test_find_dirtype_with_size(self):
748 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
749 self._test_member(tarinfo, size=255)
750
751 def test_find_lnktype(self):
752 tarinfo = self.tar.getmember("ustar/lnktype")
753 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
754
755 def test_find_symtype(self):
756 tarinfo = self.tar.getmember("ustar/symtype")
757 self._test_member(tarinfo, size=0, linkname="regtype")
758
759 def test_find_blktype(self):
760 tarinfo = self.tar.getmember("ustar/blktype")
761 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
762
763 def test_find_chrtype(self):
764 tarinfo = self.tar.getmember("ustar/chrtype")
765 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
766
767 def test_find_fifotype(self):
768 tarinfo = self.tar.getmember("ustar/fifotype")
769 self._test_member(tarinfo, size=0)
770
771 def test_find_sparse(self):
772 tarinfo = self.tar.getmember("ustar/sparse")
773 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
774
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000775 def test_find_gnusparse(self):
776 tarinfo = self.tar.getmember("gnu/sparse")
777 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
778
779 def test_find_gnusparse_00(self):
780 tarinfo = self.tar.getmember("gnu/sparse-0.0")
781 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
782
783 def test_find_gnusparse_01(self):
784 tarinfo = self.tar.getmember("gnu/sparse-0.1")
785 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
786
787 def test_find_gnusparse_10(self):
788 tarinfo = self.tar.getmember("gnu/sparse-1.0")
789 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
790
Guido van Rossumd8faa362007-04-27 19:54:29 +0000791 def test_find_umlauts(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300792 tarinfo = self.tar.getmember("ustar/umlauts-"
793 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000794 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
795
796 def test_find_ustar_longname(self):
797 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000798 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000799
800 def test_find_regtype_oldv7(self):
801 tarinfo = self.tar.getmember("misc/regtype-old-v7")
802 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
803
804 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000805 self.tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300806 self.tar = tarfile.open(self.tarname, mode=self.mode,
807 encoding="iso8859-1")
808 tarinfo = self.tar.getmember("pax/umlauts-"
809 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000810 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
811
812
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300813class LongnameTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000814
815 def test_read_longname(self):
816 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000817 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000818 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000819 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000820 except KeyError:
821 self.fail("longname not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300822 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
823 "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000824
825 def test_read_longlink(self):
826 longname = self.subdir + "/" + "123/" * 125 + "longname"
827 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
828 try:
829 tarinfo = self.tar.getmember(longlink)
830 except KeyError:
831 self.fail("longlink not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300832 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000833
834 def test_truncated_longname(self):
835 longname = self.subdir + "/" + "123/" * 125 + "longname"
836 tarinfo = self.tar.getmember(longname)
837 offset = tarinfo.offset
838 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000839 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300840 with self.assertRaises(tarfile.ReadError):
841 tarfile.open(name="foo.tar", fileobj=fobj)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000842
Guido van Rossume7ba4952007-06-06 23:52:48 +0000843 def test_header_offset(self):
844 # Test if the start offset of the TarInfo object includes
845 # the preceding extended header.
846 longname = self.subdir + "/" + "123/" * 125 + "longname"
847 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000848 with open(tarname, "rb") as fobj:
849 fobj.seek(offset)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300850 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
851 "iso8859-1", "strict")
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000852 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000853
Guido van Rossumd8faa362007-04-27 19:54:29 +0000854
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300855class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000856
857 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000858 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000859
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000860 # Since 3.2 tarfile is supposed to accurately restore sparse members and
861 # produce files with holes. This is what we actually want to test here.
862 # Unfortunately, not all platforms/filesystems support sparse files, and
863 # even on platforms that do it is non-trivial to make reliable assertions
864 # about holes in files. Therefore, we first do one basic test which works
865 # an all platforms, and after that a test that will work only on
866 # platforms/filesystems that prove to support sparse files.
867 def _test_sparse_file(self, name):
868 self.tar.extract(name, TEMPDIR)
869 filename = os.path.join(TEMPDIR, name)
870 with open(filename, "rb") as fobj:
871 data = fobj.read()
872 self.assertEqual(md5sum(data), md5_sparse,
873 "wrong md5sum for %s" % name)
874
875 if self._fs_supports_holes():
876 s = os.stat(filename)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300877 self.assertLess(s.st_blocks * 512, s.st_size)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000878
879 def test_sparse_file_old(self):
880 self._test_sparse_file("gnu/sparse")
881
882 def test_sparse_file_00(self):
883 self._test_sparse_file("gnu/sparse-0.0")
884
885 def test_sparse_file_01(self):
886 self._test_sparse_file("gnu/sparse-0.1")
887
888 def test_sparse_file_10(self):
889 self._test_sparse_file("gnu/sparse-1.0")
890
891 @staticmethod
892 def _fs_supports_holes():
893 # Return True if the platform knows the st_blocks stat attribute and
894 # uses st_blocks units of 512 bytes, and if the filesystem is able to
895 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200896 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000897 # Linux evidentially has 512 byte st_blocks units.
898 name = os.path.join(TEMPDIR, "sparse-test")
899 with open(name, "wb") as fobj:
900 fobj.seek(4096)
901 fobj.truncate()
902 s = os.stat(name)
Victor Stinner57004c62014-09-04 00:49:01 +0200903 support.unlink(name)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000904 return s.st_blocks == 0
905 else:
906 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907
908
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300909class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000910
911 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000912 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000913
Guido van Rossume7ba4952007-06-06 23:52:48 +0000914 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000915 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000916 try:
917 tarinfo = tar.getmember("pax/regtype1")
918 self.assertEqual(tarinfo.uname, "foo")
919 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300920 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
921 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000922
Antoine Pitrou95f55602010-09-23 18:36:46 +0000923 tarinfo = tar.getmember("pax/regtype2")
924 self.assertEqual(tarinfo.uname, "")
925 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300926 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
927 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000928
Antoine Pitrou95f55602010-09-23 18:36:46 +0000929 tarinfo = tar.getmember("pax/regtype3")
930 self.assertEqual(tarinfo.uname, "tarfile")
931 self.assertEqual(tarinfo.gname, "tarfile")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300932 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
933 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000934 finally:
935 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000936
937 def test_pax_number_fields(self):
938 # All following number fields are read from the pax header.
939 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000940 try:
941 tarinfo = tar.getmember("pax/regtype4")
942 self.assertEqual(tarinfo.size, 7011)
943 self.assertEqual(tarinfo.uid, 123)
944 self.assertEqual(tarinfo.gid, 123)
945 self.assertEqual(tarinfo.mtime, 1041808783.0)
946 self.assertEqual(type(tarinfo.mtime), float)
947 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
948 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
949 finally:
950 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951
952
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300953class WriteTestBase(TarTest):
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000954 # Put all write tests in here that are supposed to be tested
955 # in all possible mode combinations.
956
957 def test_fileobj_no_close(self):
958 fobj = io.BytesIO()
959 tar = tarfile.open(fileobj=fobj, mode=self.mode)
960 tar.addfile(tarfile.TarInfo("foo"))
961 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300962 self.assertFalse(fobj.closed, "external fileobjs must never closed")
Serhiy Storchaka9fbec7a2014-01-18 15:53:05 +0200963 # Issue #20238: Incomplete gzip output with mode="w:gz"
964 data = fobj.getvalue()
965 del tar
966 support.gc_collect()
967 self.assertFalse(fobj.closed)
968 self.assertEqual(data, fobj.getvalue())
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000969
970
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300971class WriteTest(WriteTestBase, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300973 prefix = "w:"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000974
975 def test_100_char_name(self):
976 # The name field in a tar header stores strings of at most 100 chars.
977 # If a string is shorter than 100 chars it has to be padded with '\0',
978 # which implies that a string of exactly 100 chars is stored without
979 # a trailing '\0'.
980 name = "0123456789" * 10
981 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000982 try:
983 t = tarfile.TarInfo(name)
984 tar.addfile(t)
985 finally:
986 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000987
Guido van Rossumd8faa362007-04-27 19:54:29 +0000988 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000989 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300990 self.assertEqual(tar.getnames()[0], name,
Antoine Pitrou95f55602010-09-23 18:36:46 +0000991 "failed to store 100 char filename")
992 finally:
993 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000994
Guido van Rossumd8faa362007-04-27 19:54:29 +0000995 def test_tar_size(self):
996 # Test for bug #1013882.
997 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000998 try:
999 path = os.path.join(TEMPDIR, "file")
1000 with open(path, "wb") as fobj:
1001 fobj.write(b"aaa")
1002 tar.add(path)
1003 finally:
1004 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001005 self.assertGreater(os.path.getsize(tmpname), 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001006 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001007
Guido van Rossumd8faa362007-04-27 19:54:29 +00001008 # The test_*_size tests test for bug #1167128.
1009 def test_file_size(self):
1010 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001011 try:
1012 path = os.path.join(TEMPDIR, "file")
1013 with open(path, "wb"):
1014 pass
1015 tarinfo = tar.gettarinfo(path)
1016 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001017
Antoine Pitrou95f55602010-09-23 18:36:46 +00001018 with open(path, "wb") as fobj:
1019 fobj.write(b"aaa")
1020 tarinfo = tar.gettarinfo(path)
1021 self.assertEqual(tarinfo.size, 3)
1022 finally:
1023 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001024
1025 def test_directory_size(self):
1026 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001027 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028 try:
1029 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001030 try:
1031 tarinfo = tar.gettarinfo(path)
1032 self.assertEqual(tarinfo.size, 0)
1033 finally:
1034 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001035 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001036 support.rmdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001037
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001038 @unittest.skipUnless(hasattr(os, "link"),
1039 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001040 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001041 link = os.path.join(TEMPDIR, "link")
1042 target = os.path.join(TEMPDIR, "link_target")
1043 with open(target, "wb") as fobj:
1044 fobj.write(b"aaa")
1045 os.link(target, link)
1046 try:
1047 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001048 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001049 # Record the link target in the inodes list.
1050 tar.gettarinfo(target)
1051 tarinfo = tar.gettarinfo(link)
1052 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001053 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001054 tar.close()
1055 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001056 support.unlink(target)
1057 support.unlink(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001058
Brian Curtin3b4499c2010-12-28 14:31:47 +00001059 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +00001060 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +00001061 path = os.path.join(TEMPDIR, "symlink")
1062 os.symlink("link_target", path)
1063 try:
1064 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001065 try:
1066 tarinfo = tar.gettarinfo(path)
1067 self.assertEqual(tarinfo.size, 0)
1068 finally:
1069 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +00001070 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001071 support.unlink(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001072
1073 def test_add_self(self):
1074 # Test for #1257255.
1075 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001077 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001078 self.assertEqual(tar.name, dstname,
1079 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001080 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001081 self.assertEqual(tar.getnames(), [],
1082 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001083
Antoine Pitrou95f55602010-09-23 18:36:46 +00001084 cwd = os.getcwd()
1085 os.chdir(TEMPDIR)
1086 tar.add(dstname)
1087 os.chdir(cwd)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001088 self.assertEqual(tar.getnames(), [],
1089 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001090 finally:
1091 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001092
Guido van Rossum486364b2007-06-30 05:01:58 +00001093 def test_exclude(self):
1094 tempdir = os.path.join(TEMPDIR, "exclude")
1095 os.mkdir(tempdir)
1096 try:
1097 for name in ("foo", "bar", "baz"):
1098 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001099 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +00001100
Benjamin Peterson886af962010-03-21 23:13:07 +00001101 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +00001102
1103 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001104 try:
1105 with support.check_warnings(("use the filter argument",
1106 DeprecationWarning)):
1107 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
1108 finally:
1109 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001110
1111 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001112 try:
1113 self.assertEqual(len(tar.getmembers()), 1)
1114 self.assertEqual(tar.getnames()[0], "empty_dir")
1115 finally:
1116 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001117 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001118 support.rmtree(tempdir)
Guido van Rossum486364b2007-06-30 05:01:58 +00001119
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001120 def test_filter(self):
1121 tempdir = os.path.join(TEMPDIR, "filter")
1122 os.mkdir(tempdir)
1123 try:
1124 for name in ("foo", "bar", "baz"):
1125 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001126 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001127
1128 def filter(tarinfo):
1129 if os.path.basename(tarinfo.name) == "bar":
1130 return
1131 tarinfo.uid = 123
1132 tarinfo.uname = "foo"
1133 return tarinfo
1134
1135 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001136 try:
1137 tar.add(tempdir, arcname="empty_dir", filter=filter)
1138 finally:
1139 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001140
Raymond Hettingera63a3122011-01-26 20:34:14 +00001141 # Verify that filter is a keyword-only argument
1142 with self.assertRaises(TypeError):
1143 tar.add(tempdir, "empty_dir", True, None, filter)
1144
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001145 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001146 try:
1147 for tarinfo in tar:
1148 self.assertEqual(tarinfo.uid, 123)
1149 self.assertEqual(tarinfo.uname, "foo")
1150 self.assertEqual(len(tar.getmembers()), 3)
1151 finally:
1152 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001153 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001154 support.rmtree(tempdir)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001155
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001156 # Guarantee that stored pathnames are not modified. Don't
1157 # remove ./ or ../ or double slashes. Still make absolute
1158 # pathnames relative.
1159 # For details see bug #6054.
1160 def _test_pathname(self, path, cmp_path=None, dir=False):
1161 # Create a tarfile with an empty member named path
1162 # and compare the stored name with the original.
1163 foo = os.path.join(TEMPDIR, "foo")
1164 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001165 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001166 else:
1167 os.mkdir(foo)
1168
1169 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001170 try:
1171 tar.add(foo, arcname=path)
1172 finally:
1173 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001174
1175 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001176 try:
1177 t = tar.next()
1178 finally:
1179 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001180
1181 if not dir:
Victor Stinner57004c62014-09-04 00:49:01 +02001182 support.unlink(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001183 else:
Victor Stinner57004c62014-09-04 00:49:01 +02001184 support.rmdir(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001185
1186 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1187
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001188
1189 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001190 def test_extractall_symlinks(self):
1191 # Test if extractall works properly when tarfile contains symlinks
1192 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1193 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1194 os.mkdir(tempdir)
1195 try:
1196 source_file = os.path.join(tempdir,'source')
1197 target_file = os.path.join(tempdir,'symlink')
1198 with open(source_file,'w') as f:
1199 f.write('something\n')
1200 os.symlink(source_file, target_file)
1201 tar = tarfile.open(temparchive,'w')
1202 tar.add(source_file)
1203 tar.add(target_file)
1204 tar.close()
1205 # Let's extract it to the location which contains the symlink
1206 tar = tarfile.open(temparchive,'r')
1207 # this should not raise OSError: [Errno 17] File exists
1208 try:
1209 tar.extractall(path=tempdir)
1210 except OSError:
1211 self.fail("extractall failed with symlinked files")
1212 finally:
1213 tar.close()
1214 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001215 support.unlink(temparchive)
1216 support.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001217
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001218 def test_pathnames(self):
1219 self._test_pathname("foo")
1220 self._test_pathname(os.path.join("foo", ".", "bar"))
1221 self._test_pathname(os.path.join("foo", "..", "bar"))
1222 self._test_pathname(os.path.join(".", "foo"))
1223 self._test_pathname(os.path.join(".", "foo", "."))
1224 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1225 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1226 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1227 self._test_pathname(os.path.join("..", "foo"))
1228 self._test_pathname(os.path.join("..", "foo", ".."))
1229 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1230 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1231
1232 self._test_pathname("foo" + os.sep + os.sep + "bar")
1233 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1234
1235 def test_abs_pathnames(self):
1236 if sys.platform == "win32":
1237 self._test_pathname("C:\\foo", "foo")
1238 else:
1239 self._test_pathname("/foo", "foo")
1240 self._test_pathname("///foo", "foo")
1241
1242 def test_cwd(self):
1243 # Test adding the current working directory.
1244 cwd = os.getcwd()
1245 os.chdir(TEMPDIR)
1246 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001247 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001248 try:
1249 tar.add(".")
1250 finally:
1251 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001252
1253 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001254 try:
1255 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001256 if t.name != ".":
1257 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001258 finally:
1259 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001260 finally:
1261 os.chdir(cwd)
1262
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001263 def test_open_nonwritable_fileobj(self):
1264 for exctype in OSError, EOFError, RuntimeError:
1265 class BadFile(io.BytesIO):
1266 first = True
1267 def write(self, data):
1268 if self.first:
1269 self.first = False
1270 raise exctype
1271
1272 f = BadFile()
1273 with self.assertRaises(exctype):
1274 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1275 format=tarfile.PAX_FORMAT,
1276 pax_headers={'non': 'empty'})
1277 self.assertFalse(f.closed)
1278
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001279class GzipWriteTest(GzipTest, WriteTest):
1280 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001281
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001282class Bz2WriteTest(Bz2Test, WriteTest):
1283 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001284
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001285class LzmaWriteTest(LzmaTest, WriteTest):
1286 pass
1287
1288
1289class StreamWriteTest(WriteTestBase, unittest.TestCase):
1290
1291 prefix = "w|"
1292 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001293
Guido van Rossumd8faa362007-04-27 19:54:29 +00001294 def test_stream_padding(self):
1295 # Test for bug #1543303.
1296 tar = tarfile.open(tmpname, self.mode)
1297 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001298 if self.decompressor:
1299 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001300 with open(tmpname, "rb") as fobj:
1301 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001302 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001303 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001304 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001305 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001306 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001307 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1308 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001309
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001310 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1311 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001312 def test_file_mode(self):
1313 # Test for issue #8464: Create files with correct
1314 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001315 if os.path.exists(tmpname):
Victor Stinner57004c62014-09-04 00:49:01 +02001316 support.unlink(tmpname)
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001317
1318 original_umask = os.umask(0o022)
1319 try:
1320 tar = tarfile.open(tmpname, self.mode)
1321 tar.close()
1322 mode = os.stat(tmpname).st_mode & 0o777
1323 self.assertEqual(mode, 0o644, "wrong file permissions")
1324 finally:
1325 os.umask(original_umask)
1326
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001327class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1328 pass
1329
1330class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1331 decompressor = bz2.BZ2Decompressor if bz2 else None
1332
1333class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1334 decompressor = lzma.LZMADecompressor if lzma else None
1335
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001336
Guido van Rossumd8faa362007-04-27 19:54:29 +00001337class GNUWriteTest(unittest.TestCase):
1338 # This testcase checks for correct creation of GNU Longname
1339 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001340
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001341 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001342 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001343 return blocks * 512
1344
1345 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001346 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001347 count = 512
1348
1349 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001350 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001351 count += 512
1352 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001353 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001354 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001355 count += 512
1356 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001357 return count
1358
1359 def _test(self, name, link=None):
1360 tarinfo = tarfile.TarInfo(name)
1361 if link:
1362 tarinfo.linkname = link
1363 tarinfo.type = tarfile.LNKTYPE
1364
Guido van Rossumd8faa362007-04-27 19:54:29 +00001365 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001366 try:
1367 tar.format = tarfile.GNU_FORMAT
1368 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001369
Antoine Pitrou95f55602010-09-23 18:36:46 +00001370 v1 = self._calc_size(name, link)
1371 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001372 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001373 finally:
1374 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001375
Guido van Rossumd8faa362007-04-27 19:54:29 +00001376 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001377 try:
1378 member = tar.next()
1379 self.assertIsNotNone(member,
1380 "unable to read longname member")
1381 self.assertEqual(tarinfo.name, member.name,
1382 "unable to read longname member")
1383 self.assertEqual(tarinfo.linkname, member.linkname,
1384 "unable to read longname member")
1385 finally:
1386 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001387
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001388 def test_longname_1023(self):
1389 self._test(("longnam/" * 127) + "longnam")
1390
1391 def test_longname_1024(self):
1392 self._test(("longnam/" * 127) + "longname")
1393
1394 def test_longname_1025(self):
1395 self._test(("longnam/" * 127) + "longname_")
1396
1397 def test_longlink_1023(self):
1398 self._test("name", ("longlnk/" * 127) + "longlnk")
1399
1400 def test_longlink_1024(self):
1401 self._test("name", ("longlnk/" * 127) + "longlink")
1402
1403 def test_longlink_1025(self):
1404 self._test("name", ("longlnk/" * 127) + "longlink_")
1405
1406 def test_longnamelink_1023(self):
1407 self._test(("longnam/" * 127) + "longnam",
1408 ("longlnk/" * 127) + "longlnk")
1409
1410 def test_longnamelink_1024(self):
1411 self._test(("longnam/" * 127) + "longname",
1412 ("longlnk/" * 127) + "longlink")
1413
1414 def test_longnamelink_1025(self):
1415 self._test(("longnam/" * 127) + "longname_",
1416 ("longlnk/" * 127) + "longlink_")
1417
Guido van Rossumd8faa362007-04-27 19:54:29 +00001418
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001419@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001420class HardlinkTest(unittest.TestCase):
1421 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001422
1423 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001424 self.foo = os.path.join(TEMPDIR, "foo")
1425 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001426
Antoine Pitrou95f55602010-09-23 18:36:46 +00001427 with open(self.foo, "wb") as fobj:
1428 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001429
Guido van Rossumd8faa362007-04-27 19:54:29 +00001430 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001431
Guido van Rossumd8faa362007-04-27 19:54:29 +00001432 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001433 self.tar.add(self.foo)
1434
Guido van Rossumd8faa362007-04-27 19:54:29 +00001435 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001436 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001437 support.unlink(self.foo)
1438 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001439
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001440 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001441 # The same name will be added as a REGTYPE every
1442 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001443 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001444 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001445 "add file as regular failed")
1446
1447 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001448 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001449 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001450 "add file as hardlink failed")
1451
1452 def test_dereference_hardlink(self):
1453 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001454 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001455 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001456 "dereferencing hardlink failed")
1457
Neal Norwitza4f651a2004-07-20 22:07:44 +00001458
Guido van Rossumd8faa362007-04-27 19:54:29 +00001459class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001460
Guido van Rossumd8faa362007-04-27 19:54:29 +00001461 def _test(self, name, link=None):
1462 # See GNUWriteTest.
1463 tarinfo = tarfile.TarInfo(name)
1464 if link:
1465 tarinfo.linkname = link
1466 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001467
Guido van Rossumd8faa362007-04-27 19:54:29 +00001468 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001469 try:
1470 tar.addfile(tarinfo)
1471 finally:
1472 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001473
Guido van Rossumd8faa362007-04-27 19:54:29 +00001474 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001475 try:
1476 if link:
1477 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001478 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001479 else:
1480 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001481 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001482 finally:
1483 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001484
Guido van Rossume7ba4952007-06-06 23:52:48 +00001485 def test_pax_global_header(self):
1486 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001487 "foo": "bar",
1488 "uid": "0",
1489 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001490 "test": "\xe4\xf6\xfc",
1491 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001492
Benjamin Peterson886af962010-03-21 23:13:07 +00001493 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001494 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001495 try:
1496 tar.addfile(tarfile.TarInfo("test"))
1497 finally:
1498 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001499
1500 # Test if the global header was written correctly.
1501 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001502 try:
1503 self.assertEqual(tar.pax_headers, pax_headers)
1504 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1505 # Test if all the fields are strings.
1506 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001507 self.assertIsNot(type(key), bytes)
1508 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001509 if key in tarfile.PAX_NUMBER_FIELDS:
1510 try:
1511 tarfile.PAX_NUMBER_FIELDS[key](val)
1512 except (TypeError, ValueError):
1513 self.fail("unable to convert pax header field")
1514 finally:
1515 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001516
1517 def test_pax_extended_header(self):
1518 # The fields from the pax header have priority over the
1519 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001520 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001521
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001522 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1523 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001524 try:
1525 t = tarfile.TarInfo()
1526 t.name = "\xe4\xf6\xfc" # non-ASCII
1527 t.uid = 8**8 # too large
1528 t.pax_headers = pax_headers
1529 tar.addfile(t)
1530 finally:
1531 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001532
1533 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001534 try:
1535 t = tar.getmembers()[0]
1536 self.assertEqual(t.pax_headers, pax_headers)
1537 self.assertEqual(t.name, "foo")
1538 self.assertEqual(t.uid, 123)
1539 finally:
1540 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001541
1542
1543class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001544
1545 format = tarfile.USTAR_FORMAT
1546
1547 def test_iso8859_1_filename(self):
1548 self._test_unicode_filename("iso8859-1")
1549
1550 def test_utf7_filename(self):
1551 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001552
1553 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001554 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001555
Guido van Rossumd8faa362007-04-27 19:54:29 +00001556 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001557 tar = tarfile.open(tmpname, "w", format=self.format,
1558 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001559 try:
1560 name = "\xe4\xf6\xfc"
1561 tar.addfile(tarfile.TarInfo(name))
1562 finally:
1563 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001564
1565 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001566 try:
1567 self.assertEqual(tar.getmembers()[0].name, name)
1568 finally:
1569 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001570
1571 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001572 tar = tarfile.open(tmpname, "w", format=self.format,
1573 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001574 try:
1575 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001576
Antoine Pitrou95f55602010-09-23 18:36:46 +00001577 tarinfo.name = "\xe4\xf6\xfc"
1578 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001579
Antoine Pitrou95f55602010-09-23 18:36:46 +00001580 tarinfo.name = "foo"
1581 tarinfo.uname = "\xe4\xf6\xfc"
1582 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1583 finally:
1584 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001585
1586 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001587 tar = tarfile.open(tarname, "r",
1588 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001589 try:
1590 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001591 self.assertIs(type(t.name), str)
1592 self.assertIs(type(t.linkname), str)
1593 self.assertIs(type(t.uname), str)
1594 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001595 finally:
1596 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001597
Guido van Rossume7ba4952007-06-06 23:52:48 +00001598 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001599 t = tarfile.TarInfo("foo")
1600 t.uname = "\xe4\xf6\xfc"
1601 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001602
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001603 tar = tarfile.open(tmpname, mode="w", format=self.format,
1604 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001605 try:
1606 tar.addfile(t)
1607 finally:
1608 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001609
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001610 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001611 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001612 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001613 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1614 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1615
1616 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001617 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001618 tar = tarfile.open(tmpname, encoding="ascii")
1619 t = tar.getmember("foo")
1620 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1621 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1622 finally:
1623 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001624
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001625
Guido van Rossume7ba4952007-06-06 23:52:48 +00001626class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001627
Guido van Rossume7ba4952007-06-06 23:52:48 +00001628 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001629
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001630 def test_bad_pax_header(self):
1631 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1632 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001633 for encoding, name in (
1634 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001635 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001636 with tarfile.open(tarname, encoding=encoding,
1637 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001638 try:
1639 t = tar.getmember(name)
1640 except KeyError:
1641 self.fail("unable to read bad GNU tar pax header")
1642
Guido van Rossumd8faa362007-04-27 19:54:29 +00001643
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001644class PAXUnicodeTest(UstarUnicodeTest):
1645
1646 format = tarfile.PAX_FORMAT
1647
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001648 # PAX_FORMAT ignores encoding in write mode.
1649 test_unicode_filename_error = None
1650
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001651 def test_binary_header(self):
1652 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001653 for encoding, name in (
1654 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001655 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001656 with tarfile.open(tarname, encoding=encoding,
1657 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001658 try:
1659 t = tar.getmember(name)
1660 except KeyError:
1661 self.fail("unable to read POSIX.1-2008 binary header")
1662
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001663
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001664class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001665 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001666
Guido van Rossumd8faa362007-04-27 19:54:29 +00001667 def setUp(self):
1668 self.tarname = tmpname
1669 if os.path.exists(self.tarname):
Victor Stinner57004c62014-09-04 00:49:01 +02001670 support.unlink(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001671
Guido van Rossumd8faa362007-04-27 19:54:29 +00001672 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001673 with tarfile.open(tarname, encoding="iso8859-1") as src:
1674 t = src.getmember("ustar/regtype")
1675 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001676 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001677 with tarfile.open(self.tarname, mode) as tar:
1678 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001679
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001680 def test_append_compressed(self):
1681 self._create_testtar("w:" + self.suffix)
1682 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1683
1684class AppendTest(AppendTestBase, unittest.TestCase):
1685 test_append_compressed = None
1686
1687 def _add_testfile(self, fileobj=None):
1688 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1689 tar.addfile(tarfile.TarInfo("bar"))
1690
Guido van Rossumd8faa362007-04-27 19:54:29 +00001691 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001692 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1693 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001694
1695 def test_non_existing(self):
1696 self._add_testfile()
1697 self._test()
1698
1699 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001700 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001701 self._add_testfile()
1702 self._test()
1703
1704 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001705 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001706 self._add_testfile(fobj)
1707 fobj.seek(0)
1708 self._test(fileobj=fobj)
1709
1710 def test_fileobj(self):
1711 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001712 with open(self.tarname, "rb") as fobj:
1713 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001714 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001715 self._add_testfile(fobj)
1716 fobj.seek(0)
1717 self._test(names=["foo", "bar"], fileobj=fobj)
1718
1719 def test_existing(self):
1720 self._create_testtar()
1721 self._add_testfile()
1722 self._test(names=["foo", "bar"])
1723
Lars Gustäbel9520a432009-11-22 18:48:49 +00001724 # Append mode is supposed to fail if the tarfile to append to
1725 # does not end with a zero block.
1726 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001727 with open(self.tarname, "wb") as fobj:
1728 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001729 self.assertRaises(tarfile.ReadError, self._add_testfile)
1730
1731 def test_null(self):
1732 self._test_error(b"")
1733
1734 def test_incomplete(self):
1735 self._test_error(b"\0" * 13)
1736
1737 def test_premature_eof(self):
1738 data = tarfile.TarInfo("foo").tobuf()
1739 self._test_error(data)
1740
1741 def test_trailing_garbage(self):
1742 data = tarfile.TarInfo("foo").tobuf()
1743 self._test_error(data + b"\0" * 13)
1744
1745 def test_invalid(self):
1746 self._test_error(b"a" * 512)
1747
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001748class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
1749 pass
1750
1751class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
1752 pass
1753
1754class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
1755 pass
1756
Guido van Rossumd8faa362007-04-27 19:54:29 +00001757
1758class LimitsTest(unittest.TestCase):
1759
1760 def test_ustar_limits(self):
1761 # 100 char name
1762 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001763 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001764
1765 # 101 char name that cannot be stored
1766 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001767 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001768
1769 # 256 char name with a slash at pos 156
1770 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001771 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001772
1773 # 256 char name that cannot be stored
1774 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001775 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001776
1777 # 512 char name
1778 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001779 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001780
1781 # 512 char linkname
1782 tarinfo = tarfile.TarInfo("longlink")
1783 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001784 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001785
1786 # uid > 8 digits
1787 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001788 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001789 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001790
1791 def test_gnu_limits(self):
1792 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001793 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001794
1795 tarinfo = tarfile.TarInfo("longlink")
1796 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001797 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001798
1799 # uid >= 256 ** 7
1800 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001801 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001802 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001803
1804 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001805 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001806 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001807
1808 tarinfo = tarfile.TarInfo("longlink")
1809 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001810 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001811
1812 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001813 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001814 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001815
1816
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001817class MiscTest(unittest.TestCase):
1818
1819 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001820 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
1821 b"foo\0\0\0\0\0")
1822 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
1823 b"foo")
1824 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
1825 "foo")
1826 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
1827 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001828
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001829 def test_read_number_fields(self):
1830 # Issue 13158: Test if GNU tar specific base-256 number fields
1831 # are decoded correctly.
1832 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1833 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001834 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
1835 0o10000000)
1836 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
1837 0xffffffff)
1838 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
1839 -1)
1840 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
1841 -100)
1842 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
1843 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001844
1845 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001846 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001847 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001848 self.assertEqual(tarfile.itn(0o10000000),
1849 b"\x80\x00\x00\x00\x00\x20\x00\x00")
1850 self.assertEqual(tarfile.itn(0xffffffff),
1851 b"\x80\x00\x00\x00\xff\xff\xff\xff")
1852 self.assertEqual(tarfile.itn(-1),
1853 b"\xff\xff\xff\xff\xff\xff\xff\xff")
1854 self.assertEqual(tarfile.itn(-100),
1855 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1856 self.assertEqual(tarfile.itn(-0x100000000000000),
1857 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001858
1859 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001860 with self.assertRaises(ValueError):
1861 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
1862 with self.assertRaises(ValueError):
1863 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
1864 with self.assertRaises(ValueError):
1865 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
1866 with self.assertRaises(ValueError):
1867 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001868
1869
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001870class CommandLineTest(unittest.TestCase):
1871
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001872 def tarfilecmd(self, *args, **kwargs):
1873 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
1874 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01001875 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001876
1877 def tarfilecmd_failure(self, *args):
1878 return script_helper.assert_python_failure('-m', 'tarfile', *args)
1879
1880 def make_simple_tarfile(self, tar_name):
1881 files = [support.findfile('tokenize_tests.txt'),
1882 support.findfile('tokenize_tests-no-coding-cookie-'
1883 'and-utf8-bom-sig-only.txt')]
1884 self.addCleanup(support.unlink, tar_name)
1885 with tarfile.open(tar_name, 'w') as tf:
1886 for tardata in files:
1887 tf.add(tardata, arcname=os.path.basename(tardata))
1888
1889 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001890 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001891 for opt in '-t', '--test':
1892 out = self.tarfilecmd(opt, tar_name)
1893 self.assertEqual(out, b'')
1894
1895 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001896 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001897 for opt in '-v', '--verbose':
1898 out = self.tarfilecmd(opt, '-t', tar_name)
1899 self.assertIn(b'is a tar archive.\n', out)
1900
1901 def test_test_command_invalid_file(self):
1902 zipname = support.findfile('zipdir.zip')
1903 rc, out, err = self.tarfilecmd_failure('-t', zipname)
1904 self.assertIn(b' is not a tar archive.', err)
1905 self.assertEqual(out, b'')
1906 self.assertEqual(rc, 1)
1907
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001908 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001909 with self.subTest(tar_name=tar_name):
1910 with open(tar_name, 'rb') as f:
1911 data = f.read()
1912 try:
1913 with open(tmpname, 'wb') as f:
1914 f.write(data[:511])
1915 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
1916 self.assertEqual(out, b'')
1917 self.assertEqual(rc, 1)
1918 finally:
1919 support.unlink(tmpname)
1920
1921 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001922 for tar_name in testtarnames:
1923 with support.captured_stdout() as t:
1924 with tarfile.open(tar_name, 'r') as tf:
1925 tf.list(verbose=False)
1926 expected = t.getvalue().encode('ascii', 'backslashreplace')
1927 for opt in '-l', '--list':
1928 out = self.tarfilecmd(opt, tar_name,
1929 PYTHONIOENCODING='ascii')
1930 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001931
1932 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001933 for tar_name in testtarnames:
1934 with support.captured_stdout() as t:
1935 with tarfile.open(tar_name, 'r') as tf:
1936 tf.list(verbose=True)
1937 expected = t.getvalue().encode('ascii', 'backslashreplace')
1938 for opt in '-v', '--verbose':
1939 out = self.tarfilecmd(opt, '-l', tar_name,
1940 PYTHONIOENCODING='ascii')
1941 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001942
1943 def test_list_command_invalid_file(self):
1944 zipname = support.findfile('zipdir.zip')
1945 rc, out, err = self.tarfilecmd_failure('-l', zipname)
1946 self.assertIn(b' is not a tar archive.', err)
1947 self.assertEqual(out, b'')
1948 self.assertEqual(rc, 1)
1949
1950 def test_create_command(self):
1951 files = [support.findfile('tokenize_tests.txt'),
1952 support.findfile('tokenize_tests-no-coding-cookie-'
1953 'and-utf8-bom-sig-only.txt')]
1954 for opt in '-c', '--create':
1955 try:
1956 out = self.tarfilecmd(opt, tmpname, *files)
1957 self.assertEqual(out, b'')
1958 with tarfile.open(tmpname) as tar:
1959 tar.getmembers()
1960 finally:
1961 support.unlink(tmpname)
1962
1963 def test_create_command_verbose(self):
1964 files = [support.findfile('tokenize_tests.txt'),
1965 support.findfile('tokenize_tests-no-coding-cookie-'
1966 'and-utf8-bom-sig-only.txt')]
1967 for opt in '-v', '--verbose':
1968 try:
1969 out = self.tarfilecmd(opt, '-c', tmpname, *files)
1970 self.assertIn(b' file created.', out)
1971 with tarfile.open(tmpname) as tar:
1972 tar.getmembers()
1973 finally:
1974 support.unlink(tmpname)
1975
1976 def test_create_command_dotless_filename(self):
1977 files = [support.findfile('tokenize_tests.txt')]
1978 try:
1979 out = self.tarfilecmd('-c', dotlessname, *files)
1980 self.assertEqual(out, b'')
1981 with tarfile.open(dotlessname) as tar:
1982 tar.getmembers()
1983 finally:
1984 support.unlink(dotlessname)
1985
1986 def test_create_command_dot_started_filename(self):
1987 tar_name = os.path.join(TEMPDIR, ".testtar")
1988 files = [support.findfile('tokenize_tests.txt')]
1989 try:
1990 out = self.tarfilecmd('-c', tar_name, *files)
1991 self.assertEqual(out, b'')
1992 with tarfile.open(tar_name) as tar:
1993 tar.getmembers()
1994 finally:
1995 support.unlink(tar_name)
1996
1997 def test_extract_command(self):
1998 self.make_simple_tarfile(tmpname)
1999 for opt in '-e', '--extract':
2000 try:
2001 with support.temp_cwd(tarextdir):
2002 out = self.tarfilecmd(opt, tmpname)
2003 self.assertEqual(out, b'')
2004 finally:
2005 support.rmtree(tarextdir)
2006
2007 def test_extract_command_verbose(self):
2008 self.make_simple_tarfile(tmpname)
2009 for opt in '-v', '--verbose':
2010 try:
2011 with support.temp_cwd(tarextdir):
2012 out = self.tarfilecmd(opt, '-e', tmpname)
2013 self.assertIn(b' file is extracted.', out)
2014 finally:
2015 support.rmtree(tarextdir)
2016
2017 def test_extract_command_different_directory(self):
2018 self.make_simple_tarfile(tmpname)
2019 try:
2020 with support.temp_cwd(tarextdir):
2021 out = self.tarfilecmd('-e', tmpname, 'spamdir')
2022 self.assertEqual(out, b'')
2023 finally:
2024 support.rmtree(tarextdir)
2025
2026 def test_extract_command_invalid_file(self):
2027 zipname = support.findfile('zipdir.zip')
2028 with support.temp_cwd(tarextdir):
2029 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2030 self.assertIn(b' is not a tar archive.', err)
2031 self.assertEqual(out, b'')
2032 self.assertEqual(rc, 1)
2033
2034
Lars Gustäbel01385812010-03-03 12:08:54 +00002035class ContextManagerTest(unittest.TestCase):
2036
2037 def test_basic(self):
2038 with tarfile.open(tarname) as tar:
2039 self.assertFalse(tar.closed, "closed inside runtime context")
2040 self.assertTrue(tar.closed, "context manager failed")
2041
2042 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002043 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002044 # if the TarFile object is already closed.
2045 tar = tarfile.open(tarname)
2046 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002047 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002048 with tar:
2049 pass
2050
2051 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002052 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002053 with self.assertRaises(Exception) as exc:
2054 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002055 raise OSError
2056 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002057 "wrong exception raised in context manager")
2058 self.assertTrue(tar.closed, "context manager failed")
2059
2060 def test_no_eof(self):
2061 # __exit__() must not write end-of-archive blocks if an
2062 # exception was raised.
2063 try:
2064 with tarfile.open(tmpname, "w") as tar:
2065 raise Exception
2066 except:
2067 pass
2068 self.assertEqual(os.path.getsize(tmpname), 0,
2069 "context manager wrote an end-of-archive block")
2070 self.assertTrue(tar.closed, "context manager failed")
2071
2072 def test_eof(self):
2073 # __exit__() must write end-of-archive blocks, i.e. call
2074 # TarFile.close() if there was no error.
2075 with tarfile.open(tmpname, "w"):
2076 pass
2077 self.assertNotEqual(os.path.getsize(tmpname), 0,
2078 "context manager wrote no end-of-archive block")
2079
2080 def test_fileobj(self):
2081 # Test that __exit__() did not close the external file
2082 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002083 with open(tmpname, "wb") as fobj:
2084 try:
2085 with tarfile.open(fileobj=fobj, mode="w") as tar:
2086 raise Exception
2087 except:
2088 pass
2089 self.assertFalse(fobj.closed, "external file object was closed")
2090 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002091
2092
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002093@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2094class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002095
2096 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002097 # symbolic or hard links tarfile tries to extract these types of members
2098 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002099 def _test_link_extraction(self, name):
2100 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002101 with open(os.path.join(TEMPDIR, name), "rb") as f:
2102 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002103 self.assertEqual(md5sum(data), md5_regtype)
2104
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002105 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002106 @unittest.skipIf(hasattr(os.path, "islink"),
2107 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002108 def test_hardlink_extraction1(self):
2109 self._test_link_extraction("ustar/lnktype")
2110
Brian Curtind40e6f72010-07-08 21:39:08 +00002111 @unittest.skipIf(hasattr(os.path, "islink"),
2112 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002113 def test_hardlink_extraction2(self):
2114 self._test_link_extraction("./ustar/linktest2/lnktype")
2115
Brian Curtin74e45612010-07-09 15:58:59 +00002116 @unittest.skipIf(hasattr(os, "symlink"),
2117 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002118 def test_symlink_extraction1(self):
2119 self._test_link_extraction("ustar/symtype")
2120
Brian Curtin74e45612010-07-09 15:58:59 +00002121 @unittest.skipIf(hasattr(os, "symlink"),
2122 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002123 def test_symlink_extraction2(self):
2124 self._test_link_extraction("./ustar/linktest2/symtype")
2125
2126
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002127class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002128 # Issue5068: The _BZ2Proxy.read() method loops forever
2129 # on an empty or partial bzipped file.
2130
2131 def _test_partial_input(self, mode):
2132 class MyBytesIO(io.BytesIO):
2133 hit_eof = False
2134 def read(self, n):
2135 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002136 raise AssertionError("infinite loop detected in "
2137 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002138 self.hit_eof = self.tell() == len(self.getvalue())
2139 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002140 def seek(self, *args):
2141 self.hit_eof = False
2142 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002143
2144 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2145 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002146 try:
2147 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2148 except tarfile.ReadError:
2149 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002150
2151 def test_partial_input(self):
2152 self._test_partial_input("r")
2153
2154 def test_partial_input_bz2(self):
2155 self._test_partial_input("r:bz2")
2156
2157
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002158def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002159 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002160 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002161
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002162 global testtarnames
2163 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002164 with open(tarname, "rb") as fobj:
2165 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002166
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002167 # Create compressed tarfiles.
2168 for c in GzipTest, Bz2Test, LzmaTest:
2169 if c.open:
2170 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002171 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002172 with c.open(c.tarname, "wb") as tar:
2173 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002174
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002175def tearDownModule():
2176 if os.path.exists(TEMPDIR):
Victor Stinner57004c62014-09-04 00:49:01 +02002177 support.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002178
Neal Norwitz996acf12003-02-17 14:51:41 +00002179if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002180 unittest.main()