blob: ab88be41b725d449c9a7d8684cc06e68db70979b [file] [log] [blame]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001import sys
2import os
Lars Gustäbelb506dc32007-08-07 18:36:16 +00003import io
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00004import shutil
Guido van Rossuma8add0e2007-05-14 22:03:55 +00005from hashlib import md5
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00006
7import unittest
8import tarfile
9
Serhiy Storchakad27b4552013-11-24 01:53:29 +020010from test import support, script_helper
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000011
12# Check for our compression modules.
13try:
14 import gzip
Brett Cannon260fbe82013-07-04 18:16:15 -040015except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000016 gzip = None
17try:
18 import bz2
Brett Cannon260fbe82013-07-04 18:16:15 -040019except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000020 bz2 = None
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010021try:
22 import lzma
Brett Cannon260fbe82013-07-04 18:16:15 -040023except ImportError:
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010024 lzma = None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000025
Guido van Rossumd8faa362007-04-27 19:54:29 +000026def md5sum(data):
Guido van Rossuma8add0e2007-05-14 22:03:55 +000027 return md5(data).hexdigest()
Guido van Rossumd8faa362007-04-27 19:54:29 +000028
Antoine Pitrouab58b5f2010-09-23 19:39:35 +000029TEMPDIR = os.path.abspath(support.TESTFN) + "-tardir"
Serhiy Storchakad27b4552013-11-24 01:53:29 +020030tarextdir = TEMPDIR + '-extract-test'
Antoine Pitrou941ee882009-11-11 20:59:38 +000031tarname = support.findfile("testtar.tar")
Guido van Rossumd8faa362007-04-27 19:54:29 +000032gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
33bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010034xzname = os.path.join(TEMPDIR, "testtar.tar.xz")
Guido van Rossumd8faa362007-04-27 19:54:29 +000035tmpname = os.path.join(TEMPDIR, "tmp.tar")
Serhiy Storchakad27b4552013-11-24 01:53:29 +020036dotlessname = os.path.join(TEMPDIR, "testtar")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000037
Guido van Rossumd8faa362007-04-27 19:54:29 +000038md5_regtype = "65f477c818ad9e15f7feab0c6d37742f"
39md5_sparse = "a54fbc4ca4f4399a90e1b27164012fc6"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000040
41
Serhiy Storchaka8b562922013-06-17 15:38:50 +030042class TarTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +000043 tarname = tarname
Serhiy Storchaka8b562922013-06-17 15:38:50 +030044 suffix = ''
45 open = io.FileIO
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020046 taropen = tarfile.TarFile.taropen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030047
48 @property
49 def mode(self):
50 return self.prefix + self.suffix
51
52@support.requires_gzip
53class GzipTest:
54 tarname = gzipname
55 suffix = 'gz'
56 open = gzip.GzipFile if gzip else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020057 taropen = tarfile.TarFile.gzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030058
59@support.requires_bz2
60class Bz2Test:
61 tarname = bz2name
62 suffix = 'bz2'
63 open = bz2.BZ2File if bz2 else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020064 taropen = tarfile.TarFile.bz2open
Serhiy Storchaka8b562922013-06-17 15:38:50 +030065
66@support.requires_lzma
67class LzmaTest:
68 tarname = xzname
69 suffix = 'xz'
70 open = lzma.LZMAFile if lzma else None
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +020071 taropen = tarfile.TarFile.xzopen
Serhiy Storchaka8b562922013-06-17 15:38:50 +030072
73
74class ReadTest(TarTest):
75
76 prefix = "r:"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000077
78 def setUp(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +030079 self.tar = tarfile.open(self.tarname, mode=self.mode,
80 encoding="iso8859-1")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000081
82 def tearDown(self):
83 self.tar.close()
84
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000085
Serhiy Storchaka8b562922013-06-17 15:38:50 +030086class UstarReadTest(ReadTest, unittest.TestCase):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000087
Guido van Rossumd8faa362007-04-27 19:54:29 +000088 def test_fileobj_regular_file(self):
89 tarinfo = self.tar.getmember("ustar/regtype")
Lars Gustäbel7a919e92012-05-05 18:15:03 +020090 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000091 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +030092 self.assertEqual(len(data), tarinfo.size,
93 "regular file extraction failed")
94 self.assertEqual(md5sum(data), md5_regtype,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +000095 "regular file extraction failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000096
Guido van Rossumd8faa362007-04-27 19:54:29 +000097 def test_fileobj_readlines(self):
98 self.tar.extract("ustar/regtype", TEMPDIR)
99 tarinfo = self.tar.getmember("ustar/regtype")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000100 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
101 lines1 = fobj1.readlines()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000102
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200103 with self.tar.extractfile(tarinfo) as fobj:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000104 fobj2 = io.TextIOWrapper(fobj)
105 lines2 = fobj2.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300106 self.assertEqual(lines1, lines2,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000107 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300108 self.assertEqual(len(lines2), 114,
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000109 "fileobj.readlines() failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300110 self.assertEqual(lines2[83],
111 "I will gladly admit that Python is not the fastest "
112 "running scripting language.\n",
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000113 "fileobj.readlines() failed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000114
Guido van Rossumd8faa362007-04-27 19:54:29 +0000115 def test_fileobj_iter(self):
116 self.tar.extract("ustar/regtype", TEMPDIR)
117 tarinfo = self.tar.getmember("ustar/regtype")
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200118 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000119 lines1 = fobj1.readlines()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200120 with self.tar.extractfile(tarinfo) as fobj2:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000121 lines2 = list(io.TextIOWrapper(fobj2))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300122 self.assertEqual(lines1, lines2,
123 "fileobj.__iter__() failed")
Martin v. Löwisdf241532005-03-03 08:17:42 +0000124
Guido van Rossumd8faa362007-04-27 19:54:29 +0000125 def test_fileobj_seek(self):
126 self.tar.extract("ustar/regtype", TEMPDIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000127 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
128 data = fobj.read()
Neal Norwitzf3396542005-10-28 05:52:22 +0000129
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130 tarinfo = self.tar.getmember("ustar/regtype")
131 fobj = self.tar.extractfile(tarinfo)
132
133 text = fobj.read()
134 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000135 self.assertEqual(0, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000136 "seek() to file's start failed")
137 fobj.seek(2048, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000138 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000139 "seek() to absolute position failed")
140 fobj.seek(-1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000141 self.assertEqual(1024, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000142 "seek() to negative relative position failed")
143 fobj.seek(1024, 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000144 self.assertEqual(2048, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000145 "seek() to positive relative position failed")
146 s = fobj.read(10)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300147 self.assertEqual(s, data[2048:2058],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148 "read() after seek failed")
149 fobj.seek(0, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000150 self.assertEqual(tarinfo.size, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000151 "seek() to file's end failed")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300152 self.assertEqual(fobj.read(), b"",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000153 "read() at file's end did not return empty string")
154 fobj.seek(-tarinfo.size, 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000155 self.assertEqual(0, fobj.tell(),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000156 "relative seek() to file's end failed")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000157 fobj.seek(512)
158 s1 = fobj.readlines()
159 fobj.seek(512)
160 s2 = fobj.readlines()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300161 self.assertEqual(s1, s2,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000162 "readlines() after seek failed")
163 fobj.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000164 self.assertEqual(len(fobj.readline()), fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000165 "tell() after readline() failed")
166 fobj.seek(512)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300167 self.assertEqual(len(fobj.readline()) + 512, fobj.tell(),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000168 "tell() after seek() and readline() failed")
169 fobj.seek(0)
170 line = fobj.readline()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000171 self.assertEqual(fobj.read(), data[len(line):],
Guido van Rossumd8faa362007-04-27 19:54:29 +0000172 "read() after readline() failed")
173 fobj.close()
174
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200175 def test_fileobj_text(self):
176 with self.tar.extractfile("ustar/regtype") as fobj:
177 fobj = io.TextIOWrapper(fobj)
178 data = fobj.read().encode("iso8859-1")
179 self.assertEqual(md5sum(data), md5_regtype)
180 try:
181 fobj.seek(100)
182 except AttributeError:
183 # Issue #13815: seek() complained about a missing
184 # flush() method.
185 self.fail("seeking failed in text mode")
186
Lars Gustäbel1b512722010-06-03 12:45:16 +0000187 # Test if symbolic and hard links are resolved by extractfile(). The
188 # test link members each point to a regular member whose data is
189 # supposed to be exported.
190 def _test_fileobj_link(self, lnktype, regtype):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300191 with self.tar.extractfile(lnktype) as a, \
192 self.tar.extractfile(regtype) as b:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000193 self.assertEqual(a.name, b.name)
Lars Gustäbel1b512722010-06-03 12:45:16 +0000194
195 def test_fileobj_link1(self):
196 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
197
198 def test_fileobj_link2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300199 self._test_fileobj_link("./ustar/linktest2/lnktype",
200 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000201
202 def test_fileobj_symlink1(self):
203 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
204
205 def test_fileobj_symlink2(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300206 self._test_fileobj_link("./ustar/linktest2/symtype",
207 "ustar/linktest1/regtype")
Lars Gustäbel1b512722010-06-03 12:45:16 +0000208
Lars Gustäbel1ef9eda2012-04-24 21:04:40 +0200209 def test_issue14160(self):
210 self._test_fileobj_link("symtype2", "ustar/regtype")
211
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300212class GzipUstarReadTest(GzipTest, UstarReadTest):
213 pass
214
215class Bz2UstarReadTest(Bz2Test, UstarReadTest):
216 pass
217
218class LzmaUstarReadTest(LzmaTest, UstarReadTest):
219 pass
220
Guido van Rossumd8faa362007-04-27 19:54:29 +0000221
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200222class ListTest(ReadTest, unittest.TestCase):
223
224 # Override setUp to use default encoding (UTF-8)
225 def setUp(self):
226 self.tar = tarfile.open(self.tarname, mode=self.mode)
227
228 def test_list(self):
229 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
230 with support.swap_attr(sys, 'stdout', tio):
231 self.tar.list(verbose=False)
232 out = tio.detach().getvalue()
233 self.assertIn(b'ustar/conttype', out)
234 self.assertIn(b'ustar/regtype', out)
235 self.assertIn(b'ustar/lnktype', out)
236 self.assertIn(b'ustar' + (b'/12345' * 40) + b'67/longname', out)
237 self.assertIn(b'./ustar/linktest2/symtype', out)
238 self.assertIn(b'./ustar/linktest2/lnktype', out)
239 # Make sure it puts trailing slash for directory
240 self.assertIn(b'ustar/dirtype/', out)
241 self.assertIn(b'ustar/dirtype-with-size/', out)
242 # Make sure it is able to print unencodable characters
243 self.assertIn(br'ustar/umlauts-'
244 br'\udcc4\udcd6\udcdc\udce4\udcf6\udcfc\udcdf', out)
245 self.assertIn(br'misc/regtype-hpux-signed-chksum-'
246 br'\udcc4\udcd6\udcdc\udce4\udcf6\udcfc\udcdf', out)
247 self.assertIn(br'misc/regtype-old-v7-signed-chksum-'
248 br'\udcc4\udcd6\udcdc\udce4\udcf6\udcfc\udcdf', out)
249 self.assertIn(br'pax/bad-pax-\udce4\udcf6\udcfc', out)
250 self.assertIn(br'pax/hdrcharset-\udce4\udcf6\udcfc', out)
251 # Make sure it prints files separated by one newline without any
252 # 'ls -l'-like accessories if verbose flag is not being used
253 # ...
254 # ustar/conttype
255 # ustar/regtype
256 # ...
257 self.assertRegex(out, br'ustar/conttype ?\r?\n'
258 br'ustar/regtype ?\r?\n')
259 # Make sure it does not print the source of link without verbose flag
260 self.assertNotIn(b'link to', out)
261 self.assertNotIn(b'->', out)
262
263 def test_list_verbose(self):
264 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
265 with support.swap_attr(sys, 'stdout', tio):
266 self.tar.list(verbose=True)
267 out = tio.detach().getvalue()
268 # Make sure it prints files separated by one newline with 'ls -l'-like
269 # accessories if verbose flag is being used
270 # ...
271 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
272 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
273 # ...
Serhiy Storchaka255493c2014-02-05 20:54:43 +0200274 self.assertRegex(out, (br'\?rw-r--r-- tarfile/tarfile\s+7011 '
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200275 br'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
276 br'ustar/\w+type ?\r?\n') * 2)
277 # Make sure it prints the source of link with verbose flag
278 self.assertIn(b'ustar/symtype -> regtype', out)
279 self.assertIn(b'./ustar/linktest2/symtype -> ../linktest1/regtype', out)
280 self.assertIn(b'./ustar/linktest2/lnktype link to '
281 b'./ustar/linktest1/regtype', out)
282 self.assertIn(b'gnu' + (b'/123' * 125) + b'/longlink link to gnu' +
283 (b'/123' * 125) + b'/longname', out)
284 self.assertIn(b'pax' + (b'/123' * 125) + b'/longlink link to pax' +
285 (b'/123' * 125) + b'/longname', out)
286
287
288class GzipListTest(GzipTest, ListTest):
289 pass
290
291
292class Bz2ListTest(Bz2Test, ListTest):
293 pass
294
295
296class LzmaListTest(LzmaTest, ListTest):
297 pass
298
299
Lars Gustäbel9520a432009-11-22 18:48:49 +0000300class CommonReadTest(ReadTest):
301
302 def test_empty_tarfile(self):
303 # Test for issue6123: Allow opening empty archives.
304 # This test checks if tarfile.open() is able to open an empty tar
305 # archive successfully. Note that an empty tar archive is not the
306 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000307 with tarfile.open(tmpname, self.mode.replace("r", "w")):
308 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000309 try:
310 tar = tarfile.open(tmpname, self.mode)
311 tar.getnames()
312 except tarfile.ReadError:
313 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000314 else:
315 self.assertListEqual(tar.getmembers(), [])
316 finally:
317 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000318
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200319 def test_non_existent_tarfile(self):
320 # Test for issue11513: prevent non-existent gzipped tarfiles raising
321 # multiple exceptions.
322 with self.assertRaisesRegex(FileNotFoundError, "xxx"):
323 tarfile.open("xxx", self.mode)
324
Lars Gustäbel9520a432009-11-22 18:48:49 +0000325 def test_null_tarfile(self):
326 # Test for issue6123: Allow opening empty archives.
327 # This test guarantees that tarfile.open() does not treat an empty
328 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000329 with open(tmpname, "wb"):
330 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000331 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
332 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
333
334 def test_ignore_zeros(self):
335 # Test TarFile's ignore_zeros option.
Lars Gustäbel9520a432009-11-22 18:48:49 +0000336 for char in (b'\0', b'a'):
337 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
338 # are ignored correctly.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300339 with self.open(tmpname, "w") as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000340 fobj.write(char * 1024)
341 fobj.write(tarfile.TarInfo("foo").tobuf())
Lars Gustäbel9520a432009-11-22 18:48:49 +0000342
343 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000344 try:
345 self.assertListEqual(tar.getnames(), ["foo"],
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300346 "ignore_zeros=True should have skipped the %r-blocks" %
347 char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000348 finally:
349 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000350
351
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300352class MiscReadTestBase(CommonReadTest):
Thomas Woutersed03b412007-08-28 21:37:11 +0000353 def test_no_name_argument(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000354 with open(self.tarname, "rb") as fobj:
355 tar = tarfile.open(fileobj=fobj, mode=self.mode)
356 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000357
Thomas Woutersed03b412007-08-28 21:37:11 +0000358 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000359 with open(self.tarname, "rb") as fobj:
360 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000361 fobj = io.BytesIO(data)
362 self.assertRaises(AttributeError, getattr, fobj, "name")
363 tar = tarfile.open(fileobj=fobj, mode=self.mode)
364 self.assertEqual(tar.name, None)
365
366 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000367 with open(self.tarname, "rb") as fobj:
368 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000369 fobj = io.BytesIO(data)
370 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000371 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
372 self.assertEqual(tar.name, None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000373
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +0200374 def test_illegal_mode_arg(self):
375 with open(tmpname, 'wb'):
376 pass
377 with self.assertRaisesRegex(ValueError, 'mode must be '):
378 tar = self.taropen(tmpname, 'q')
379 with self.assertRaisesRegex(ValueError, 'mode must be '):
380 tar = self.taropen(tmpname, 'rw')
381 with self.assertRaisesRegex(ValueError, 'mode must be '):
382 tar = self.taropen(tmpname, '')
383
Christian Heimesd8654cf2007-12-02 15:22:16 +0000384 def test_fileobj_with_offset(self):
385 # Skip the first member and store values from the second member
386 # of the testtar.
387 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000388 try:
389 tar.next()
390 t = tar.next()
391 name = t.name
392 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200393 with tar.extractfile(t) as f:
394 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000395 finally:
396 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000397
398 # Open the testtar and seek to the offset of the second member.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300399 with self.open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000400 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000401
Antoine Pitrou95f55602010-09-23 18:36:46 +0000402 # Test if the tarfile starts with the second member.
403 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
404 t = tar.next()
405 self.assertEqual(t.name, name)
406 # Read to the end of fileobj and test if seeking back to the
407 # beginning works.
408 tar.getmembers()
409 self.assertEqual(tar.extractfile(t).read(), data,
410 "seek back did not work")
411 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000412
Guido van Rossumd8faa362007-04-27 19:54:29 +0000413 def test_fail_comp(self):
414 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000415 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000416 with open(tarname, "rb") as fobj:
417 self.assertRaises(tarfile.ReadError, tarfile.open,
418 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000419
420 def test_v7_dirtype(self):
421 # Test old style dirtype member (bug #1336623):
422 # Old V7 tars create directory members using an AREGTYPE
423 # header with a "/" appended to the filename field.
424 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300425 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000426 "v7 dirtype failed")
427
Christian Heimes126d29a2008-02-11 22:57:17 +0000428 def test_xstar_type(self):
429 # The xstar format stores extra atime and ctime fields inside the
430 # space reserved for the prefix field. The prefix field must be
431 # ignored in this case, otherwise it will mess up the name.
432 try:
433 self.tar.getmember("misc/regtype-xstar")
434 except KeyError:
435 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
436
Guido van Rossumd8faa362007-04-27 19:54:29 +0000437 def test_check_members(self):
438 for tarinfo in self.tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300439 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000440 "wrong mtime for %s" % tarinfo.name)
441 if not tarinfo.name.startswith("ustar/"):
442 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300443 self.assertEqual(tarinfo.uname, "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000444 "wrong uname for %s" % tarinfo.name)
445
446 def test_find_members(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300447 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000448 "could not find all members")
449
Brian Curtin74e45612010-07-09 15:58:59 +0000450 @unittest.skipUnless(hasattr(os, "link"),
451 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000452 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000453 def test_extract_hardlink(self):
454 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200455 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000456 tar.extract("ustar/regtype", TEMPDIR)
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200457 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000458
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200459 tar.extract("ustar/lnktype", TEMPDIR)
460 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000461 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
462 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000463 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000464
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200465 tar.extract("ustar/symtype", TEMPDIR)
466 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000467 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
468 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000469 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000470
Christian Heimesfaf2f632008-01-06 16:59:19 +0000471 def test_extractall(self):
472 # Test if extractall() correctly restores directory permissions
473 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000474 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000475 DIR = os.path.join(TEMPDIR, "extractall")
476 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000477 try:
478 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000479 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000480 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000481 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000482 if sys.platform != "win32":
483 # Win32 has no support for fine grained permissions.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300484 self.assertEqual(tarinfo.mode & 0o777,
485 os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000486 def format_mtime(mtime):
487 if isinstance(mtime, float):
488 return "{} ({})".format(mtime, mtime.hex())
489 else:
490 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000491 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000492 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
493 format_mtime(tarinfo.mtime),
494 format_mtime(file_mtime),
495 path)
496 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000497 finally:
498 tar.close()
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000499 shutil.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000500
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000501 def test_extract_directory(self):
502 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000503 DIR = os.path.join(TEMPDIR, "extractdir")
504 os.mkdir(DIR)
505 try:
506 with tarfile.open(tarname, encoding="iso8859-1") as tar:
507 tarinfo = tar.getmember(dirtype)
508 tar.extract(tarinfo, path=DIR)
509 extracted = os.path.join(DIR, dirtype)
510 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
511 if sys.platform != "win32":
512 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
513 finally:
514 shutil.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000515
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000516 def test_init_close_fobj(self):
517 # Issue #7341: Close the internal file object in the TarFile
518 # constructor in case of an error. For the test we rely on
519 # the fact that opening an empty file raises a ReadError.
520 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000521 with open(empty, "wb") as fobj:
522 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000523
524 try:
525 tar = object.__new__(tarfile.TarFile)
526 try:
527 tar.__init__(empty)
528 except tarfile.ReadError:
529 self.assertTrue(tar.fileobj.closed)
530 else:
531 self.fail("ReadError not raised")
532 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000533 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000534
Serhiy Storchaka263fab92013-05-09 14:22:26 +0300535 def test_parallel_iteration(self):
536 # Issue #16601: Restarting iteration over tarfile continued
537 # from where it left off.
538 with tarfile.open(self.tarname) as tar:
539 for m1, m2 in zip(tar, tar):
540 self.assertEqual(m1.offset, m2.offset)
541 self.assertEqual(m1.get_info(), m2.get_info())
542
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300543class MiscReadTest(MiscReadTestBase, unittest.TestCase):
544 test_fail_comp = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000545
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300546class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200547 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000548
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300549class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
550 def test_no_name_argument(self):
551 self.skipTest("BZ2File have no name attribute")
552
553class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
554 def test_no_name_argument(self):
555 self.skipTest("LZMAFile have no name attribute")
556
557
558class StreamReadTest(CommonReadTest, unittest.TestCase):
559
560 prefix="r|"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561
Lars Gustäbeldd071042011-02-23 11:42:22 +0000562 def test_read_through(self):
563 # Issue #11224: A poorly designed _FileInFile.read() method
564 # caused seeking errors with stream tar files.
565 for tarinfo in self.tar:
566 if not tarinfo.isreg():
567 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200568 with self.tar.extractfile(tarinfo) as fobj:
569 while True:
570 try:
571 buf = fobj.read(512)
572 except tarfile.StreamError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300573 self.fail("simple read-through using "
574 "TarFile.extractfile() failed")
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200575 if not buf:
576 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000577
Guido van Rossumd8faa362007-04-27 19:54:29 +0000578 def test_fileobj_regular_file(self):
579 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200580 with self.tar.extractfile(tarinfo) as fobj:
581 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300582 self.assertEqual(len(data), tarinfo.size,
583 "regular file extraction failed")
584 self.assertEqual(md5sum(data), md5_regtype,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000585 "regular file extraction failed")
586
587 def test_provoke_stream_error(self):
588 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200589 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
590 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000591
Guido van Rossumd8faa362007-04-27 19:54:29 +0000592 def test_compare_members(self):
593 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000594 try:
595 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000596
Antoine Pitrou95f55602010-09-23 18:36:46 +0000597 while True:
598 t1 = tar1.next()
599 t2 = tar2.next()
600 if t1 is None:
601 break
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300602 self.assertIsNotNone(t2, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000603
Antoine Pitrou95f55602010-09-23 18:36:46 +0000604 if t2.islnk() or t2.issym():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300605 with self.assertRaises(tarfile.StreamError):
606 tar2.extractfile(t2)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000607 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000608
Antoine Pitrou95f55602010-09-23 18:36:46 +0000609 v1 = tar1.extractfile(t1)
610 v2 = tar2.extractfile(t2)
611 if v1 is None:
612 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300613 self.assertIsNotNone(v2, "stream.extractfile() failed")
614 self.assertEqual(v1.read(), v2.read(),
615 "stream extraction failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000616 finally:
617 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000618
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300619class GzipStreamReadTest(GzipTest, StreamReadTest):
620 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000621
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300622class Bz2StreamReadTest(Bz2Test, StreamReadTest):
623 pass
Thomas Wouterscf297e42007-02-23 15:07:44 +0000624
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300625class LzmaStreamReadTest(LzmaTest, StreamReadTest):
626 pass
627
628
629class DetectReadTest(TarTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000630 def _testfunc_file(self, name, mode):
631 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000632 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000633 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000634 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000635 else:
636 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000637
Guido van Rossumd8faa362007-04-27 19:54:29 +0000638 def _testfunc_fileobj(self, name, mode):
639 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000640 with open(name, "rb") as f:
641 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000642 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000643 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000644 else:
645 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000646
647 def _test_modes(self, testfunc):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300648 if self.suffix:
649 with self.assertRaises(tarfile.ReadError):
650 tarfile.open(tarname, mode="r:" + self.suffix)
651 with self.assertRaises(tarfile.ReadError):
652 tarfile.open(tarname, mode="r|" + self.suffix)
653 with self.assertRaises(tarfile.ReadError):
654 tarfile.open(self.tarname, mode="r:")
655 with self.assertRaises(tarfile.ReadError):
656 tarfile.open(self.tarname, mode="r|")
657 testfunc(self.tarname, "r")
658 testfunc(self.tarname, "r:" + self.suffix)
659 testfunc(self.tarname, "r:*")
660 testfunc(self.tarname, "r|" + self.suffix)
661 testfunc(self.tarname, "r|*")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100662
Guido van Rossumd8faa362007-04-27 19:54:29 +0000663 def test_detect_file(self):
664 self._test_modes(self._testfunc_file)
665
666 def test_detect_fileobj(self):
667 self._test_modes(self._testfunc_fileobj)
668
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300669class GzipDetectReadTest(GzipTest, DetectReadTest):
670 pass
671
672class Bz2DetectReadTest(Bz2Test, DetectReadTest):
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100673 def test_detect_stream_bz2(self):
674 # Originally, tarfile's stream detection looked for the string
675 # "BZh91" at the start of the file. This is incorrect because
676 # the '9' represents the blocksize (900kB). If the file was
677 # compressed using another blocksize autodetection fails.
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100678 with open(tarname, "rb") as fobj:
679 data = fobj.read()
680
681 # Compress with blocksize 100kB, the file starts with "BZh11".
682 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
683 fobj.write(data)
684
685 self._testfunc_file(tmpname, "r|*")
686
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300687class LzmaDetectReadTest(LzmaTest, DetectReadTest):
688 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000689
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300690
691class MemberReadTest(ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000692
693 def _test_member(self, tarinfo, chksum=None, **kwargs):
694 if chksum is not None:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300695 with self.tar.extractfile(tarinfo) as f:
696 self.assertEqual(md5sum(f.read()), chksum,
697 "wrong md5sum for %s" % tarinfo.name)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000698
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000699 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000700 kwargs["uid"] = 1000
701 kwargs["gid"] = 100
702 if "old-v7" not in tarinfo.name:
703 # V7 tar can't handle alphabetic owners.
704 kwargs["uname"] = "tarfile"
705 kwargs["gname"] = "tarfile"
706 for k, v in kwargs.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300707 self.assertEqual(getattr(tarinfo, k), v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000708 "wrong value in %s field of %s" % (k, tarinfo.name))
709
710 def test_find_regtype(self):
711 tarinfo = self.tar.getmember("ustar/regtype")
712 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
713
714 def test_find_conttype(self):
715 tarinfo = self.tar.getmember("ustar/conttype")
716 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
717
718 def test_find_dirtype(self):
719 tarinfo = self.tar.getmember("ustar/dirtype")
720 self._test_member(tarinfo, size=0)
721
722 def test_find_dirtype_with_size(self):
723 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
724 self._test_member(tarinfo, size=255)
725
726 def test_find_lnktype(self):
727 tarinfo = self.tar.getmember("ustar/lnktype")
728 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
729
730 def test_find_symtype(self):
731 tarinfo = self.tar.getmember("ustar/symtype")
732 self._test_member(tarinfo, size=0, linkname="regtype")
733
734 def test_find_blktype(self):
735 tarinfo = self.tar.getmember("ustar/blktype")
736 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
737
738 def test_find_chrtype(self):
739 tarinfo = self.tar.getmember("ustar/chrtype")
740 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
741
742 def test_find_fifotype(self):
743 tarinfo = self.tar.getmember("ustar/fifotype")
744 self._test_member(tarinfo, size=0)
745
746 def test_find_sparse(self):
747 tarinfo = self.tar.getmember("ustar/sparse")
748 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
749
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000750 def test_find_gnusparse(self):
751 tarinfo = self.tar.getmember("gnu/sparse")
752 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
753
754 def test_find_gnusparse_00(self):
755 tarinfo = self.tar.getmember("gnu/sparse-0.0")
756 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
757
758 def test_find_gnusparse_01(self):
759 tarinfo = self.tar.getmember("gnu/sparse-0.1")
760 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
761
762 def test_find_gnusparse_10(self):
763 tarinfo = self.tar.getmember("gnu/sparse-1.0")
764 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
765
Guido van Rossumd8faa362007-04-27 19:54:29 +0000766 def test_find_umlauts(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300767 tarinfo = self.tar.getmember("ustar/umlauts-"
768 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000769 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
770
771 def test_find_ustar_longname(self):
772 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000773 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000774
775 def test_find_regtype_oldv7(self):
776 tarinfo = self.tar.getmember("misc/regtype-old-v7")
777 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
778
779 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000780 self.tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300781 self.tar = tarfile.open(self.tarname, mode=self.mode,
782 encoding="iso8859-1")
783 tarinfo = self.tar.getmember("pax/umlauts-"
784 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000785 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
786
787
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300788class LongnameTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000789
790 def test_read_longname(self):
791 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000792 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000793 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000794 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795 except KeyError:
796 self.fail("longname not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300797 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
798 "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000799
800 def test_read_longlink(self):
801 longname = self.subdir + "/" + "123/" * 125 + "longname"
802 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
803 try:
804 tarinfo = self.tar.getmember(longlink)
805 except KeyError:
806 self.fail("longlink not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300807 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000808
809 def test_truncated_longname(self):
810 longname = self.subdir + "/" + "123/" * 125 + "longname"
811 tarinfo = self.tar.getmember(longname)
812 offset = tarinfo.offset
813 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000814 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300815 with self.assertRaises(tarfile.ReadError):
816 tarfile.open(name="foo.tar", fileobj=fobj)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000817
Guido van Rossume7ba4952007-06-06 23:52:48 +0000818 def test_header_offset(self):
819 # Test if the start offset of the TarInfo object includes
820 # the preceding extended header.
821 longname = self.subdir + "/" + "123/" * 125 + "longname"
822 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000823 with open(tarname, "rb") as fobj:
824 fobj.seek(offset)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300825 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
826 "iso8859-1", "strict")
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000827 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000828
Guido van Rossumd8faa362007-04-27 19:54:29 +0000829
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300830class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000831
832 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000833 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000834
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000835 # Since 3.2 tarfile is supposed to accurately restore sparse members and
836 # produce files with holes. This is what we actually want to test here.
837 # Unfortunately, not all platforms/filesystems support sparse files, and
838 # even on platforms that do it is non-trivial to make reliable assertions
839 # about holes in files. Therefore, we first do one basic test which works
840 # an all platforms, and after that a test that will work only on
841 # platforms/filesystems that prove to support sparse files.
842 def _test_sparse_file(self, name):
843 self.tar.extract(name, TEMPDIR)
844 filename = os.path.join(TEMPDIR, name)
845 with open(filename, "rb") as fobj:
846 data = fobj.read()
847 self.assertEqual(md5sum(data), md5_sparse,
848 "wrong md5sum for %s" % name)
849
850 if self._fs_supports_holes():
851 s = os.stat(filename)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300852 self.assertLess(s.st_blocks * 512, s.st_size)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000853
854 def test_sparse_file_old(self):
855 self._test_sparse_file("gnu/sparse")
856
857 def test_sparse_file_00(self):
858 self._test_sparse_file("gnu/sparse-0.0")
859
860 def test_sparse_file_01(self):
861 self._test_sparse_file("gnu/sparse-0.1")
862
863 def test_sparse_file_10(self):
864 self._test_sparse_file("gnu/sparse-1.0")
865
866 @staticmethod
867 def _fs_supports_holes():
868 # Return True if the platform knows the st_blocks stat attribute and
869 # uses st_blocks units of 512 bytes, and if the filesystem is able to
870 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200871 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000872 # Linux evidentially has 512 byte st_blocks units.
873 name = os.path.join(TEMPDIR, "sparse-test")
874 with open(name, "wb") as fobj:
875 fobj.seek(4096)
876 fobj.truncate()
877 s = os.stat(name)
878 os.remove(name)
879 return s.st_blocks == 0
880 else:
881 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000882
883
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300884class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000885
886 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000887 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888
Guido van Rossume7ba4952007-06-06 23:52:48 +0000889 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000890 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000891 try:
892 tarinfo = tar.getmember("pax/regtype1")
893 self.assertEqual(tarinfo.uname, "foo")
894 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300895 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
896 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000897
Antoine Pitrou95f55602010-09-23 18:36:46 +0000898 tarinfo = tar.getmember("pax/regtype2")
899 self.assertEqual(tarinfo.uname, "")
900 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300901 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
902 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000903
Antoine Pitrou95f55602010-09-23 18:36:46 +0000904 tarinfo = tar.getmember("pax/regtype3")
905 self.assertEqual(tarinfo.uname, "tarfile")
906 self.assertEqual(tarinfo.gname, "tarfile")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300907 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
908 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000909 finally:
910 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000911
912 def test_pax_number_fields(self):
913 # All following number fields are read from the pax header.
914 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000915 try:
916 tarinfo = tar.getmember("pax/regtype4")
917 self.assertEqual(tarinfo.size, 7011)
918 self.assertEqual(tarinfo.uid, 123)
919 self.assertEqual(tarinfo.gid, 123)
920 self.assertEqual(tarinfo.mtime, 1041808783.0)
921 self.assertEqual(type(tarinfo.mtime), float)
922 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
923 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
924 finally:
925 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000926
927
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300928class WriteTestBase(TarTest):
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000929 # Put all write tests in here that are supposed to be tested
930 # in all possible mode combinations.
931
932 def test_fileobj_no_close(self):
933 fobj = io.BytesIO()
934 tar = tarfile.open(fileobj=fobj, mode=self.mode)
935 tar.addfile(tarfile.TarInfo("foo"))
936 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300937 self.assertFalse(fobj.closed, "external fileobjs must never closed")
Serhiy Storchaka9fbec7a2014-01-18 15:53:05 +0200938 # Issue #20238: Incomplete gzip output with mode="w:gz"
939 data = fobj.getvalue()
940 del tar
941 support.gc_collect()
942 self.assertFalse(fobj.closed)
943 self.assertEqual(data, fobj.getvalue())
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000944
945
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300946class WriteTest(WriteTestBase, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000947
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300948 prefix = "w:"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000949
950 def test_100_char_name(self):
951 # The name field in a tar header stores strings of at most 100 chars.
952 # If a string is shorter than 100 chars it has to be padded with '\0',
953 # which implies that a string of exactly 100 chars is stored without
954 # a trailing '\0'.
955 name = "0123456789" * 10
956 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000957 try:
958 t = tarfile.TarInfo(name)
959 tar.addfile(t)
960 finally:
961 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000962
Guido van Rossumd8faa362007-04-27 19:54:29 +0000963 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000964 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300965 self.assertEqual(tar.getnames()[0], name,
Antoine Pitrou95f55602010-09-23 18:36:46 +0000966 "failed to store 100 char filename")
967 finally:
968 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000969
Guido van Rossumd8faa362007-04-27 19:54:29 +0000970 def test_tar_size(self):
971 # Test for bug #1013882.
972 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000973 try:
974 path = os.path.join(TEMPDIR, "file")
975 with open(path, "wb") as fobj:
976 fobj.write(b"aaa")
977 tar.add(path)
978 finally:
979 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300980 self.assertGreater(os.path.getsize(tmpname), 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000981 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000982
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983 # The test_*_size tests test for bug #1167128.
984 def test_file_size(self):
985 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000986 try:
987 path = os.path.join(TEMPDIR, "file")
988 with open(path, "wb"):
989 pass
990 tarinfo = tar.gettarinfo(path)
991 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000992
Antoine Pitrou95f55602010-09-23 18:36:46 +0000993 with open(path, "wb") as fobj:
994 fobj.write(b"aaa")
995 tarinfo = tar.gettarinfo(path)
996 self.assertEqual(tarinfo.size, 3)
997 finally:
998 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000999
1000 def test_directory_size(self):
1001 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001002 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001003 try:
1004 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001005 try:
1006 tarinfo = tar.gettarinfo(path)
1007 self.assertEqual(tarinfo.size, 0)
1008 finally:
1009 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001010 finally:
1011 os.rmdir(path)
1012
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001013 @unittest.skipUnless(hasattr(os, "link"),
1014 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001015 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001016 link = os.path.join(TEMPDIR, "link")
1017 target = os.path.join(TEMPDIR, "link_target")
1018 with open(target, "wb") as fobj:
1019 fobj.write(b"aaa")
1020 os.link(target, link)
1021 try:
1022 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001023 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001024 # Record the link target in the inodes list.
1025 tar.gettarinfo(target)
1026 tarinfo = tar.gettarinfo(link)
1027 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001029 tar.close()
1030 finally:
1031 os.remove(target)
1032 os.remove(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001033
Brian Curtin3b4499c2010-12-28 14:31:47 +00001034 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +00001035 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +00001036 path = os.path.join(TEMPDIR, "symlink")
1037 os.symlink("link_target", path)
1038 try:
1039 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001040 try:
1041 tarinfo = tar.gettarinfo(path)
1042 self.assertEqual(tarinfo.size, 0)
1043 finally:
1044 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +00001045 finally:
1046 os.remove(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001047
1048 def test_add_self(self):
1049 # Test for #1257255.
1050 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001051 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001052 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001053 self.assertEqual(tar.name, dstname,
1054 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001055 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001056 self.assertEqual(tar.getnames(), [],
1057 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001058
Antoine Pitrou95f55602010-09-23 18:36:46 +00001059 cwd = os.getcwd()
1060 os.chdir(TEMPDIR)
1061 tar.add(dstname)
1062 os.chdir(cwd)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001063 self.assertEqual(tar.getnames(), [],
1064 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001065 finally:
1066 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001067
Guido van Rossum486364b2007-06-30 05:01:58 +00001068 def test_exclude(self):
1069 tempdir = os.path.join(TEMPDIR, "exclude")
1070 os.mkdir(tempdir)
1071 try:
1072 for name in ("foo", "bar", "baz"):
1073 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001074 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +00001075
Benjamin Peterson886af962010-03-21 23:13:07 +00001076 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +00001077
1078 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001079 try:
1080 with support.check_warnings(("use the filter argument",
1081 DeprecationWarning)):
1082 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
1083 finally:
1084 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001085
1086 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001087 try:
1088 self.assertEqual(len(tar.getmembers()), 1)
1089 self.assertEqual(tar.getnames()[0], "empty_dir")
1090 finally:
1091 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001092 finally:
1093 shutil.rmtree(tempdir)
1094
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001095 def test_filter(self):
1096 tempdir = os.path.join(TEMPDIR, "filter")
1097 os.mkdir(tempdir)
1098 try:
1099 for name in ("foo", "bar", "baz"):
1100 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001101 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001102
1103 def filter(tarinfo):
1104 if os.path.basename(tarinfo.name) == "bar":
1105 return
1106 tarinfo.uid = 123
1107 tarinfo.uname = "foo"
1108 return tarinfo
1109
1110 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001111 try:
1112 tar.add(tempdir, arcname="empty_dir", filter=filter)
1113 finally:
1114 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001115
Raymond Hettingera63a3122011-01-26 20:34:14 +00001116 # Verify that filter is a keyword-only argument
1117 with self.assertRaises(TypeError):
1118 tar.add(tempdir, "empty_dir", True, None, filter)
1119
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001120 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001121 try:
1122 for tarinfo in tar:
1123 self.assertEqual(tarinfo.uid, 123)
1124 self.assertEqual(tarinfo.uname, "foo")
1125 self.assertEqual(len(tar.getmembers()), 3)
1126 finally:
1127 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001128 finally:
1129 shutil.rmtree(tempdir)
1130
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001131 # Guarantee that stored pathnames are not modified. Don't
1132 # remove ./ or ../ or double slashes. Still make absolute
1133 # pathnames relative.
1134 # For details see bug #6054.
1135 def _test_pathname(self, path, cmp_path=None, dir=False):
1136 # Create a tarfile with an empty member named path
1137 # and compare the stored name with the original.
1138 foo = os.path.join(TEMPDIR, "foo")
1139 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001140 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001141 else:
1142 os.mkdir(foo)
1143
1144 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001145 try:
1146 tar.add(foo, arcname=path)
1147 finally:
1148 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001149
1150 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001151 try:
1152 t = tar.next()
1153 finally:
1154 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001155
1156 if not dir:
1157 os.remove(foo)
1158 else:
1159 os.rmdir(foo)
1160
1161 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1162
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001163
1164 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001165 def test_extractall_symlinks(self):
1166 # Test if extractall works properly when tarfile contains symlinks
1167 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1168 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1169 os.mkdir(tempdir)
1170 try:
1171 source_file = os.path.join(tempdir,'source')
1172 target_file = os.path.join(tempdir,'symlink')
1173 with open(source_file,'w') as f:
1174 f.write('something\n')
1175 os.symlink(source_file, target_file)
1176 tar = tarfile.open(temparchive,'w')
1177 tar.add(source_file)
1178 tar.add(target_file)
1179 tar.close()
1180 # Let's extract it to the location which contains the symlink
1181 tar = tarfile.open(temparchive,'r')
1182 # this should not raise OSError: [Errno 17] File exists
1183 try:
1184 tar.extractall(path=tempdir)
1185 except OSError:
1186 self.fail("extractall failed with symlinked files")
1187 finally:
1188 tar.close()
1189 finally:
1190 os.unlink(temparchive)
1191 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001192
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001193 def test_pathnames(self):
1194 self._test_pathname("foo")
1195 self._test_pathname(os.path.join("foo", ".", "bar"))
1196 self._test_pathname(os.path.join("foo", "..", "bar"))
1197 self._test_pathname(os.path.join(".", "foo"))
1198 self._test_pathname(os.path.join(".", "foo", "."))
1199 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1200 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1201 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1202 self._test_pathname(os.path.join("..", "foo"))
1203 self._test_pathname(os.path.join("..", "foo", ".."))
1204 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1205 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1206
1207 self._test_pathname("foo" + os.sep + os.sep + "bar")
1208 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1209
1210 def test_abs_pathnames(self):
1211 if sys.platform == "win32":
1212 self._test_pathname("C:\\foo", "foo")
1213 else:
1214 self._test_pathname("/foo", "foo")
1215 self._test_pathname("///foo", "foo")
1216
1217 def test_cwd(self):
1218 # Test adding the current working directory.
1219 cwd = os.getcwd()
1220 os.chdir(TEMPDIR)
1221 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001222 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001223 try:
1224 tar.add(".")
1225 finally:
1226 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001227
1228 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001229 try:
1230 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001231 if t.name != ".":
1232 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001233 finally:
1234 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001235 finally:
1236 os.chdir(cwd)
1237
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001238 def test_open_nonwritable_fileobj(self):
1239 for exctype in OSError, EOFError, RuntimeError:
1240 class BadFile(io.BytesIO):
1241 first = True
1242 def write(self, data):
1243 if self.first:
1244 self.first = False
1245 raise exctype
1246
1247 f = BadFile()
1248 with self.assertRaises(exctype):
1249 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1250 format=tarfile.PAX_FORMAT,
1251 pax_headers={'non': 'empty'})
1252 self.assertFalse(f.closed)
1253
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001254class GzipWriteTest(GzipTest, WriteTest):
1255 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001256
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001257class Bz2WriteTest(Bz2Test, WriteTest):
1258 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001259
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001260class LzmaWriteTest(LzmaTest, WriteTest):
1261 pass
1262
1263
1264class StreamWriteTest(WriteTestBase, unittest.TestCase):
1265
1266 prefix = "w|"
1267 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001268
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269 def test_stream_padding(self):
1270 # Test for bug #1543303.
1271 tar = tarfile.open(tmpname, self.mode)
1272 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001273 if self.decompressor:
1274 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001275 with open(tmpname, "rb") as fobj:
1276 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001277 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001278 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001279 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001280 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001281 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001282 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1283 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001284
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001285 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1286 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001287 def test_file_mode(self):
1288 # Test for issue #8464: Create files with correct
1289 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001290 if os.path.exists(tmpname):
1291 os.remove(tmpname)
1292
1293 original_umask = os.umask(0o022)
1294 try:
1295 tar = tarfile.open(tmpname, self.mode)
1296 tar.close()
1297 mode = os.stat(tmpname).st_mode & 0o777
1298 self.assertEqual(mode, 0o644, "wrong file permissions")
1299 finally:
1300 os.umask(original_umask)
1301
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001302class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1303 pass
1304
1305class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1306 decompressor = bz2.BZ2Decompressor if bz2 else None
1307
1308class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1309 decompressor = lzma.LZMADecompressor if lzma else None
1310
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001311
Guido van Rossumd8faa362007-04-27 19:54:29 +00001312class GNUWriteTest(unittest.TestCase):
1313 # This testcase checks for correct creation of GNU Longname
1314 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001315
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001316 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001317 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001318 return blocks * 512
1319
1320 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001321 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001322 count = 512
1323
1324 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001325 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001326 count += 512
1327 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001328 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001329 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001330 count += 512
1331 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001332 return count
1333
1334 def _test(self, name, link=None):
1335 tarinfo = tarfile.TarInfo(name)
1336 if link:
1337 tarinfo.linkname = link
1338 tarinfo.type = tarfile.LNKTYPE
1339
Guido van Rossumd8faa362007-04-27 19:54:29 +00001340 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001341 try:
1342 tar.format = tarfile.GNU_FORMAT
1343 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001344
Antoine Pitrou95f55602010-09-23 18:36:46 +00001345 v1 = self._calc_size(name, link)
1346 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001347 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001348 finally:
1349 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001350
Guido van Rossumd8faa362007-04-27 19:54:29 +00001351 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001352 try:
1353 member = tar.next()
1354 self.assertIsNotNone(member,
1355 "unable to read longname member")
1356 self.assertEqual(tarinfo.name, member.name,
1357 "unable to read longname member")
1358 self.assertEqual(tarinfo.linkname, member.linkname,
1359 "unable to read longname member")
1360 finally:
1361 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001362
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001363 def test_longname_1023(self):
1364 self._test(("longnam/" * 127) + "longnam")
1365
1366 def test_longname_1024(self):
1367 self._test(("longnam/" * 127) + "longname")
1368
1369 def test_longname_1025(self):
1370 self._test(("longnam/" * 127) + "longname_")
1371
1372 def test_longlink_1023(self):
1373 self._test("name", ("longlnk/" * 127) + "longlnk")
1374
1375 def test_longlink_1024(self):
1376 self._test("name", ("longlnk/" * 127) + "longlink")
1377
1378 def test_longlink_1025(self):
1379 self._test("name", ("longlnk/" * 127) + "longlink_")
1380
1381 def test_longnamelink_1023(self):
1382 self._test(("longnam/" * 127) + "longnam",
1383 ("longlnk/" * 127) + "longlnk")
1384
1385 def test_longnamelink_1024(self):
1386 self._test(("longnam/" * 127) + "longname",
1387 ("longlnk/" * 127) + "longlink")
1388
1389 def test_longnamelink_1025(self):
1390 self._test(("longnam/" * 127) + "longname_",
1391 ("longlnk/" * 127) + "longlink_")
1392
Guido van Rossumd8faa362007-04-27 19:54:29 +00001393
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001394@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001395class HardlinkTest(unittest.TestCase):
1396 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001397
1398 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001399 self.foo = os.path.join(TEMPDIR, "foo")
1400 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001401
Antoine Pitrou95f55602010-09-23 18:36:46 +00001402 with open(self.foo, "wb") as fobj:
1403 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001404
Guido van Rossumd8faa362007-04-27 19:54:29 +00001405 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001406
Guido van Rossumd8faa362007-04-27 19:54:29 +00001407 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001408 self.tar.add(self.foo)
1409
Guido van Rossumd8faa362007-04-27 19:54:29 +00001410 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001411 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001412 support.unlink(self.foo)
1413 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001414
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001415 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001416 # The same name will be added as a REGTYPE every
1417 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001418 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001419 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001420 "add file as regular failed")
1421
1422 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001423 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001424 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001425 "add file as hardlink failed")
1426
1427 def test_dereference_hardlink(self):
1428 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001429 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001430 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001431 "dereferencing hardlink failed")
1432
Neal Norwitza4f651a2004-07-20 22:07:44 +00001433
Guido van Rossumd8faa362007-04-27 19:54:29 +00001434class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001435
Guido van Rossumd8faa362007-04-27 19:54:29 +00001436 def _test(self, name, link=None):
1437 # See GNUWriteTest.
1438 tarinfo = tarfile.TarInfo(name)
1439 if link:
1440 tarinfo.linkname = link
1441 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001442
Guido van Rossumd8faa362007-04-27 19:54:29 +00001443 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001444 try:
1445 tar.addfile(tarinfo)
1446 finally:
1447 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001448
Guido van Rossumd8faa362007-04-27 19:54:29 +00001449 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001450 try:
1451 if link:
1452 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001453 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001454 else:
1455 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001456 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001457 finally:
1458 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001459
Guido van Rossume7ba4952007-06-06 23:52:48 +00001460 def test_pax_global_header(self):
1461 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001462 "foo": "bar",
1463 "uid": "0",
1464 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001465 "test": "\xe4\xf6\xfc",
1466 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001467
Benjamin Peterson886af962010-03-21 23:13:07 +00001468 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001469 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001470 try:
1471 tar.addfile(tarfile.TarInfo("test"))
1472 finally:
1473 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001474
1475 # Test if the global header was written correctly.
1476 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001477 try:
1478 self.assertEqual(tar.pax_headers, pax_headers)
1479 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1480 # Test if all the fields are strings.
1481 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001482 self.assertIsNot(type(key), bytes)
1483 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001484 if key in tarfile.PAX_NUMBER_FIELDS:
1485 try:
1486 tarfile.PAX_NUMBER_FIELDS[key](val)
1487 except (TypeError, ValueError):
1488 self.fail("unable to convert pax header field")
1489 finally:
1490 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001491
1492 def test_pax_extended_header(self):
1493 # The fields from the pax header have priority over the
1494 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001495 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001496
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001497 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1498 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001499 try:
1500 t = tarfile.TarInfo()
1501 t.name = "\xe4\xf6\xfc" # non-ASCII
1502 t.uid = 8**8 # too large
1503 t.pax_headers = pax_headers
1504 tar.addfile(t)
1505 finally:
1506 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001507
1508 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001509 try:
1510 t = tar.getmembers()[0]
1511 self.assertEqual(t.pax_headers, pax_headers)
1512 self.assertEqual(t.name, "foo")
1513 self.assertEqual(t.uid, 123)
1514 finally:
1515 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001516
1517
1518class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001519
1520 format = tarfile.USTAR_FORMAT
1521
1522 def test_iso8859_1_filename(self):
1523 self._test_unicode_filename("iso8859-1")
1524
1525 def test_utf7_filename(self):
1526 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001527
1528 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001529 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001530
Guido van Rossumd8faa362007-04-27 19:54:29 +00001531 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001532 tar = tarfile.open(tmpname, "w", format=self.format,
1533 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001534 try:
1535 name = "\xe4\xf6\xfc"
1536 tar.addfile(tarfile.TarInfo(name))
1537 finally:
1538 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001539
1540 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001541 try:
1542 self.assertEqual(tar.getmembers()[0].name, name)
1543 finally:
1544 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001545
1546 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001547 tar = tarfile.open(tmpname, "w", format=self.format,
1548 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001549 try:
1550 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001551
Antoine Pitrou95f55602010-09-23 18:36:46 +00001552 tarinfo.name = "\xe4\xf6\xfc"
1553 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001554
Antoine Pitrou95f55602010-09-23 18:36:46 +00001555 tarinfo.name = "foo"
1556 tarinfo.uname = "\xe4\xf6\xfc"
1557 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1558 finally:
1559 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001560
1561 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001562 tar = tarfile.open(tarname, "r",
1563 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001564 try:
1565 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001566 self.assertIs(type(t.name), str)
1567 self.assertIs(type(t.linkname), str)
1568 self.assertIs(type(t.uname), str)
1569 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001570 finally:
1571 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001572
Guido van Rossume7ba4952007-06-06 23:52:48 +00001573 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001574 t = tarfile.TarInfo("foo")
1575 t.uname = "\xe4\xf6\xfc"
1576 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001577
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001578 tar = tarfile.open(tmpname, mode="w", format=self.format,
1579 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001580 try:
1581 tar.addfile(t)
1582 finally:
1583 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001584
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001585 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001586 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001587 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001588 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1589 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1590
1591 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001592 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001593 tar = tarfile.open(tmpname, encoding="ascii")
1594 t = tar.getmember("foo")
1595 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1596 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1597 finally:
1598 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001599
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001600
Guido van Rossume7ba4952007-06-06 23:52:48 +00001601class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001602
Guido van Rossume7ba4952007-06-06 23:52:48 +00001603 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001604
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001605 def test_bad_pax_header(self):
1606 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1607 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001608 for encoding, name in (
1609 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001610 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001611 with tarfile.open(tarname, encoding=encoding,
1612 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001613 try:
1614 t = tar.getmember(name)
1615 except KeyError:
1616 self.fail("unable to read bad GNU tar pax header")
1617
Guido van Rossumd8faa362007-04-27 19:54:29 +00001618
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001619class PAXUnicodeTest(UstarUnicodeTest):
1620
1621 format = tarfile.PAX_FORMAT
1622
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001623 # PAX_FORMAT ignores encoding in write mode.
1624 test_unicode_filename_error = None
1625
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001626 def test_binary_header(self):
1627 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001628 for encoding, name in (
1629 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001630 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001631 with tarfile.open(tarname, encoding=encoding,
1632 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001633 try:
1634 t = tar.getmember(name)
1635 except KeyError:
1636 self.fail("unable to read POSIX.1-2008 binary header")
1637
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001638
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001639class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001640 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001641
Guido van Rossumd8faa362007-04-27 19:54:29 +00001642 def setUp(self):
1643 self.tarname = tmpname
1644 if os.path.exists(self.tarname):
1645 os.remove(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001646
Guido van Rossumd8faa362007-04-27 19:54:29 +00001647 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001648 with tarfile.open(tarname, encoding="iso8859-1") as src:
1649 t = src.getmember("ustar/regtype")
1650 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001651 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001652 with tarfile.open(self.tarname, mode) as tar:
1653 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001654
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001655 def test_append_compressed(self):
1656 self._create_testtar("w:" + self.suffix)
1657 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1658
1659class AppendTest(AppendTestBase, unittest.TestCase):
1660 test_append_compressed = None
1661
1662 def _add_testfile(self, fileobj=None):
1663 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1664 tar.addfile(tarfile.TarInfo("bar"))
1665
Guido van Rossumd8faa362007-04-27 19:54:29 +00001666 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001667 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1668 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001669
1670 def test_non_existing(self):
1671 self._add_testfile()
1672 self._test()
1673
1674 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001675 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001676 self._add_testfile()
1677 self._test()
1678
1679 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001680 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001681 self._add_testfile(fobj)
1682 fobj.seek(0)
1683 self._test(fileobj=fobj)
1684
1685 def test_fileobj(self):
1686 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001687 with open(self.tarname, "rb") as fobj:
1688 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001689 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001690 self._add_testfile(fobj)
1691 fobj.seek(0)
1692 self._test(names=["foo", "bar"], fileobj=fobj)
1693
1694 def test_existing(self):
1695 self._create_testtar()
1696 self._add_testfile()
1697 self._test(names=["foo", "bar"])
1698
Lars Gustäbel9520a432009-11-22 18:48:49 +00001699 # Append mode is supposed to fail if the tarfile to append to
1700 # does not end with a zero block.
1701 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001702 with open(self.tarname, "wb") as fobj:
1703 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001704 self.assertRaises(tarfile.ReadError, self._add_testfile)
1705
1706 def test_null(self):
1707 self._test_error(b"")
1708
1709 def test_incomplete(self):
1710 self._test_error(b"\0" * 13)
1711
1712 def test_premature_eof(self):
1713 data = tarfile.TarInfo("foo").tobuf()
1714 self._test_error(data)
1715
1716 def test_trailing_garbage(self):
1717 data = tarfile.TarInfo("foo").tobuf()
1718 self._test_error(data + b"\0" * 13)
1719
1720 def test_invalid(self):
1721 self._test_error(b"a" * 512)
1722
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001723class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
1724 pass
1725
1726class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
1727 pass
1728
1729class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
1730 pass
1731
Guido van Rossumd8faa362007-04-27 19:54:29 +00001732
1733class LimitsTest(unittest.TestCase):
1734
1735 def test_ustar_limits(self):
1736 # 100 char name
1737 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001738 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001739
1740 # 101 char name that cannot be stored
1741 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001742 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001743
1744 # 256 char name with a slash at pos 156
1745 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001746 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001747
1748 # 256 char name that cannot be stored
1749 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001750 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001751
1752 # 512 char name
1753 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001754 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001755
1756 # 512 char linkname
1757 tarinfo = tarfile.TarInfo("longlink")
1758 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001759 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001760
1761 # uid > 8 digits
1762 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001763 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001764 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001765
1766 def test_gnu_limits(self):
1767 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001768 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001769
1770 tarinfo = tarfile.TarInfo("longlink")
1771 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001772 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001773
1774 # uid >= 256 ** 7
1775 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001776 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001777 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001778
1779 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001780 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001781 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001782
1783 tarinfo = tarfile.TarInfo("longlink")
1784 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001785 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001786
1787 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001788 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001789 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001790
1791
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001792class MiscTest(unittest.TestCase):
1793
1794 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001795 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
1796 b"foo\0\0\0\0\0")
1797 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
1798 b"foo")
1799 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
1800 "foo")
1801 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
1802 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001803
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001804 def test_read_number_fields(self):
1805 # Issue 13158: Test if GNU tar specific base-256 number fields
1806 # are decoded correctly.
1807 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1808 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001809 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
1810 0o10000000)
1811 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
1812 0xffffffff)
1813 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
1814 -1)
1815 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
1816 -100)
1817 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
1818 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001819
1820 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001821 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001822 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001823 self.assertEqual(tarfile.itn(0o10000000),
1824 b"\x80\x00\x00\x00\x00\x20\x00\x00")
1825 self.assertEqual(tarfile.itn(0xffffffff),
1826 b"\x80\x00\x00\x00\xff\xff\xff\xff")
1827 self.assertEqual(tarfile.itn(-1),
1828 b"\xff\xff\xff\xff\xff\xff\xff\xff")
1829 self.assertEqual(tarfile.itn(-100),
1830 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1831 self.assertEqual(tarfile.itn(-0x100000000000000),
1832 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001833
1834 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001835 with self.assertRaises(ValueError):
1836 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
1837 with self.assertRaises(ValueError):
1838 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
1839 with self.assertRaises(ValueError):
1840 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
1841 with self.assertRaises(ValueError):
1842 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001843
1844
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001845class CommandLineTest(unittest.TestCase):
1846
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001847 def tarfilecmd(self, *args, **kwargs):
1848 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
1849 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01001850 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001851
1852 def tarfilecmd_failure(self, *args):
1853 return script_helper.assert_python_failure('-m', 'tarfile', *args)
1854
1855 def make_simple_tarfile(self, tar_name):
1856 files = [support.findfile('tokenize_tests.txt'),
1857 support.findfile('tokenize_tests-no-coding-cookie-'
1858 'and-utf8-bom-sig-only.txt')]
1859 self.addCleanup(support.unlink, tar_name)
1860 with tarfile.open(tar_name, 'w') as tf:
1861 for tardata in files:
1862 tf.add(tardata, arcname=os.path.basename(tardata))
1863
1864 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001865 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001866 for opt in '-t', '--test':
1867 out = self.tarfilecmd(opt, tar_name)
1868 self.assertEqual(out, b'')
1869
1870 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001871 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001872 for opt in '-v', '--verbose':
1873 out = self.tarfilecmd(opt, '-t', tar_name)
1874 self.assertIn(b'is a tar archive.\n', out)
1875
1876 def test_test_command_invalid_file(self):
1877 zipname = support.findfile('zipdir.zip')
1878 rc, out, err = self.tarfilecmd_failure('-t', zipname)
1879 self.assertIn(b' is not a tar archive.', err)
1880 self.assertEqual(out, b'')
1881 self.assertEqual(rc, 1)
1882
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001883 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001884 with self.subTest(tar_name=tar_name):
1885 with open(tar_name, 'rb') as f:
1886 data = f.read()
1887 try:
1888 with open(tmpname, 'wb') as f:
1889 f.write(data[:511])
1890 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
1891 self.assertEqual(out, b'')
1892 self.assertEqual(rc, 1)
1893 finally:
1894 support.unlink(tmpname)
1895
1896 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001897 for tar_name in testtarnames:
1898 with support.captured_stdout() as t:
1899 with tarfile.open(tar_name, 'r') as tf:
1900 tf.list(verbose=False)
1901 expected = t.getvalue().encode('ascii', 'backslashreplace')
1902 for opt in '-l', '--list':
1903 out = self.tarfilecmd(opt, tar_name,
1904 PYTHONIOENCODING='ascii')
1905 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001906
1907 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001908 for tar_name in testtarnames:
1909 with support.captured_stdout() as t:
1910 with tarfile.open(tar_name, 'r') as tf:
1911 tf.list(verbose=True)
1912 expected = t.getvalue().encode('ascii', 'backslashreplace')
1913 for opt in '-v', '--verbose':
1914 out = self.tarfilecmd(opt, '-l', tar_name,
1915 PYTHONIOENCODING='ascii')
1916 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001917
1918 def test_list_command_invalid_file(self):
1919 zipname = support.findfile('zipdir.zip')
1920 rc, out, err = self.tarfilecmd_failure('-l', zipname)
1921 self.assertIn(b' is not a tar archive.', err)
1922 self.assertEqual(out, b'')
1923 self.assertEqual(rc, 1)
1924
1925 def test_create_command(self):
1926 files = [support.findfile('tokenize_tests.txt'),
1927 support.findfile('tokenize_tests-no-coding-cookie-'
1928 'and-utf8-bom-sig-only.txt')]
1929 for opt in '-c', '--create':
1930 try:
1931 out = self.tarfilecmd(opt, tmpname, *files)
1932 self.assertEqual(out, b'')
1933 with tarfile.open(tmpname) as tar:
1934 tar.getmembers()
1935 finally:
1936 support.unlink(tmpname)
1937
1938 def test_create_command_verbose(self):
1939 files = [support.findfile('tokenize_tests.txt'),
1940 support.findfile('tokenize_tests-no-coding-cookie-'
1941 'and-utf8-bom-sig-only.txt')]
1942 for opt in '-v', '--verbose':
1943 try:
1944 out = self.tarfilecmd(opt, '-c', tmpname, *files)
1945 self.assertIn(b' file created.', out)
1946 with tarfile.open(tmpname) as tar:
1947 tar.getmembers()
1948 finally:
1949 support.unlink(tmpname)
1950
1951 def test_create_command_dotless_filename(self):
1952 files = [support.findfile('tokenize_tests.txt')]
1953 try:
1954 out = self.tarfilecmd('-c', dotlessname, *files)
1955 self.assertEqual(out, b'')
1956 with tarfile.open(dotlessname) as tar:
1957 tar.getmembers()
1958 finally:
1959 support.unlink(dotlessname)
1960
1961 def test_create_command_dot_started_filename(self):
1962 tar_name = os.path.join(TEMPDIR, ".testtar")
1963 files = [support.findfile('tokenize_tests.txt')]
1964 try:
1965 out = self.tarfilecmd('-c', tar_name, *files)
1966 self.assertEqual(out, b'')
1967 with tarfile.open(tar_name) as tar:
1968 tar.getmembers()
1969 finally:
1970 support.unlink(tar_name)
1971
1972 def test_extract_command(self):
1973 self.make_simple_tarfile(tmpname)
1974 for opt in '-e', '--extract':
1975 try:
1976 with support.temp_cwd(tarextdir):
1977 out = self.tarfilecmd(opt, tmpname)
1978 self.assertEqual(out, b'')
1979 finally:
1980 support.rmtree(tarextdir)
1981
1982 def test_extract_command_verbose(self):
1983 self.make_simple_tarfile(tmpname)
1984 for opt in '-v', '--verbose':
1985 try:
1986 with support.temp_cwd(tarextdir):
1987 out = self.tarfilecmd(opt, '-e', tmpname)
1988 self.assertIn(b' file is extracted.', out)
1989 finally:
1990 support.rmtree(tarextdir)
1991
1992 def test_extract_command_different_directory(self):
1993 self.make_simple_tarfile(tmpname)
1994 try:
1995 with support.temp_cwd(tarextdir):
1996 out = self.tarfilecmd('-e', tmpname, 'spamdir')
1997 self.assertEqual(out, b'')
1998 finally:
1999 support.rmtree(tarextdir)
2000
2001 def test_extract_command_invalid_file(self):
2002 zipname = support.findfile('zipdir.zip')
2003 with support.temp_cwd(tarextdir):
2004 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2005 self.assertIn(b' is not a tar archive.', err)
2006 self.assertEqual(out, b'')
2007 self.assertEqual(rc, 1)
2008
2009
Lars Gustäbel01385812010-03-03 12:08:54 +00002010class ContextManagerTest(unittest.TestCase):
2011
2012 def test_basic(self):
2013 with tarfile.open(tarname) as tar:
2014 self.assertFalse(tar.closed, "closed inside runtime context")
2015 self.assertTrue(tar.closed, "context manager failed")
2016
2017 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002018 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002019 # if the TarFile object is already closed.
2020 tar = tarfile.open(tarname)
2021 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002022 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002023 with tar:
2024 pass
2025
2026 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002027 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002028 with self.assertRaises(Exception) as exc:
2029 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002030 raise OSError
2031 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002032 "wrong exception raised in context manager")
2033 self.assertTrue(tar.closed, "context manager failed")
2034
2035 def test_no_eof(self):
2036 # __exit__() must not write end-of-archive blocks if an
2037 # exception was raised.
2038 try:
2039 with tarfile.open(tmpname, "w") as tar:
2040 raise Exception
2041 except:
2042 pass
2043 self.assertEqual(os.path.getsize(tmpname), 0,
2044 "context manager wrote an end-of-archive block")
2045 self.assertTrue(tar.closed, "context manager failed")
2046
2047 def test_eof(self):
2048 # __exit__() must write end-of-archive blocks, i.e. call
2049 # TarFile.close() if there was no error.
2050 with tarfile.open(tmpname, "w"):
2051 pass
2052 self.assertNotEqual(os.path.getsize(tmpname), 0,
2053 "context manager wrote no end-of-archive block")
2054
2055 def test_fileobj(self):
2056 # Test that __exit__() did not close the external file
2057 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002058 with open(tmpname, "wb") as fobj:
2059 try:
2060 with tarfile.open(fileobj=fobj, mode="w") as tar:
2061 raise Exception
2062 except:
2063 pass
2064 self.assertFalse(fobj.closed, "external file object was closed")
2065 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002066
2067
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002068@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2069class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002070
2071 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002072 # symbolic or hard links tarfile tries to extract these types of members
2073 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002074 def _test_link_extraction(self, name):
2075 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002076 with open(os.path.join(TEMPDIR, name), "rb") as f:
2077 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002078 self.assertEqual(md5sum(data), md5_regtype)
2079
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002080 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002081 @unittest.skipIf(hasattr(os.path, "islink"),
2082 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002083 def test_hardlink_extraction1(self):
2084 self._test_link_extraction("ustar/lnktype")
2085
Brian Curtind40e6f72010-07-08 21:39:08 +00002086 @unittest.skipIf(hasattr(os.path, "islink"),
2087 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002088 def test_hardlink_extraction2(self):
2089 self._test_link_extraction("./ustar/linktest2/lnktype")
2090
Brian Curtin74e45612010-07-09 15:58:59 +00002091 @unittest.skipIf(hasattr(os, "symlink"),
2092 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002093 def test_symlink_extraction1(self):
2094 self._test_link_extraction("ustar/symtype")
2095
Brian Curtin74e45612010-07-09 15:58:59 +00002096 @unittest.skipIf(hasattr(os, "symlink"),
2097 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002098 def test_symlink_extraction2(self):
2099 self._test_link_extraction("./ustar/linktest2/symtype")
2100
2101
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002102class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002103 # Issue5068: The _BZ2Proxy.read() method loops forever
2104 # on an empty or partial bzipped file.
2105
2106 def _test_partial_input(self, mode):
2107 class MyBytesIO(io.BytesIO):
2108 hit_eof = False
2109 def read(self, n):
2110 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002111 raise AssertionError("infinite loop detected in "
2112 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002113 self.hit_eof = self.tell() == len(self.getvalue())
2114 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002115 def seek(self, *args):
2116 self.hit_eof = False
2117 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002118
2119 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2120 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002121 try:
2122 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2123 except tarfile.ReadError:
2124 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002125
2126 def test_partial_input(self):
2127 self._test_partial_input("r")
2128
2129 def test_partial_input_bz2(self):
2130 self._test_partial_input("r:bz2")
2131
2132
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002133def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002134 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002135 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002136
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002137 global testtarnames
2138 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002139 with open(tarname, "rb") as fobj:
2140 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002141
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002142 # Create compressed tarfiles.
2143 for c in GzipTest, Bz2Test, LzmaTest:
2144 if c.open:
2145 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002146 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002147 with c.open(c.tarname, "wb") as tar:
2148 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002149
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002150def tearDownModule():
2151 if os.path.exists(TEMPDIR):
2152 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002153
Neal Norwitz996acf12003-02-17 14:51:41 +00002154if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002155 unittest.main()