blob: 82aa840d869ee74d1b16bac0f644b38fb2a052d2 [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
Serhiy Storchaka162c4772014-02-19 18:44:12 +0200243 def conv(b):
244 s = b.decode(self.tar.encoding, 'surrogateescape')
245 return s.encode('ascii', 'backslashreplace')
246 self.assertIn(conv(b'ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
247 self.assertIn(conv(b'misc/regtype-hpux-signed-chksum-'
248 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
249 self.assertIn(conv(b'misc/regtype-old-v7-signed-chksum-'
250 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
251 self.assertIn(conv(b'pax/bad-pax-\xe4\xf6\xfc'), out)
252 self.assertIn(conv(b'pax/hdrcharset-\xe4\xf6\xfc'), out)
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200253 # Make sure it prints files separated by one newline without any
254 # 'ls -l'-like accessories if verbose flag is not being used
255 # ...
256 # ustar/conttype
257 # ustar/regtype
258 # ...
259 self.assertRegex(out, br'ustar/conttype ?\r?\n'
260 br'ustar/regtype ?\r?\n')
261 # Make sure it does not print the source of link without verbose flag
262 self.assertNotIn(b'link to', out)
263 self.assertNotIn(b'->', out)
264
265 def test_list_verbose(self):
266 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
267 with support.swap_attr(sys, 'stdout', tio):
268 self.tar.list(verbose=True)
269 out = tio.detach().getvalue()
270 # Make sure it prints files separated by one newline with 'ls -l'-like
271 # accessories if verbose flag is being used
272 # ...
273 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
274 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
275 # ...
Serhiy Storchaka255493c2014-02-05 20:54:43 +0200276 self.assertRegex(out, (br'\?rw-r--r-- tarfile/tarfile\s+7011 '
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200277 br'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
278 br'ustar/\w+type ?\r?\n') * 2)
279 # Make sure it prints the source of link with verbose flag
280 self.assertIn(b'ustar/symtype -> regtype', out)
281 self.assertIn(b'./ustar/linktest2/symtype -> ../linktest1/regtype', out)
282 self.assertIn(b'./ustar/linktest2/lnktype link to '
283 b'./ustar/linktest1/regtype', out)
284 self.assertIn(b'gnu' + (b'/123' * 125) + b'/longlink link to gnu' +
285 (b'/123' * 125) + b'/longname', out)
286 self.assertIn(b'pax' + (b'/123' * 125) + b'/longlink link to pax' +
287 (b'/123' * 125) + b'/longname', out)
288
289
290class GzipListTest(GzipTest, ListTest):
291 pass
292
293
294class Bz2ListTest(Bz2Test, ListTest):
295 pass
296
297
298class LzmaListTest(LzmaTest, ListTest):
299 pass
300
301
Lars Gustäbel9520a432009-11-22 18:48:49 +0000302class CommonReadTest(ReadTest):
303
304 def test_empty_tarfile(self):
305 # Test for issue6123: Allow opening empty archives.
306 # This test checks if tarfile.open() is able to open an empty tar
307 # archive successfully. Note that an empty tar archive is not the
308 # same as an empty file!
Antoine Pitrou95f55602010-09-23 18:36:46 +0000309 with tarfile.open(tmpname, self.mode.replace("r", "w")):
310 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000311 try:
312 tar = tarfile.open(tmpname, self.mode)
313 tar.getnames()
314 except tarfile.ReadError:
315 self.fail("tarfile.open() failed on empty archive")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000316 else:
317 self.assertListEqual(tar.getmembers(), [])
318 finally:
319 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000320
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200321 def test_non_existent_tarfile(self):
322 # Test for issue11513: prevent non-existent gzipped tarfiles raising
323 # multiple exceptions.
324 with self.assertRaisesRegex(FileNotFoundError, "xxx"):
325 tarfile.open("xxx", self.mode)
326
Lars Gustäbel9520a432009-11-22 18:48:49 +0000327 def test_null_tarfile(self):
328 # Test for issue6123: Allow opening empty archives.
329 # This test guarantees that tarfile.open() does not treat an empty
330 # file as an empty tar archive.
Antoine Pitrou95f55602010-09-23 18:36:46 +0000331 with open(tmpname, "wb"):
332 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000333 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
334 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
335
336 def test_ignore_zeros(self):
337 # Test TarFile's ignore_zeros option.
Lars Gustäbel9520a432009-11-22 18:48:49 +0000338 for char in (b'\0', b'a'):
339 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
340 # are ignored correctly.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300341 with self.open(tmpname, "w") as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000342 fobj.write(char * 1024)
343 fobj.write(tarfile.TarInfo("foo").tobuf())
Lars Gustäbel9520a432009-11-22 18:48:49 +0000344
345 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000346 try:
347 self.assertListEqual(tar.getnames(), ["foo"],
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300348 "ignore_zeros=True should have skipped the %r-blocks" %
349 char)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000350 finally:
351 tar.close()
Lars Gustäbel9520a432009-11-22 18:48:49 +0000352
353
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300354class MiscReadTestBase(CommonReadTest):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300355 def requires_name_attribute(self):
356 pass
357
Thomas Woutersed03b412007-08-28 21:37:11 +0000358 def test_no_name_argument(self):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300359 self.requires_name_attribute()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000360 with open(self.tarname, "rb") as fobj:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300361 self.assertIsInstance(fobj.name, str)
362 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
363 self.assertIsInstance(tar.name, str)
364 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000365
Thomas Woutersed03b412007-08-28 21:37:11 +0000366 def test_no_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 self.assertRaises(AttributeError, getattr, fobj, "name")
371 tar = tarfile.open(fileobj=fobj, mode=self.mode)
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300372 self.assertIsNone(tar.name)
Thomas Woutersed03b412007-08-28 21:37:11 +0000373
374 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000375 with open(self.tarname, "rb") as fobj:
376 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000377 fobj = io.BytesIO(data)
378 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000379 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300380 self.assertIsNone(tar.name)
381
382 def test_int_name_attribute(self):
383 # Issue 21044: tarfile.open() should handle fileobj with an integer
384 # 'name' attribute.
385 fd = os.open(self.tarname, os.O_RDONLY)
386 with open(fd, 'rb') as fobj:
387 self.assertIsInstance(fobj.name, int)
388 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
389 self.assertIsNone(tar.name)
390
391 def test_bytes_name_attribute(self):
392 self.requires_name_attribute()
393 tarname = os.fsencode(self.tarname)
394 with open(tarname, 'rb') as fobj:
395 self.assertIsInstance(fobj.name, bytes)
396 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
397 self.assertIsInstance(tar.name, bytes)
398 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Thomas Woutersed03b412007-08-28 21:37:11 +0000399
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +0200400 def test_illegal_mode_arg(self):
401 with open(tmpname, 'wb'):
402 pass
403 with self.assertRaisesRegex(ValueError, 'mode must be '):
404 tar = self.taropen(tmpname, 'q')
405 with self.assertRaisesRegex(ValueError, 'mode must be '):
406 tar = self.taropen(tmpname, 'rw')
407 with self.assertRaisesRegex(ValueError, 'mode must be '):
408 tar = self.taropen(tmpname, '')
409
Christian Heimesd8654cf2007-12-02 15:22:16 +0000410 def test_fileobj_with_offset(self):
411 # Skip the first member and store values from the second member
412 # of the testtar.
413 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000414 try:
415 tar.next()
416 t = tar.next()
417 name = t.name
418 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200419 with tar.extractfile(t) as f:
420 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000421 finally:
422 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000423
424 # Open the testtar and seek to the offset of the second member.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300425 with self.open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000426 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000427
Antoine Pitrou95f55602010-09-23 18:36:46 +0000428 # Test if the tarfile starts with the second member.
429 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
430 t = tar.next()
431 self.assertEqual(t.name, name)
432 # Read to the end of fileobj and test if seeking back to the
433 # beginning works.
434 tar.getmembers()
435 self.assertEqual(tar.extractfile(t).read(), data,
436 "seek back did not work")
437 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000438
Guido van Rossumd8faa362007-04-27 19:54:29 +0000439 def test_fail_comp(self):
440 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000441 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000442 with open(tarname, "rb") as fobj:
443 self.assertRaises(tarfile.ReadError, tarfile.open,
444 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000445
446 def test_v7_dirtype(self):
447 # Test old style dirtype member (bug #1336623):
448 # Old V7 tars create directory members using an AREGTYPE
449 # header with a "/" appended to the filename field.
450 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300451 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000452 "v7 dirtype failed")
453
Christian Heimes126d29a2008-02-11 22:57:17 +0000454 def test_xstar_type(self):
455 # The xstar format stores extra atime and ctime fields inside the
456 # space reserved for the prefix field. The prefix field must be
457 # ignored in this case, otherwise it will mess up the name.
458 try:
459 self.tar.getmember("misc/regtype-xstar")
460 except KeyError:
461 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
462
Guido van Rossumd8faa362007-04-27 19:54:29 +0000463 def test_check_members(self):
464 for tarinfo in self.tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300465 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000466 "wrong mtime for %s" % tarinfo.name)
467 if not tarinfo.name.startswith("ustar/"):
468 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300469 self.assertEqual(tarinfo.uname, "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000470 "wrong uname for %s" % tarinfo.name)
471
472 def test_find_members(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300473 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000474 "could not find all members")
475
Brian Curtin74e45612010-07-09 15:58:59 +0000476 @unittest.skipUnless(hasattr(os, "link"),
477 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000478 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000479 def test_extract_hardlink(self):
480 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200481 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000482 tar.extract("ustar/regtype", TEMPDIR)
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200483 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000484
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200485 tar.extract("ustar/lnktype", TEMPDIR)
486 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000487 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
488 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000489 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000490
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200491 tar.extract("ustar/symtype", TEMPDIR)
492 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000493 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
494 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000495 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000496
Christian Heimesfaf2f632008-01-06 16:59:19 +0000497 def test_extractall(self):
498 # Test if extractall() correctly restores directory permissions
499 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000500 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000501 DIR = os.path.join(TEMPDIR, "extractall")
502 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000503 try:
504 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000505 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000506 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000507 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000508 if sys.platform != "win32":
509 # Win32 has no support for fine grained permissions.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300510 self.assertEqual(tarinfo.mode & 0o777,
511 os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000512 def format_mtime(mtime):
513 if isinstance(mtime, float):
514 return "{} ({})".format(mtime, mtime.hex())
515 else:
516 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000517 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000518 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
519 format_mtime(tarinfo.mtime),
520 format_mtime(file_mtime),
521 path)
522 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000523 finally:
524 tar.close()
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000525 shutil.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000526
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000527 def test_extract_directory(self):
528 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000529 DIR = os.path.join(TEMPDIR, "extractdir")
530 os.mkdir(DIR)
531 try:
532 with tarfile.open(tarname, encoding="iso8859-1") as tar:
533 tarinfo = tar.getmember(dirtype)
534 tar.extract(tarinfo, path=DIR)
535 extracted = os.path.join(DIR, dirtype)
536 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
537 if sys.platform != "win32":
538 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
539 finally:
540 shutil.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000541
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000542 def test_init_close_fobj(self):
543 # Issue #7341: Close the internal file object in the TarFile
544 # constructor in case of an error. For the test we rely on
545 # the fact that opening an empty file raises a ReadError.
546 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000547 with open(empty, "wb") as fobj:
548 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000549
550 try:
551 tar = object.__new__(tarfile.TarFile)
552 try:
553 tar.__init__(empty)
554 except tarfile.ReadError:
555 self.assertTrue(tar.fileobj.closed)
556 else:
557 self.fail("ReadError not raised")
558 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000559 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000560
Serhiy Storchaka263fab92013-05-09 14:22:26 +0300561 def test_parallel_iteration(self):
562 # Issue #16601: Restarting iteration over tarfile continued
563 # from where it left off.
564 with tarfile.open(self.tarname) as tar:
565 for m1, m2 in zip(tar, tar):
566 self.assertEqual(m1.offset, m2.offset)
567 self.assertEqual(m1.get_info(), m2.get_info())
568
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300569class MiscReadTest(MiscReadTestBase, unittest.TestCase):
570 test_fail_comp = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300572class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200573 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000574
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300575class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300576 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300577 self.skipTest("BZ2File have no name attribute")
578
579class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +0300580 def requires_name_attribute(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300581 self.skipTest("LZMAFile have no name attribute")
582
583
584class StreamReadTest(CommonReadTest, unittest.TestCase):
585
586 prefix="r|"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000587
Lars Gustäbeldd071042011-02-23 11:42:22 +0000588 def test_read_through(self):
589 # Issue #11224: A poorly designed _FileInFile.read() method
590 # caused seeking errors with stream tar files.
591 for tarinfo in self.tar:
592 if not tarinfo.isreg():
593 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200594 with self.tar.extractfile(tarinfo) as fobj:
595 while True:
596 try:
597 buf = fobj.read(512)
598 except tarfile.StreamError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300599 self.fail("simple read-through using "
600 "TarFile.extractfile() failed")
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200601 if not buf:
602 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000603
Guido van Rossumd8faa362007-04-27 19:54:29 +0000604 def test_fileobj_regular_file(self):
605 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200606 with self.tar.extractfile(tarinfo) as fobj:
607 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300608 self.assertEqual(len(data), tarinfo.size,
609 "regular file extraction failed")
610 self.assertEqual(md5sum(data), md5_regtype,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000611 "regular file extraction failed")
612
613 def test_provoke_stream_error(self):
614 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200615 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
616 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000618 def test_compare_members(self):
619 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000620 try:
621 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000622
Antoine Pitrou95f55602010-09-23 18:36:46 +0000623 while True:
624 t1 = tar1.next()
625 t2 = tar2.next()
626 if t1 is None:
627 break
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300628 self.assertIsNotNone(t2, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000629
Antoine Pitrou95f55602010-09-23 18:36:46 +0000630 if t2.islnk() or t2.issym():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300631 with self.assertRaises(tarfile.StreamError):
632 tar2.extractfile(t2)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000633 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000634
Antoine Pitrou95f55602010-09-23 18:36:46 +0000635 v1 = tar1.extractfile(t1)
636 v2 = tar2.extractfile(t2)
637 if v1 is None:
638 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300639 self.assertIsNotNone(v2, "stream.extractfile() failed")
640 self.assertEqual(v1.read(), v2.read(),
641 "stream extraction failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000642 finally:
643 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000644
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300645class GzipStreamReadTest(GzipTest, StreamReadTest):
646 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000647
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300648class Bz2StreamReadTest(Bz2Test, StreamReadTest):
649 pass
Thomas Wouterscf297e42007-02-23 15:07:44 +0000650
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300651class LzmaStreamReadTest(LzmaTest, StreamReadTest):
652 pass
653
654
655class DetectReadTest(TarTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000656 def _testfunc_file(self, name, mode):
657 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000658 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000659 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000660 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000661 else:
662 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000663
Guido van Rossumd8faa362007-04-27 19:54:29 +0000664 def _testfunc_fileobj(self, name, mode):
665 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000666 with open(name, "rb") as f:
667 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000668 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000669 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000670 else:
671 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000672
673 def _test_modes(self, testfunc):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300674 if self.suffix:
675 with self.assertRaises(tarfile.ReadError):
676 tarfile.open(tarname, mode="r:" + self.suffix)
677 with self.assertRaises(tarfile.ReadError):
678 tarfile.open(tarname, mode="r|" + self.suffix)
679 with self.assertRaises(tarfile.ReadError):
680 tarfile.open(self.tarname, mode="r:")
681 with self.assertRaises(tarfile.ReadError):
682 tarfile.open(self.tarname, mode="r|")
683 testfunc(self.tarname, "r")
684 testfunc(self.tarname, "r:" + self.suffix)
685 testfunc(self.tarname, "r:*")
686 testfunc(self.tarname, "r|" + self.suffix)
687 testfunc(self.tarname, "r|*")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100688
Guido van Rossumd8faa362007-04-27 19:54:29 +0000689 def test_detect_file(self):
690 self._test_modes(self._testfunc_file)
691
692 def test_detect_fileobj(self):
693 self._test_modes(self._testfunc_fileobj)
694
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300695class GzipDetectReadTest(GzipTest, DetectReadTest):
696 pass
697
698class Bz2DetectReadTest(Bz2Test, DetectReadTest):
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100699 def test_detect_stream_bz2(self):
700 # Originally, tarfile's stream detection looked for the string
701 # "BZh91" at the start of the file. This is incorrect because
702 # the '9' represents the blocksize (900kB). If the file was
703 # compressed using another blocksize autodetection fails.
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100704 with open(tarname, "rb") as fobj:
705 data = fobj.read()
706
707 # Compress with blocksize 100kB, the file starts with "BZh11".
708 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
709 fobj.write(data)
710
711 self._testfunc_file(tmpname, "r|*")
712
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300713class LzmaDetectReadTest(LzmaTest, DetectReadTest):
714 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000715
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300716
717class MemberReadTest(ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000718
719 def _test_member(self, tarinfo, chksum=None, **kwargs):
720 if chksum is not None:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300721 with self.tar.extractfile(tarinfo) as f:
722 self.assertEqual(md5sum(f.read()), chksum,
723 "wrong md5sum for %s" % tarinfo.name)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000724
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000725 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000726 kwargs["uid"] = 1000
727 kwargs["gid"] = 100
728 if "old-v7" not in tarinfo.name:
729 # V7 tar can't handle alphabetic owners.
730 kwargs["uname"] = "tarfile"
731 kwargs["gname"] = "tarfile"
732 for k, v in kwargs.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300733 self.assertEqual(getattr(tarinfo, k), v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000734 "wrong value in %s field of %s" % (k, tarinfo.name))
735
736 def test_find_regtype(self):
737 tarinfo = self.tar.getmember("ustar/regtype")
738 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
739
740 def test_find_conttype(self):
741 tarinfo = self.tar.getmember("ustar/conttype")
742 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
743
744 def test_find_dirtype(self):
745 tarinfo = self.tar.getmember("ustar/dirtype")
746 self._test_member(tarinfo, size=0)
747
748 def test_find_dirtype_with_size(self):
749 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
750 self._test_member(tarinfo, size=255)
751
752 def test_find_lnktype(self):
753 tarinfo = self.tar.getmember("ustar/lnktype")
754 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
755
756 def test_find_symtype(self):
757 tarinfo = self.tar.getmember("ustar/symtype")
758 self._test_member(tarinfo, size=0, linkname="regtype")
759
760 def test_find_blktype(self):
761 tarinfo = self.tar.getmember("ustar/blktype")
762 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
763
764 def test_find_chrtype(self):
765 tarinfo = self.tar.getmember("ustar/chrtype")
766 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
767
768 def test_find_fifotype(self):
769 tarinfo = self.tar.getmember("ustar/fifotype")
770 self._test_member(tarinfo, size=0)
771
772 def test_find_sparse(self):
773 tarinfo = self.tar.getmember("ustar/sparse")
774 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
775
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000776 def test_find_gnusparse(self):
777 tarinfo = self.tar.getmember("gnu/sparse")
778 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
779
780 def test_find_gnusparse_00(self):
781 tarinfo = self.tar.getmember("gnu/sparse-0.0")
782 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
783
784 def test_find_gnusparse_01(self):
785 tarinfo = self.tar.getmember("gnu/sparse-0.1")
786 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
787
788 def test_find_gnusparse_10(self):
789 tarinfo = self.tar.getmember("gnu/sparse-1.0")
790 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
791
Guido van Rossumd8faa362007-04-27 19:54:29 +0000792 def test_find_umlauts(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300793 tarinfo = self.tar.getmember("ustar/umlauts-"
794 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
796
797 def test_find_ustar_longname(self):
798 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000799 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000800
801 def test_find_regtype_oldv7(self):
802 tarinfo = self.tar.getmember("misc/regtype-old-v7")
803 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
804
805 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000806 self.tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300807 self.tar = tarfile.open(self.tarname, mode=self.mode,
808 encoding="iso8859-1")
809 tarinfo = self.tar.getmember("pax/umlauts-"
810 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000811 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
812
813
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300814class LongnameTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000815
816 def test_read_longname(self):
817 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000818 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000819 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000820 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000821 except KeyError:
822 self.fail("longname not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300823 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
824 "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000825
826 def test_read_longlink(self):
827 longname = self.subdir + "/" + "123/" * 125 + "longname"
828 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
829 try:
830 tarinfo = self.tar.getmember(longlink)
831 except KeyError:
832 self.fail("longlink not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300833 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000834
835 def test_truncated_longname(self):
836 longname = self.subdir + "/" + "123/" * 125 + "longname"
837 tarinfo = self.tar.getmember(longname)
838 offset = tarinfo.offset
839 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000840 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300841 with self.assertRaises(tarfile.ReadError):
842 tarfile.open(name="foo.tar", fileobj=fobj)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000843
Guido van Rossume7ba4952007-06-06 23:52:48 +0000844 def test_header_offset(self):
845 # Test if the start offset of the TarInfo object includes
846 # the preceding extended header.
847 longname = self.subdir + "/" + "123/" * 125 + "longname"
848 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000849 with open(tarname, "rb") as fobj:
850 fobj.seek(offset)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300851 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
852 "iso8859-1", "strict")
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000853 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000854
Guido van Rossumd8faa362007-04-27 19:54:29 +0000855
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300856class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000857
858 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000859 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000860
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000861 # Since 3.2 tarfile is supposed to accurately restore sparse members and
862 # produce files with holes. This is what we actually want to test here.
863 # Unfortunately, not all platforms/filesystems support sparse files, and
864 # even on platforms that do it is non-trivial to make reliable assertions
865 # about holes in files. Therefore, we first do one basic test which works
866 # an all platforms, and after that a test that will work only on
867 # platforms/filesystems that prove to support sparse files.
868 def _test_sparse_file(self, name):
869 self.tar.extract(name, TEMPDIR)
870 filename = os.path.join(TEMPDIR, name)
871 with open(filename, "rb") as fobj:
872 data = fobj.read()
873 self.assertEqual(md5sum(data), md5_sparse,
874 "wrong md5sum for %s" % name)
875
876 if self._fs_supports_holes():
877 s = os.stat(filename)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300878 self.assertLess(s.st_blocks * 512, s.st_size)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000879
880 def test_sparse_file_old(self):
881 self._test_sparse_file("gnu/sparse")
882
883 def test_sparse_file_00(self):
884 self._test_sparse_file("gnu/sparse-0.0")
885
886 def test_sparse_file_01(self):
887 self._test_sparse_file("gnu/sparse-0.1")
888
889 def test_sparse_file_10(self):
890 self._test_sparse_file("gnu/sparse-1.0")
891
892 @staticmethod
893 def _fs_supports_holes():
894 # Return True if the platform knows the st_blocks stat attribute and
895 # uses st_blocks units of 512 bytes, and if the filesystem is able to
896 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200897 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000898 # Linux evidentially has 512 byte st_blocks units.
899 name = os.path.join(TEMPDIR, "sparse-test")
900 with open(name, "wb") as fobj:
901 fobj.seek(4096)
902 fobj.truncate()
903 s = os.stat(name)
904 os.remove(name)
905 return s.st_blocks == 0
906 else:
907 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000908
909
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300910class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000911
912 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000913 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000914
Guido van Rossume7ba4952007-06-06 23:52:48 +0000915 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000916 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000917 try:
918 tarinfo = tar.getmember("pax/regtype1")
919 self.assertEqual(tarinfo.uname, "foo")
920 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300921 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
922 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000923
Antoine Pitrou95f55602010-09-23 18:36:46 +0000924 tarinfo = tar.getmember("pax/regtype2")
925 self.assertEqual(tarinfo.uname, "")
926 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300927 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
928 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000929
Antoine Pitrou95f55602010-09-23 18:36:46 +0000930 tarinfo = tar.getmember("pax/regtype3")
931 self.assertEqual(tarinfo.uname, "tarfile")
932 self.assertEqual(tarinfo.gname, "tarfile")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300933 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
934 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000935 finally:
936 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000937
938 def test_pax_number_fields(self):
939 # All following number fields are read from the pax header.
940 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000941 try:
942 tarinfo = tar.getmember("pax/regtype4")
943 self.assertEqual(tarinfo.size, 7011)
944 self.assertEqual(tarinfo.uid, 123)
945 self.assertEqual(tarinfo.gid, 123)
946 self.assertEqual(tarinfo.mtime, 1041808783.0)
947 self.assertEqual(type(tarinfo.mtime), float)
948 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
949 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
950 finally:
951 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000952
953
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300954class WriteTestBase(TarTest):
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000955 # Put all write tests in here that are supposed to be tested
956 # in all possible mode combinations.
957
958 def test_fileobj_no_close(self):
959 fobj = io.BytesIO()
960 tar = tarfile.open(fileobj=fobj, mode=self.mode)
961 tar.addfile(tarfile.TarInfo("foo"))
962 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300963 self.assertFalse(fobj.closed, "external fileobjs must never closed")
Serhiy Storchaka9fbec7a2014-01-18 15:53:05 +0200964 # Issue #20238: Incomplete gzip output with mode="w:gz"
965 data = fobj.getvalue()
966 del tar
967 support.gc_collect()
968 self.assertFalse(fobj.closed)
969 self.assertEqual(data, fobj.getvalue())
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000970
971
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300972class WriteTest(WriteTestBase, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000973
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300974 prefix = "w:"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000975
976 def test_100_char_name(self):
977 # The name field in a tar header stores strings of at most 100 chars.
978 # If a string is shorter than 100 chars it has to be padded with '\0',
979 # which implies that a string of exactly 100 chars is stored without
980 # a trailing '\0'.
981 name = "0123456789" * 10
982 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000983 try:
984 t = tarfile.TarInfo(name)
985 tar.addfile(t)
986 finally:
987 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000988
Guido van Rossumd8faa362007-04-27 19:54:29 +0000989 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000990 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300991 self.assertEqual(tar.getnames()[0], name,
Antoine Pitrou95f55602010-09-23 18:36:46 +0000992 "failed to store 100 char filename")
993 finally:
994 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000995
Guido van Rossumd8faa362007-04-27 19:54:29 +0000996 def test_tar_size(self):
997 # Test for bug #1013882.
998 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000999 try:
1000 path = os.path.join(TEMPDIR, "file")
1001 with open(path, "wb") as fobj:
1002 fobj.write(b"aaa")
1003 tar.add(path)
1004 finally:
1005 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001006 self.assertGreater(os.path.getsize(tmpname), 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001007 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +00001008
Guido van Rossumd8faa362007-04-27 19:54:29 +00001009 # The test_*_size tests test for bug #1167128.
1010 def test_file_size(self):
1011 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001012 try:
1013 path = os.path.join(TEMPDIR, "file")
1014 with open(path, "wb"):
1015 pass
1016 tarinfo = tar.gettarinfo(path)
1017 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001018
Antoine Pitrou95f55602010-09-23 18:36:46 +00001019 with open(path, "wb") as fobj:
1020 fobj.write(b"aaa")
1021 tarinfo = tar.gettarinfo(path)
1022 self.assertEqual(tarinfo.size, 3)
1023 finally:
1024 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001025
1026 def test_directory_size(self):
1027 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001028 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029 try:
1030 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001031 try:
1032 tarinfo = tar.gettarinfo(path)
1033 self.assertEqual(tarinfo.size, 0)
1034 finally:
1035 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001036 finally:
1037 os.rmdir(path)
1038
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001039 @unittest.skipUnless(hasattr(os, "link"),
1040 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001041 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001042 link = os.path.join(TEMPDIR, "link")
1043 target = os.path.join(TEMPDIR, "link_target")
1044 with open(target, "wb") as fobj:
1045 fobj.write(b"aaa")
1046 os.link(target, link)
1047 try:
1048 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001050 # Record the link target in the inodes list.
1051 tar.gettarinfo(target)
1052 tarinfo = tar.gettarinfo(link)
1053 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001054 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001055 tar.close()
1056 finally:
1057 os.remove(target)
1058 os.remove(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001059
Brian Curtin3b4499c2010-12-28 14:31:47 +00001060 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +00001061 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +00001062 path = os.path.join(TEMPDIR, "symlink")
1063 os.symlink("link_target", path)
1064 try:
1065 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001066 try:
1067 tarinfo = tar.gettarinfo(path)
1068 self.assertEqual(tarinfo.size, 0)
1069 finally:
1070 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +00001071 finally:
1072 os.remove(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001073
1074 def test_add_self(self):
1075 # Test for #1257255.
1076 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001077 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001078 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001079 self.assertEqual(tar.name, dstname,
1080 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001081 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001082 self.assertEqual(tar.getnames(), [],
1083 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001084
Antoine Pitrou95f55602010-09-23 18:36:46 +00001085 cwd = os.getcwd()
1086 os.chdir(TEMPDIR)
1087 tar.add(dstname)
1088 os.chdir(cwd)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001089 self.assertEqual(tar.getnames(), [],
1090 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001091 finally:
1092 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001093
Guido van Rossum486364b2007-06-30 05:01:58 +00001094 def test_exclude(self):
1095 tempdir = os.path.join(TEMPDIR, "exclude")
1096 os.mkdir(tempdir)
1097 try:
1098 for name in ("foo", "bar", "baz"):
1099 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001100 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +00001101
Benjamin Peterson886af962010-03-21 23:13:07 +00001102 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +00001103
1104 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001105 try:
1106 with support.check_warnings(("use the filter argument",
1107 DeprecationWarning)):
1108 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
1109 finally:
1110 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001111
1112 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001113 try:
1114 self.assertEqual(len(tar.getmembers()), 1)
1115 self.assertEqual(tar.getnames()[0], "empty_dir")
1116 finally:
1117 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001118 finally:
1119 shutil.rmtree(tempdir)
1120
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001121 def test_filter(self):
1122 tempdir = os.path.join(TEMPDIR, "filter")
1123 os.mkdir(tempdir)
1124 try:
1125 for name in ("foo", "bar", "baz"):
1126 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001127 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001128
1129 def filter(tarinfo):
1130 if os.path.basename(tarinfo.name) == "bar":
1131 return
1132 tarinfo.uid = 123
1133 tarinfo.uname = "foo"
1134 return tarinfo
1135
1136 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001137 try:
1138 tar.add(tempdir, arcname="empty_dir", filter=filter)
1139 finally:
1140 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001141
Raymond Hettingera63a3122011-01-26 20:34:14 +00001142 # Verify that filter is a keyword-only argument
1143 with self.assertRaises(TypeError):
1144 tar.add(tempdir, "empty_dir", True, None, filter)
1145
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001146 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001147 try:
1148 for tarinfo in tar:
1149 self.assertEqual(tarinfo.uid, 123)
1150 self.assertEqual(tarinfo.uname, "foo")
1151 self.assertEqual(len(tar.getmembers()), 3)
1152 finally:
1153 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001154 finally:
1155 shutil.rmtree(tempdir)
1156
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001157 # Guarantee that stored pathnames are not modified. Don't
1158 # remove ./ or ../ or double slashes. Still make absolute
1159 # pathnames relative.
1160 # For details see bug #6054.
1161 def _test_pathname(self, path, cmp_path=None, dir=False):
1162 # Create a tarfile with an empty member named path
1163 # and compare the stored name with the original.
1164 foo = os.path.join(TEMPDIR, "foo")
1165 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001166 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001167 else:
1168 os.mkdir(foo)
1169
1170 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001171 try:
1172 tar.add(foo, arcname=path)
1173 finally:
1174 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001175
1176 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001177 try:
1178 t = tar.next()
1179 finally:
1180 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001181
1182 if not dir:
1183 os.remove(foo)
1184 else:
1185 os.rmdir(foo)
1186
1187 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1188
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001189
1190 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001191 def test_extractall_symlinks(self):
1192 # Test if extractall works properly when tarfile contains symlinks
1193 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1194 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1195 os.mkdir(tempdir)
1196 try:
1197 source_file = os.path.join(tempdir,'source')
1198 target_file = os.path.join(tempdir,'symlink')
1199 with open(source_file,'w') as f:
1200 f.write('something\n')
1201 os.symlink(source_file, target_file)
1202 tar = tarfile.open(temparchive,'w')
1203 tar.add(source_file)
1204 tar.add(target_file)
1205 tar.close()
1206 # Let's extract it to the location which contains the symlink
1207 tar = tarfile.open(temparchive,'r')
1208 # this should not raise OSError: [Errno 17] File exists
1209 try:
1210 tar.extractall(path=tempdir)
1211 except OSError:
1212 self.fail("extractall failed with symlinked files")
1213 finally:
1214 tar.close()
1215 finally:
1216 os.unlink(temparchive)
1217 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001218
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001219 def test_pathnames(self):
1220 self._test_pathname("foo")
1221 self._test_pathname(os.path.join("foo", ".", "bar"))
1222 self._test_pathname(os.path.join("foo", "..", "bar"))
1223 self._test_pathname(os.path.join(".", "foo"))
1224 self._test_pathname(os.path.join(".", "foo", "."))
1225 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1226 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1227 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1228 self._test_pathname(os.path.join("..", "foo"))
1229 self._test_pathname(os.path.join("..", "foo", ".."))
1230 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1231 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1232
1233 self._test_pathname("foo" + os.sep + os.sep + "bar")
1234 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1235
1236 def test_abs_pathnames(self):
1237 if sys.platform == "win32":
1238 self._test_pathname("C:\\foo", "foo")
1239 else:
1240 self._test_pathname("/foo", "foo")
1241 self._test_pathname("///foo", "foo")
1242
1243 def test_cwd(self):
1244 # Test adding the current working directory.
1245 cwd = os.getcwd()
1246 os.chdir(TEMPDIR)
1247 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001248 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001249 try:
1250 tar.add(".")
1251 finally:
1252 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001253
1254 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001255 try:
1256 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001257 if t.name != ".":
1258 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001259 finally:
1260 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001261 finally:
1262 os.chdir(cwd)
1263
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001264 def test_open_nonwritable_fileobj(self):
1265 for exctype in OSError, EOFError, RuntimeError:
1266 class BadFile(io.BytesIO):
1267 first = True
1268 def write(self, data):
1269 if self.first:
1270 self.first = False
1271 raise exctype
1272
1273 f = BadFile()
1274 with self.assertRaises(exctype):
1275 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1276 format=tarfile.PAX_FORMAT,
1277 pax_headers={'non': 'empty'})
1278 self.assertFalse(f.closed)
1279
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001280class GzipWriteTest(GzipTest, WriteTest):
1281 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001282
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001283class Bz2WriteTest(Bz2Test, WriteTest):
1284 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001285
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001286class LzmaWriteTest(LzmaTest, WriteTest):
1287 pass
1288
1289
1290class StreamWriteTest(WriteTestBase, unittest.TestCase):
1291
1292 prefix = "w|"
1293 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001294
Guido van Rossumd8faa362007-04-27 19:54:29 +00001295 def test_stream_padding(self):
1296 # Test for bug #1543303.
1297 tar = tarfile.open(tmpname, self.mode)
1298 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001299 if self.decompressor:
1300 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001301 with open(tmpname, "rb") as fobj:
1302 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001303 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001304 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001305 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001306 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001307 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001308 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1309 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001310
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001311 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1312 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001313 def test_file_mode(self):
1314 # Test for issue #8464: Create files with correct
1315 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001316 if os.path.exists(tmpname):
1317 os.remove(tmpname)
1318
1319 original_umask = os.umask(0o022)
1320 try:
1321 tar = tarfile.open(tmpname, self.mode)
1322 tar.close()
1323 mode = os.stat(tmpname).st_mode & 0o777
1324 self.assertEqual(mode, 0o644, "wrong file permissions")
1325 finally:
1326 os.umask(original_umask)
1327
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001328class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1329 pass
1330
1331class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1332 decompressor = bz2.BZ2Decompressor if bz2 else None
1333
1334class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1335 decompressor = lzma.LZMADecompressor if lzma else None
1336
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001337
Guido van Rossumd8faa362007-04-27 19:54:29 +00001338class GNUWriteTest(unittest.TestCase):
1339 # This testcase checks for correct creation of GNU Longname
1340 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001341
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001342 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001343 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001344 return blocks * 512
1345
1346 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001347 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001348 count = 512
1349
1350 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001351 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001352 count += 512
1353 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001354 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001355 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001356 count += 512
1357 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001358 return count
1359
1360 def _test(self, name, link=None):
1361 tarinfo = tarfile.TarInfo(name)
1362 if link:
1363 tarinfo.linkname = link
1364 tarinfo.type = tarfile.LNKTYPE
1365
Guido van Rossumd8faa362007-04-27 19:54:29 +00001366 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001367 try:
1368 tar.format = tarfile.GNU_FORMAT
1369 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001370
Antoine Pitrou95f55602010-09-23 18:36:46 +00001371 v1 = self._calc_size(name, link)
1372 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001373 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001374 finally:
1375 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001376
Guido van Rossumd8faa362007-04-27 19:54:29 +00001377 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001378 try:
1379 member = tar.next()
1380 self.assertIsNotNone(member,
1381 "unable to read longname member")
1382 self.assertEqual(tarinfo.name, member.name,
1383 "unable to read longname member")
1384 self.assertEqual(tarinfo.linkname, member.linkname,
1385 "unable to read longname member")
1386 finally:
1387 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001388
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001389 def test_longname_1023(self):
1390 self._test(("longnam/" * 127) + "longnam")
1391
1392 def test_longname_1024(self):
1393 self._test(("longnam/" * 127) + "longname")
1394
1395 def test_longname_1025(self):
1396 self._test(("longnam/" * 127) + "longname_")
1397
1398 def test_longlink_1023(self):
1399 self._test("name", ("longlnk/" * 127) + "longlnk")
1400
1401 def test_longlink_1024(self):
1402 self._test("name", ("longlnk/" * 127) + "longlink")
1403
1404 def test_longlink_1025(self):
1405 self._test("name", ("longlnk/" * 127) + "longlink_")
1406
1407 def test_longnamelink_1023(self):
1408 self._test(("longnam/" * 127) + "longnam",
1409 ("longlnk/" * 127) + "longlnk")
1410
1411 def test_longnamelink_1024(self):
1412 self._test(("longnam/" * 127) + "longname",
1413 ("longlnk/" * 127) + "longlink")
1414
1415 def test_longnamelink_1025(self):
1416 self._test(("longnam/" * 127) + "longname_",
1417 ("longlnk/" * 127) + "longlink_")
1418
Guido van Rossumd8faa362007-04-27 19:54:29 +00001419
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001420@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001421class HardlinkTest(unittest.TestCase):
1422 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001423
1424 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001425 self.foo = os.path.join(TEMPDIR, "foo")
1426 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001427
Antoine Pitrou95f55602010-09-23 18:36:46 +00001428 with open(self.foo, "wb") as fobj:
1429 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001430
Guido van Rossumd8faa362007-04-27 19:54:29 +00001431 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001432
Guido van Rossumd8faa362007-04-27 19:54:29 +00001433 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001434 self.tar.add(self.foo)
1435
Guido van Rossumd8faa362007-04-27 19:54:29 +00001436 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001437 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001438 support.unlink(self.foo)
1439 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001440
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001441 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001442 # The same name will be added as a REGTYPE every
1443 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001444 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001445 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001446 "add file as regular failed")
1447
1448 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001449 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001450 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001451 "add file as hardlink failed")
1452
1453 def test_dereference_hardlink(self):
1454 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001455 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001456 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001457 "dereferencing hardlink failed")
1458
Neal Norwitza4f651a2004-07-20 22:07:44 +00001459
Guido van Rossumd8faa362007-04-27 19:54:29 +00001460class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001461
Guido van Rossumd8faa362007-04-27 19:54:29 +00001462 def _test(self, name, link=None):
1463 # See GNUWriteTest.
1464 tarinfo = tarfile.TarInfo(name)
1465 if link:
1466 tarinfo.linkname = link
1467 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001468
Guido van Rossumd8faa362007-04-27 19:54:29 +00001469 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001470 try:
1471 tar.addfile(tarinfo)
1472 finally:
1473 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001474
Guido van Rossumd8faa362007-04-27 19:54:29 +00001475 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001476 try:
1477 if link:
1478 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001479 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001480 else:
1481 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001482 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001483 finally:
1484 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001485
Guido van Rossume7ba4952007-06-06 23:52:48 +00001486 def test_pax_global_header(self):
1487 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001488 "foo": "bar",
1489 "uid": "0",
1490 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001491 "test": "\xe4\xf6\xfc",
1492 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001493
Benjamin Peterson886af962010-03-21 23:13:07 +00001494 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001495 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001496 try:
1497 tar.addfile(tarfile.TarInfo("test"))
1498 finally:
1499 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001500
1501 # Test if the global header was written correctly.
1502 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001503 try:
1504 self.assertEqual(tar.pax_headers, pax_headers)
1505 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1506 # Test if all the fields are strings.
1507 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001508 self.assertIsNot(type(key), bytes)
1509 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001510 if key in tarfile.PAX_NUMBER_FIELDS:
1511 try:
1512 tarfile.PAX_NUMBER_FIELDS[key](val)
1513 except (TypeError, ValueError):
1514 self.fail("unable to convert pax header field")
1515 finally:
1516 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001517
1518 def test_pax_extended_header(self):
1519 # The fields from the pax header have priority over the
1520 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001521 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001522
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001523 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1524 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001525 try:
1526 t = tarfile.TarInfo()
1527 t.name = "\xe4\xf6\xfc" # non-ASCII
1528 t.uid = 8**8 # too large
1529 t.pax_headers = pax_headers
1530 tar.addfile(t)
1531 finally:
1532 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001533
1534 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001535 try:
1536 t = tar.getmembers()[0]
1537 self.assertEqual(t.pax_headers, pax_headers)
1538 self.assertEqual(t.name, "foo")
1539 self.assertEqual(t.uid, 123)
1540 finally:
1541 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001542
1543
1544class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001545
1546 format = tarfile.USTAR_FORMAT
1547
1548 def test_iso8859_1_filename(self):
1549 self._test_unicode_filename("iso8859-1")
1550
1551 def test_utf7_filename(self):
1552 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001553
1554 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001555 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001556
Guido van Rossumd8faa362007-04-27 19:54:29 +00001557 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001558 tar = tarfile.open(tmpname, "w", format=self.format,
1559 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001560 try:
1561 name = "\xe4\xf6\xfc"
1562 tar.addfile(tarfile.TarInfo(name))
1563 finally:
1564 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001565
1566 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001567 try:
1568 self.assertEqual(tar.getmembers()[0].name, name)
1569 finally:
1570 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001571
1572 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001573 tar = tarfile.open(tmpname, "w", format=self.format,
1574 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001575 try:
1576 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001577
Antoine Pitrou95f55602010-09-23 18:36:46 +00001578 tarinfo.name = "\xe4\xf6\xfc"
1579 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001580
Antoine Pitrou95f55602010-09-23 18:36:46 +00001581 tarinfo.name = "foo"
1582 tarinfo.uname = "\xe4\xf6\xfc"
1583 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1584 finally:
1585 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001586
1587 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001588 tar = tarfile.open(tarname, "r",
1589 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001590 try:
1591 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001592 self.assertIs(type(t.name), str)
1593 self.assertIs(type(t.linkname), str)
1594 self.assertIs(type(t.uname), str)
1595 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001596 finally:
1597 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001598
Guido van Rossume7ba4952007-06-06 23:52:48 +00001599 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001600 t = tarfile.TarInfo("foo")
1601 t.uname = "\xe4\xf6\xfc"
1602 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001603
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001604 tar = tarfile.open(tmpname, mode="w", format=self.format,
1605 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001606 try:
1607 tar.addfile(t)
1608 finally:
1609 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001610
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001611 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001612 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001613 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001614 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1615 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1616
1617 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001618 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001619 tar = tarfile.open(tmpname, encoding="ascii")
1620 t = tar.getmember("foo")
1621 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1622 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1623 finally:
1624 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001625
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001626
Guido van Rossume7ba4952007-06-06 23:52:48 +00001627class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001628
Guido van Rossume7ba4952007-06-06 23:52:48 +00001629 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001630
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001631 def test_bad_pax_header(self):
1632 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1633 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001634 for encoding, name in (
1635 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001636 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001637 with tarfile.open(tarname, encoding=encoding,
1638 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001639 try:
1640 t = tar.getmember(name)
1641 except KeyError:
1642 self.fail("unable to read bad GNU tar pax header")
1643
Guido van Rossumd8faa362007-04-27 19:54:29 +00001644
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001645class PAXUnicodeTest(UstarUnicodeTest):
1646
1647 format = tarfile.PAX_FORMAT
1648
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001649 # PAX_FORMAT ignores encoding in write mode.
1650 test_unicode_filename_error = None
1651
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001652 def test_binary_header(self):
1653 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001654 for encoding, name in (
1655 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001656 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001657 with tarfile.open(tarname, encoding=encoding,
1658 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001659 try:
1660 t = tar.getmember(name)
1661 except KeyError:
1662 self.fail("unable to read POSIX.1-2008 binary header")
1663
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001664
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001665class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001666 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001667
Guido van Rossumd8faa362007-04-27 19:54:29 +00001668 def setUp(self):
1669 self.tarname = tmpname
1670 if os.path.exists(self.tarname):
1671 os.remove(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001672
Guido van Rossumd8faa362007-04-27 19:54:29 +00001673 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001674 with tarfile.open(tarname, encoding="iso8859-1") as src:
1675 t = src.getmember("ustar/regtype")
1676 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001677 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001678 with tarfile.open(self.tarname, mode) as tar:
1679 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001680
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001681 def test_append_compressed(self):
1682 self._create_testtar("w:" + self.suffix)
1683 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1684
1685class AppendTest(AppendTestBase, unittest.TestCase):
1686 test_append_compressed = None
1687
1688 def _add_testfile(self, fileobj=None):
1689 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1690 tar.addfile(tarfile.TarInfo("bar"))
1691
Guido van Rossumd8faa362007-04-27 19:54:29 +00001692 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001693 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1694 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001695
1696 def test_non_existing(self):
1697 self._add_testfile()
1698 self._test()
1699
1700 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001701 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001702 self._add_testfile()
1703 self._test()
1704
1705 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001706 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001707 self._add_testfile(fobj)
1708 fobj.seek(0)
1709 self._test(fileobj=fobj)
1710
1711 def test_fileobj(self):
1712 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001713 with open(self.tarname, "rb") as fobj:
1714 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001715 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001716 self._add_testfile(fobj)
1717 fobj.seek(0)
1718 self._test(names=["foo", "bar"], fileobj=fobj)
1719
1720 def test_existing(self):
1721 self._create_testtar()
1722 self._add_testfile()
1723 self._test(names=["foo", "bar"])
1724
Lars Gustäbel9520a432009-11-22 18:48:49 +00001725 # Append mode is supposed to fail if the tarfile to append to
1726 # does not end with a zero block.
1727 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001728 with open(self.tarname, "wb") as fobj:
1729 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001730 self.assertRaises(tarfile.ReadError, self._add_testfile)
1731
1732 def test_null(self):
1733 self._test_error(b"")
1734
1735 def test_incomplete(self):
1736 self._test_error(b"\0" * 13)
1737
1738 def test_premature_eof(self):
1739 data = tarfile.TarInfo("foo").tobuf()
1740 self._test_error(data)
1741
1742 def test_trailing_garbage(self):
1743 data = tarfile.TarInfo("foo").tobuf()
1744 self._test_error(data + b"\0" * 13)
1745
1746 def test_invalid(self):
1747 self._test_error(b"a" * 512)
1748
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001749class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
1750 pass
1751
1752class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
1753 pass
1754
1755class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
1756 pass
1757
Guido van Rossumd8faa362007-04-27 19:54:29 +00001758
1759class LimitsTest(unittest.TestCase):
1760
1761 def test_ustar_limits(self):
1762 # 100 char name
1763 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001764 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001765
1766 # 101 char name that cannot be stored
1767 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001768 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001769
1770 # 256 char name with a slash at pos 156
1771 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001772 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001773
1774 # 256 char name that cannot be stored
1775 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001776 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001777
1778 # 512 char name
1779 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001780 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001781
1782 # 512 char linkname
1783 tarinfo = tarfile.TarInfo("longlink")
1784 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001785 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001786
1787 # uid > 8 digits
1788 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001789 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001790 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001791
1792 def test_gnu_limits(self):
1793 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001794 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001795
1796 tarinfo = tarfile.TarInfo("longlink")
1797 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001798 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001799
1800 # uid >= 256 ** 7
1801 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001802 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001803 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001804
1805 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001806 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001807 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001808
1809 tarinfo = tarfile.TarInfo("longlink")
1810 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001811 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001812
1813 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001814 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001815 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001816
1817
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001818class MiscTest(unittest.TestCase):
1819
1820 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001821 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
1822 b"foo\0\0\0\0\0")
1823 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
1824 b"foo")
1825 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
1826 "foo")
1827 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
1828 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001829
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001830 def test_read_number_fields(self):
1831 # Issue 13158: Test if GNU tar specific base-256 number fields
1832 # are decoded correctly.
1833 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1834 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001835 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
1836 0o10000000)
1837 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
1838 0xffffffff)
1839 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
1840 -1)
1841 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
1842 -100)
1843 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
1844 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001845
1846 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001847 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001848 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001849 self.assertEqual(tarfile.itn(0o10000000),
1850 b"\x80\x00\x00\x00\x00\x20\x00\x00")
1851 self.assertEqual(tarfile.itn(0xffffffff),
1852 b"\x80\x00\x00\x00\xff\xff\xff\xff")
1853 self.assertEqual(tarfile.itn(-1),
1854 b"\xff\xff\xff\xff\xff\xff\xff\xff")
1855 self.assertEqual(tarfile.itn(-100),
1856 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1857 self.assertEqual(tarfile.itn(-0x100000000000000),
1858 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001859
1860 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001861 with self.assertRaises(ValueError):
1862 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
1863 with self.assertRaises(ValueError):
1864 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
1865 with self.assertRaises(ValueError):
1866 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
1867 with self.assertRaises(ValueError):
1868 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001869
1870
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001871class CommandLineTest(unittest.TestCase):
1872
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001873 def tarfilecmd(self, *args, **kwargs):
1874 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
1875 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01001876 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001877
1878 def tarfilecmd_failure(self, *args):
1879 return script_helper.assert_python_failure('-m', 'tarfile', *args)
1880
1881 def make_simple_tarfile(self, tar_name):
1882 files = [support.findfile('tokenize_tests.txt'),
1883 support.findfile('tokenize_tests-no-coding-cookie-'
1884 'and-utf8-bom-sig-only.txt')]
1885 self.addCleanup(support.unlink, tar_name)
1886 with tarfile.open(tar_name, 'w') as tf:
1887 for tardata in files:
1888 tf.add(tardata, arcname=os.path.basename(tardata))
1889
1890 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001891 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001892 for opt in '-t', '--test':
1893 out = self.tarfilecmd(opt, tar_name)
1894 self.assertEqual(out, b'')
1895
1896 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001897 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001898 for opt in '-v', '--verbose':
1899 out = self.tarfilecmd(opt, '-t', tar_name)
1900 self.assertIn(b'is a tar archive.\n', out)
1901
1902 def test_test_command_invalid_file(self):
1903 zipname = support.findfile('zipdir.zip')
1904 rc, out, err = self.tarfilecmd_failure('-t', zipname)
1905 self.assertIn(b' is not a tar archive.', err)
1906 self.assertEqual(out, b'')
1907 self.assertEqual(rc, 1)
1908
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001909 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001910 with self.subTest(tar_name=tar_name):
1911 with open(tar_name, 'rb') as f:
1912 data = f.read()
1913 try:
1914 with open(tmpname, 'wb') as f:
1915 f.write(data[:511])
1916 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
1917 self.assertEqual(out, b'')
1918 self.assertEqual(rc, 1)
1919 finally:
1920 support.unlink(tmpname)
1921
1922 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001923 for tar_name in testtarnames:
1924 with support.captured_stdout() as t:
1925 with tarfile.open(tar_name, 'r') as tf:
1926 tf.list(verbose=False)
1927 expected = t.getvalue().encode('ascii', 'backslashreplace')
1928 for opt in '-l', '--list':
1929 out = self.tarfilecmd(opt, tar_name,
1930 PYTHONIOENCODING='ascii')
1931 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001932
1933 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001934 for tar_name in testtarnames:
1935 with support.captured_stdout() as t:
1936 with tarfile.open(tar_name, 'r') as tf:
1937 tf.list(verbose=True)
1938 expected = t.getvalue().encode('ascii', 'backslashreplace')
1939 for opt in '-v', '--verbose':
1940 out = self.tarfilecmd(opt, '-l', tar_name,
1941 PYTHONIOENCODING='ascii')
1942 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001943
1944 def test_list_command_invalid_file(self):
1945 zipname = support.findfile('zipdir.zip')
1946 rc, out, err = self.tarfilecmd_failure('-l', zipname)
1947 self.assertIn(b' is not a tar archive.', err)
1948 self.assertEqual(out, b'')
1949 self.assertEqual(rc, 1)
1950
1951 def test_create_command(self):
1952 files = [support.findfile('tokenize_tests.txt'),
1953 support.findfile('tokenize_tests-no-coding-cookie-'
1954 'and-utf8-bom-sig-only.txt')]
1955 for opt in '-c', '--create':
1956 try:
1957 out = self.tarfilecmd(opt, tmpname, *files)
1958 self.assertEqual(out, b'')
1959 with tarfile.open(tmpname) as tar:
1960 tar.getmembers()
1961 finally:
1962 support.unlink(tmpname)
1963
1964 def test_create_command_verbose(self):
1965 files = [support.findfile('tokenize_tests.txt'),
1966 support.findfile('tokenize_tests-no-coding-cookie-'
1967 'and-utf8-bom-sig-only.txt')]
1968 for opt in '-v', '--verbose':
1969 try:
1970 out = self.tarfilecmd(opt, '-c', tmpname, *files)
1971 self.assertIn(b' file created.', out)
1972 with tarfile.open(tmpname) as tar:
1973 tar.getmembers()
1974 finally:
1975 support.unlink(tmpname)
1976
1977 def test_create_command_dotless_filename(self):
1978 files = [support.findfile('tokenize_tests.txt')]
1979 try:
1980 out = self.tarfilecmd('-c', dotlessname, *files)
1981 self.assertEqual(out, b'')
1982 with tarfile.open(dotlessname) as tar:
1983 tar.getmembers()
1984 finally:
1985 support.unlink(dotlessname)
1986
1987 def test_create_command_dot_started_filename(self):
1988 tar_name = os.path.join(TEMPDIR, ".testtar")
1989 files = [support.findfile('tokenize_tests.txt')]
1990 try:
1991 out = self.tarfilecmd('-c', tar_name, *files)
1992 self.assertEqual(out, b'')
1993 with tarfile.open(tar_name) as tar:
1994 tar.getmembers()
1995 finally:
1996 support.unlink(tar_name)
1997
1998 def test_extract_command(self):
1999 self.make_simple_tarfile(tmpname)
2000 for opt in '-e', '--extract':
2001 try:
2002 with support.temp_cwd(tarextdir):
2003 out = self.tarfilecmd(opt, tmpname)
2004 self.assertEqual(out, b'')
2005 finally:
2006 support.rmtree(tarextdir)
2007
2008 def test_extract_command_verbose(self):
2009 self.make_simple_tarfile(tmpname)
2010 for opt in '-v', '--verbose':
2011 try:
2012 with support.temp_cwd(tarextdir):
2013 out = self.tarfilecmd(opt, '-e', tmpname)
2014 self.assertIn(b' file is extracted.', out)
2015 finally:
2016 support.rmtree(tarextdir)
2017
2018 def test_extract_command_different_directory(self):
2019 self.make_simple_tarfile(tmpname)
2020 try:
2021 with support.temp_cwd(tarextdir):
2022 out = self.tarfilecmd('-e', tmpname, 'spamdir')
2023 self.assertEqual(out, b'')
2024 finally:
2025 support.rmtree(tarextdir)
2026
2027 def test_extract_command_invalid_file(self):
2028 zipname = support.findfile('zipdir.zip')
2029 with support.temp_cwd(tarextdir):
2030 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2031 self.assertIn(b' is not a tar archive.', err)
2032 self.assertEqual(out, b'')
2033 self.assertEqual(rc, 1)
2034
2035
Lars Gustäbel01385812010-03-03 12:08:54 +00002036class ContextManagerTest(unittest.TestCase):
2037
2038 def test_basic(self):
2039 with tarfile.open(tarname) as tar:
2040 self.assertFalse(tar.closed, "closed inside runtime context")
2041 self.assertTrue(tar.closed, "context manager failed")
2042
2043 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002044 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002045 # if the TarFile object is already closed.
2046 tar = tarfile.open(tarname)
2047 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002048 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002049 with tar:
2050 pass
2051
2052 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002053 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002054 with self.assertRaises(Exception) as exc:
2055 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002056 raise OSError
2057 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002058 "wrong exception raised in context manager")
2059 self.assertTrue(tar.closed, "context manager failed")
2060
2061 def test_no_eof(self):
2062 # __exit__() must not write end-of-archive blocks if an
2063 # exception was raised.
2064 try:
2065 with tarfile.open(tmpname, "w") as tar:
2066 raise Exception
2067 except:
2068 pass
2069 self.assertEqual(os.path.getsize(tmpname), 0,
2070 "context manager wrote an end-of-archive block")
2071 self.assertTrue(tar.closed, "context manager failed")
2072
2073 def test_eof(self):
2074 # __exit__() must write end-of-archive blocks, i.e. call
2075 # TarFile.close() if there was no error.
2076 with tarfile.open(tmpname, "w"):
2077 pass
2078 self.assertNotEqual(os.path.getsize(tmpname), 0,
2079 "context manager wrote no end-of-archive block")
2080
2081 def test_fileobj(self):
2082 # Test that __exit__() did not close the external file
2083 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002084 with open(tmpname, "wb") as fobj:
2085 try:
2086 with tarfile.open(fileobj=fobj, mode="w") as tar:
2087 raise Exception
2088 except:
2089 pass
2090 self.assertFalse(fobj.closed, "external file object was closed")
2091 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002092
2093
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002094@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2095class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002096
2097 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002098 # symbolic or hard links tarfile tries to extract these types of members
2099 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002100 def _test_link_extraction(self, name):
2101 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002102 with open(os.path.join(TEMPDIR, name), "rb") as f:
2103 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002104 self.assertEqual(md5sum(data), md5_regtype)
2105
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002106 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002107 @unittest.skipIf(hasattr(os.path, "islink"),
2108 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002109 def test_hardlink_extraction1(self):
2110 self._test_link_extraction("ustar/lnktype")
2111
Brian Curtind40e6f72010-07-08 21:39:08 +00002112 @unittest.skipIf(hasattr(os.path, "islink"),
2113 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002114 def test_hardlink_extraction2(self):
2115 self._test_link_extraction("./ustar/linktest2/lnktype")
2116
Brian Curtin74e45612010-07-09 15:58:59 +00002117 @unittest.skipIf(hasattr(os, "symlink"),
2118 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002119 def test_symlink_extraction1(self):
2120 self._test_link_extraction("ustar/symtype")
2121
Brian Curtin74e45612010-07-09 15:58:59 +00002122 @unittest.skipIf(hasattr(os, "symlink"),
2123 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002124 def test_symlink_extraction2(self):
2125 self._test_link_extraction("./ustar/linktest2/symtype")
2126
2127
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002128class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002129 # Issue5068: The _BZ2Proxy.read() method loops forever
2130 # on an empty or partial bzipped file.
2131
2132 def _test_partial_input(self, mode):
2133 class MyBytesIO(io.BytesIO):
2134 hit_eof = False
2135 def read(self, n):
2136 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002137 raise AssertionError("infinite loop detected in "
2138 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002139 self.hit_eof = self.tell() == len(self.getvalue())
2140 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002141 def seek(self, *args):
2142 self.hit_eof = False
2143 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002144
2145 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2146 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002147 try:
2148 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2149 except tarfile.ReadError:
2150 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002151
2152 def test_partial_input(self):
2153 self._test_partial_input("r")
2154
2155 def test_partial_input_bz2(self):
2156 self._test_partial_input("r:bz2")
2157
2158
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002159def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002160 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002161 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002162
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002163 global testtarnames
2164 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002165 with open(tarname, "rb") as fobj:
2166 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002167
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002168 # Create compressed tarfiles.
2169 for c in GzipTest, Bz2Test, LzmaTest:
2170 if c.open:
2171 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002172 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002173 with c.open(c.tarname, "wb") as tar:
2174 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002175
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002176def tearDownModule():
2177 if os.path.exists(TEMPDIR):
2178 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002179
Neal Norwitz996acf12003-02-17 14:51:41 +00002180if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002181 unittest.main()