blob: 92f8bfe920c6b5d60f8d5cd1ee01d5374b42eaf2 [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):
Thomas Woutersed03b412007-08-28 21:37:11 +0000355 def test_no_name_argument(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000356 with open(self.tarname, "rb") as fobj:
357 tar = tarfile.open(fileobj=fobj, mode=self.mode)
358 self.assertEqual(tar.name, os.path.abspath(fobj.name))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000359
Thomas Woutersed03b412007-08-28 21:37:11 +0000360 def test_no_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000361 with open(self.tarname, "rb") as fobj:
362 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000363 fobj = io.BytesIO(data)
364 self.assertRaises(AttributeError, getattr, fobj, "name")
365 tar = tarfile.open(fileobj=fobj, mode=self.mode)
366 self.assertEqual(tar.name, None)
367
368 def test_empty_name_attribute(self):
Antoine Pitrou95f55602010-09-23 18:36:46 +0000369 with open(self.tarname, "rb") as fobj:
370 data = fobj.read()
Thomas Woutersed03b412007-08-28 21:37:11 +0000371 fobj = io.BytesIO(data)
372 fobj.name = ""
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000373 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
374 self.assertEqual(tar.name, None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000375
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +0200376 def test_illegal_mode_arg(self):
377 with open(tmpname, 'wb'):
378 pass
379 with self.assertRaisesRegex(ValueError, 'mode must be '):
380 tar = self.taropen(tmpname, 'q')
381 with self.assertRaisesRegex(ValueError, 'mode must be '):
382 tar = self.taropen(tmpname, 'rw')
383 with self.assertRaisesRegex(ValueError, 'mode must be '):
384 tar = self.taropen(tmpname, '')
385
Christian Heimesd8654cf2007-12-02 15:22:16 +0000386 def test_fileobj_with_offset(self):
387 # Skip the first member and store values from the second member
388 # of the testtar.
389 tar = tarfile.open(self.tarname, mode=self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000390 try:
391 tar.next()
392 t = tar.next()
393 name = t.name
394 offset = t.offset
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200395 with tar.extractfile(t) as f:
396 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000397 finally:
398 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000399
400 # Open the testtar and seek to the offset of the second member.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300401 with self.open(self.tarname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000402 fobj.seek(offset)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000403
Antoine Pitrou95f55602010-09-23 18:36:46 +0000404 # Test if the tarfile starts with the second member.
405 tar = tar.open(self.tarname, mode="r:", fileobj=fobj)
406 t = tar.next()
407 self.assertEqual(t.name, name)
408 # Read to the end of fileobj and test if seeking back to the
409 # beginning works.
410 tar.getmembers()
411 self.assertEqual(tar.extractfile(t).read(), data,
412 "seek back did not work")
413 tar.close()
Christian Heimesd8654cf2007-12-02 15:22:16 +0000414
Guido van Rossumd8faa362007-04-27 19:54:29 +0000415 def test_fail_comp(self):
416 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000417 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000418 with open(tarname, "rb") as fobj:
419 self.assertRaises(tarfile.ReadError, tarfile.open,
420 fileobj=fobj, mode=self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000421
422 def test_v7_dirtype(self):
423 # Test old style dirtype member (bug #1336623):
424 # Old V7 tars create directory members using an AREGTYPE
425 # header with a "/" appended to the filename field.
426 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300427 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428 "v7 dirtype failed")
429
Christian Heimes126d29a2008-02-11 22:57:17 +0000430 def test_xstar_type(self):
431 # The xstar format stores extra atime and ctime fields inside the
432 # space reserved for the prefix field. The prefix field must be
433 # ignored in this case, otherwise it will mess up the name.
434 try:
435 self.tar.getmember("misc/regtype-xstar")
436 except KeyError:
437 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
438
Guido van Rossumd8faa362007-04-27 19:54:29 +0000439 def test_check_members(self):
440 for tarinfo in self.tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300441 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000442 "wrong mtime for %s" % tarinfo.name)
443 if not tarinfo.name.startswith("ustar/"):
444 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300445 self.assertEqual(tarinfo.uname, "tarfile",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000446 "wrong uname for %s" % tarinfo.name)
447
448 def test_find_members(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300449 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000450 "could not find all members")
451
Brian Curtin74e45612010-07-09 15:58:59 +0000452 @unittest.skipUnless(hasattr(os, "link"),
453 "Missing hardlink implementation")
Brian Curtin3b4499c2010-12-28 14:31:47 +0000454 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +0000455 def test_extract_hardlink(self):
456 # Test hardlink extraction (e.g. bug #857297).
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200457 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000458 tar.extract("ustar/regtype", TEMPDIR)
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200459 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/regtype"))
Neal Norwitzf3396542005-10-28 05:52:22 +0000460
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200461 tar.extract("ustar/lnktype", TEMPDIR)
462 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/lnktype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000463 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
464 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000465 self.assertEqual(md5sum(data), md5_regtype)
Neal Norwitzf3396542005-10-28 05:52:22 +0000466
Serhiy Storchaka88339c42012-12-30 20:16:30 +0200467 tar.extract("ustar/symtype", TEMPDIR)
468 self.addCleanup(os.remove, os.path.join(TEMPDIR, "ustar/symtype"))
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000469 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
470 data = f.read()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000471 self.assertEqual(md5sum(data), md5_regtype)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472
Christian Heimesfaf2f632008-01-06 16:59:19 +0000473 def test_extractall(self):
474 # Test if extractall() correctly restores directory permissions
475 # and times (see issue1735).
Christian Heimesfaf2f632008-01-06 16:59:19 +0000476 tar = tarfile.open(tarname, encoding="iso8859-1")
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000477 DIR = os.path.join(TEMPDIR, "extractall")
478 os.mkdir(DIR)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000479 try:
480 directories = [t for t in tar if t.isdir()]
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000481 tar.extractall(DIR, directories)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000482 for tarinfo in directories:
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000483 path = os.path.join(DIR, tarinfo.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000484 if sys.platform != "win32":
485 # Win32 has no support for fine grained permissions.
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300486 self.assertEqual(tarinfo.mode & 0o777,
487 os.stat(path).st_mode & 0o777)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000488 def format_mtime(mtime):
489 if isinstance(mtime, float):
490 return "{} ({})".format(mtime, mtime.hex())
491 else:
492 return "{!r} (int)".format(mtime)
Victor Stinner14d8fe72010-10-29 11:02:06 +0000493 file_mtime = os.path.getmtime(path)
Victor Stinner26bfb5a2010-10-29 10:59:08 +0000494 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
495 format_mtime(tarinfo.mtime),
496 format_mtime(file_mtime),
497 path)
498 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000499 finally:
500 tar.close()
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000501 shutil.rmtree(DIR)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000502
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000503 def test_extract_directory(self):
504 dirtype = "ustar/dirtype"
Martin v. Löwisbe647e22010-11-01 22:08:46 +0000505 DIR = os.path.join(TEMPDIR, "extractdir")
506 os.mkdir(DIR)
507 try:
508 with tarfile.open(tarname, encoding="iso8859-1") as tar:
509 tarinfo = tar.getmember(dirtype)
510 tar.extract(tarinfo, path=DIR)
511 extracted = os.path.join(DIR, dirtype)
512 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
513 if sys.platform != "win32":
514 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
515 finally:
516 shutil.rmtree(DIR)
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000517
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000518 def test_init_close_fobj(self):
519 # Issue #7341: Close the internal file object in the TarFile
520 # constructor in case of an error. For the test we rely on
521 # the fact that opening an empty file raises a ReadError.
522 empty = os.path.join(TEMPDIR, "empty")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000523 with open(empty, "wb") as fobj:
524 fobj.write(b"")
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000525
526 try:
527 tar = object.__new__(tarfile.TarFile)
528 try:
529 tar.__init__(empty)
530 except tarfile.ReadError:
531 self.assertTrue(tar.fileobj.closed)
532 else:
533 self.fail("ReadError not raised")
534 finally:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000535 support.unlink(empty)
Lars Gustäbelb7f09232009-11-23 15:48:33 +0000536
Serhiy Storchaka263fab92013-05-09 14:22:26 +0300537 def test_parallel_iteration(self):
538 # Issue #16601: Restarting iteration over tarfile continued
539 # from where it left off.
540 with tarfile.open(self.tarname) as tar:
541 for m1, m2 in zip(tar, tar):
542 self.assertEqual(m1.offset, m2.offset)
543 self.assertEqual(m1.get_info(), m2.get_info())
544
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300545class MiscReadTest(MiscReadTestBase, unittest.TestCase):
546 test_fail_comp = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000547
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300548class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
Serhiy Storchakaf22fe0f2014-01-13 19:08:00 +0200549 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000550
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300551class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
552 def test_no_name_argument(self):
553 self.skipTest("BZ2File have no name attribute")
554
555class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
556 def test_no_name_argument(self):
557 self.skipTest("LZMAFile have no name attribute")
558
559
560class StreamReadTest(CommonReadTest, unittest.TestCase):
561
562 prefix="r|"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000563
Lars Gustäbeldd071042011-02-23 11:42:22 +0000564 def test_read_through(self):
565 # Issue #11224: A poorly designed _FileInFile.read() method
566 # caused seeking errors with stream tar files.
567 for tarinfo in self.tar:
568 if not tarinfo.isreg():
569 continue
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200570 with self.tar.extractfile(tarinfo) as fobj:
571 while True:
572 try:
573 buf = fobj.read(512)
574 except tarfile.StreamError:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300575 self.fail("simple read-through using "
576 "TarFile.extractfile() failed")
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200577 if not buf:
578 break
Lars Gustäbeldd071042011-02-23 11:42:22 +0000579
Guido van Rossumd8faa362007-04-27 19:54:29 +0000580 def test_fileobj_regular_file(self):
581 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200582 with self.tar.extractfile(tarinfo) as fobj:
583 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300584 self.assertEqual(len(data), tarinfo.size,
585 "regular file extraction failed")
586 self.assertEqual(md5sum(data), md5_regtype,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000587 "regular file extraction failed")
588
589 def test_provoke_stream_error(self):
590 tarinfos = self.tar.getmembers()
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200591 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
592 self.assertRaises(tarfile.StreamError, f.read)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000593
Guido van Rossumd8faa362007-04-27 19:54:29 +0000594 def test_compare_members(self):
595 tar1 = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000596 try:
597 tar2 = self.tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000598
Antoine Pitrou95f55602010-09-23 18:36:46 +0000599 while True:
600 t1 = tar1.next()
601 t2 = tar2.next()
602 if t1 is None:
603 break
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300604 self.assertIsNotNone(t2, "stream.next() failed.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000605
Antoine Pitrou95f55602010-09-23 18:36:46 +0000606 if t2.islnk() or t2.issym():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300607 with self.assertRaises(tarfile.StreamError):
608 tar2.extractfile(t2)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000609 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000610
Antoine Pitrou95f55602010-09-23 18:36:46 +0000611 v1 = tar1.extractfile(t1)
612 v2 = tar2.extractfile(t2)
613 if v1 is None:
614 continue
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300615 self.assertIsNotNone(v2, "stream.extractfile() failed")
616 self.assertEqual(v1.read(), v2.read(),
617 "stream extraction failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000618 finally:
619 tar1.close()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000620
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300621class GzipStreamReadTest(GzipTest, StreamReadTest):
622 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000623
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300624class Bz2StreamReadTest(Bz2Test, StreamReadTest):
625 pass
Thomas Wouterscf297e42007-02-23 15:07:44 +0000626
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300627class LzmaStreamReadTest(LzmaTest, StreamReadTest):
628 pass
629
630
631class DetectReadTest(TarTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000632 def _testfunc_file(self, name, mode):
633 try:
Antoine Pitrou95f55602010-09-23 18:36:46 +0000634 tar = tarfile.open(name, mode)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000635 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000637 else:
638 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000639
Guido van Rossumd8faa362007-04-27 19:54:29 +0000640 def _testfunc_fileobj(self, name, mode):
641 try:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000642 with open(name, "rb") as f:
643 tar = tarfile.open(name, mode, fileobj=f)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000644 except tarfile.ReadError as e:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000645 self.fail()
Antoine Pitrou95f55602010-09-23 18:36:46 +0000646 else:
647 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000648
649 def _test_modes(self, testfunc):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300650 if self.suffix:
651 with self.assertRaises(tarfile.ReadError):
652 tarfile.open(tarname, mode="r:" + self.suffix)
653 with self.assertRaises(tarfile.ReadError):
654 tarfile.open(tarname, mode="r|" + self.suffix)
655 with self.assertRaises(tarfile.ReadError):
656 tarfile.open(self.tarname, mode="r:")
657 with self.assertRaises(tarfile.ReadError):
658 tarfile.open(self.tarname, mode="r|")
659 testfunc(self.tarname, "r")
660 testfunc(self.tarname, "r:" + self.suffix)
661 testfunc(self.tarname, "r:*")
662 testfunc(self.tarname, "r|" + self.suffix)
663 testfunc(self.tarname, "r|*")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100664
Guido van Rossumd8faa362007-04-27 19:54:29 +0000665 def test_detect_file(self):
666 self._test_modes(self._testfunc_file)
667
668 def test_detect_fileobj(self):
669 self._test_modes(self._testfunc_fileobj)
670
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300671class GzipDetectReadTest(GzipTest, DetectReadTest):
672 pass
673
674class Bz2DetectReadTest(Bz2Test, DetectReadTest):
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100675 def test_detect_stream_bz2(self):
676 # Originally, tarfile's stream detection looked for the string
677 # "BZh91" at the start of the file. This is incorrect because
678 # the '9' represents the blocksize (900kB). If the file was
679 # compressed using another blocksize autodetection fails.
Lars Gustäbeled1ac582011-12-06 12:56:38 +0100680 with open(tarname, "rb") as fobj:
681 data = fobj.read()
682
683 # Compress with blocksize 100kB, the file starts with "BZh11".
684 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
685 fobj.write(data)
686
687 self._testfunc_file(tmpname, "r|*")
688
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300689class LzmaDetectReadTest(LzmaTest, DetectReadTest):
690 pass
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300692
693class MemberReadTest(ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000694
695 def _test_member(self, tarinfo, chksum=None, **kwargs):
696 if chksum is not None:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300697 with self.tar.extractfile(tarinfo) as f:
698 self.assertEqual(md5sum(f.read()), chksum,
699 "wrong md5sum for %s" % tarinfo.name)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000700
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000701 kwargs["mtime"] = 0o7606136617
Guido van Rossumd8faa362007-04-27 19:54:29 +0000702 kwargs["uid"] = 1000
703 kwargs["gid"] = 100
704 if "old-v7" not in tarinfo.name:
705 # V7 tar can't handle alphabetic owners.
706 kwargs["uname"] = "tarfile"
707 kwargs["gname"] = "tarfile"
708 for k, v in kwargs.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300709 self.assertEqual(getattr(tarinfo, k), v,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000710 "wrong value in %s field of %s" % (k, tarinfo.name))
711
712 def test_find_regtype(self):
713 tarinfo = self.tar.getmember("ustar/regtype")
714 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
715
716 def test_find_conttype(self):
717 tarinfo = self.tar.getmember("ustar/conttype")
718 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
719
720 def test_find_dirtype(self):
721 tarinfo = self.tar.getmember("ustar/dirtype")
722 self._test_member(tarinfo, size=0)
723
724 def test_find_dirtype_with_size(self):
725 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
726 self._test_member(tarinfo, size=255)
727
728 def test_find_lnktype(self):
729 tarinfo = self.tar.getmember("ustar/lnktype")
730 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
731
732 def test_find_symtype(self):
733 tarinfo = self.tar.getmember("ustar/symtype")
734 self._test_member(tarinfo, size=0, linkname="regtype")
735
736 def test_find_blktype(self):
737 tarinfo = self.tar.getmember("ustar/blktype")
738 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
739
740 def test_find_chrtype(self):
741 tarinfo = self.tar.getmember("ustar/chrtype")
742 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
743
744 def test_find_fifotype(self):
745 tarinfo = self.tar.getmember("ustar/fifotype")
746 self._test_member(tarinfo, size=0)
747
748 def test_find_sparse(self):
749 tarinfo = self.tar.getmember("ustar/sparse")
750 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
751
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000752 def test_find_gnusparse(self):
753 tarinfo = self.tar.getmember("gnu/sparse")
754 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
755
756 def test_find_gnusparse_00(self):
757 tarinfo = self.tar.getmember("gnu/sparse-0.0")
758 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
759
760 def test_find_gnusparse_01(self):
761 tarinfo = self.tar.getmember("gnu/sparse-0.1")
762 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
763
764 def test_find_gnusparse_10(self):
765 tarinfo = self.tar.getmember("gnu/sparse-1.0")
766 self._test_member(tarinfo, size=86016, chksum=md5_sparse)
767
Guido van Rossumd8faa362007-04-27 19:54:29 +0000768 def test_find_umlauts(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300769 tarinfo = self.tar.getmember("ustar/umlauts-"
770 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000771 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
772
773 def test_find_ustar_longname(self):
774 name = "ustar/" + "12345/" * 39 + "1234567/longname"
Benjamin Peterson577473f2010-01-19 00:09:57 +0000775 self.assertIn(name, self.tar.getnames())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000776
777 def test_find_regtype_oldv7(self):
778 tarinfo = self.tar.getmember("misc/regtype-old-v7")
779 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
780
781 def test_find_pax_umlauts(self):
Antoine Pitrouab58b5f2010-09-23 19:39:35 +0000782 self.tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300783 self.tar = tarfile.open(self.tarname, mode=self.mode,
784 encoding="iso8859-1")
785 tarinfo = self.tar.getmember("pax/umlauts-"
786 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000787 self._test_member(tarinfo, size=7011, chksum=md5_regtype)
788
789
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300790class LongnameTest:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000791
792 def test_read_longname(self):
793 # Test reading of longname (bug #1471427).
Guido van Rossume7ba4952007-06-06 23:52:48 +0000794 longname = self.subdir + "/" + "123/" * 125 + "longname"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +0000796 tarinfo = self.tar.getmember(longname)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000797 except KeyError:
798 self.fail("longname not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300799 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
800 "read longname as dirtype")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000801
802 def test_read_longlink(self):
803 longname = self.subdir + "/" + "123/" * 125 + "longname"
804 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
805 try:
806 tarinfo = self.tar.getmember(longlink)
807 except KeyError:
808 self.fail("longlink not found")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300809 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000810
811 def test_truncated_longname(self):
812 longname = self.subdir + "/" + "123/" * 125 + "longname"
813 tarinfo = self.tar.getmember(longname)
814 offset = tarinfo.offset
815 self.tar.fileobj.seek(offset)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000816 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300817 with self.assertRaises(tarfile.ReadError):
818 tarfile.open(name="foo.tar", fileobj=fobj)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000819
Guido van Rossume7ba4952007-06-06 23:52:48 +0000820 def test_header_offset(self):
821 # Test if the start offset of the TarInfo object includes
822 # the preceding extended header.
823 longname = self.subdir + "/" + "123/" * 125 + "longname"
824 offset = self.tar.getmember(longname).offset
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000825 with open(tarname, "rb") as fobj:
826 fobj.seek(offset)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300827 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
828 "iso8859-1", "strict")
Antoine Pitroue1eca4e2010-10-29 23:49:49 +0000829 self.assertEqual(tarinfo.type, self.longnametype)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000830
Guido van Rossumd8faa362007-04-27 19:54:29 +0000831
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300832class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000833
834 subdir = "gnu"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000835 longnametype = tarfile.GNUTYPE_LONGNAME
Guido van Rossumd8faa362007-04-27 19:54:29 +0000836
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000837 # Since 3.2 tarfile is supposed to accurately restore sparse members and
838 # produce files with holes. This is what we actually want to test here.
839 # Unfortunately, not all platforms/filesystems support sparse files, and
840 # even on platforms that do it is non-trivial to make reliable assertions
841 # about holes in files. Therefore, we first do one basic test which works
842 # an all platforms, and after that a test that will work only on
843 # platforms/filesystems that prove to support sparse files.
844 def _test_sparse_file(self, name):
845 self.tar.extract(name, TEMPDIR)
846 filename = os.path.join(TEMPDIR, name)
847 with open(filename, "rb") as fobj:
848 data = fobj.read()
849 self.assertEqual(md5sum(data), md5_sparse,
850 "wrong md5sum for %s" % name)
851
852 if self._fs_supports_holes():
853 s = os.stat(filename)
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300854 self.assertLess(s.st_blocks * 512, s.st_size)
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000855
856 def test_sparse_file_old(self):
857 self._test_sparse_file("gnu/sparse")
858
859 def test_sparse_file_00(self):
860 self._test_sparse_file("gnu/sparse-0.0")
861
862 def test_sparse_file_01(self):
863 self._test_sparse_file("gnu/sparse-0.1")
864
865 def test_sparse_file_10(self):
866 self._test_sparse_file("gnu/sparse-1.0")
867
868 @staticmethod
869 def _fs_supports_holes():
870 # Return True if the platform knows the st_blocks stat attribute and
871 # uses st_blocks units of 512 bytes, and if the filesystem is able to
872 # store holes in files.
Victor Stinner9c3de4a2011-08-17 20:49:41 +0200873 if sys.platform.startswith("linux"):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000874 # Linux evidentially has 512 byte st_blocks units.
875 name = os.path.join(TEMPDIR, "sparse-test")
876 with open(name, "wb") as fobj:
877 fobj.seek(4096)
878 fobj.truncate()
879 s = os.stat(name)
880 os.remove(name)
881 return s.st_blocks == 0
882 else:
883 return False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884
885
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300886class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000887
888 subdir = "pax"
Guido van Rossume7ba4952007-06-06 23:52:48 +0000889 longnametype = tarfile.XHDTYPE
Guido van Rossumd8faa362007-04-27 19:54:29 +0000890
Guido van Rossume7ba4952007-06-06 23:52:48 +0000891 def test_pax_global_headers(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000892 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000893 try:
894 tarinfo = tar.getmember("pax/regtype1")
895 self.assertEqual(tarinfo.uname, "foo")
896 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300897 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
898 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossume7ba4952007-06-06 23:52:48 +0000899
Antoine Pitrou95f55602010-09-23 18:36:46 +0000900 tarinfo = tar.getmember("pax/regtype2")
901 self.assertEqual(tarinfo.uname, "")
902 self.assertEqual(tarinfo.gname, "bar")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300903 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
904 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000905
Antoine Pitrou95f55602010-09-23 18:36:46 +0000906 tarinfo = tar.getmember("pax/regtype3")
907 self.assertEqual(tarinfo.uname, "tarfile")
908 self.assertEqual(tarinfo.gname, "tarfile")
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300909 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
910 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000911 finally:
912 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000913
914 def test_pax_number_fields(self):
915 # All following number fields are read from the pax header.
916 tar = tarfile.open(tarname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +0000917 try:
918 tarinfo = tar.getmember("pax/regtype4")
919 self.assertEqual(tarinfo.size, 7011)
920 self.assertEqual(tarinfo.uid, 123)
921 self.assertEqual(tarinfo.gid, 123)
922 self.assertEqual(tarinfo.mtime, 1041808783.0)
923 self.assertEqual(type(tarinfo.mtime), float)
924 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
925 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
926 finally:
927 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000928
929
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300930class WriteTestBase(TarTest):
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000931 # Put all write tests in here that are supposed to be tested
932 # in all possible mode combinations.
933
934 def test_fileobj_no_close(self):
935 fobj = io.BytesIO()
936 tar = tarfile.open(fileobj=fobj, mode=self.mode)
937 tar.addfile(tarfile.TarInfo("foo"))
938 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300939 self.assertFalse(fobj.closed, "external fileobjs must never closed")
Serhiy Storchaka9fbec7a2014-01-18 15:53:05 +0200940 # Issue #20238: Incomplete gzip output with mode="w:gz"
941 data = fobj.getvalue()
942 del tar
943 support.gc_collect()
944 self.assertFalse(fobj.closed)
945 self.assertEqual(data, fobj.getvalue())
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000946
947
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300948class WriteTest(WriteTestBase, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000949
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300950 prefix = "w:"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951
952 def test_100_char_name(self):
953 # The name field in a tar header stores strings of at most 100 chars.
954 # If a string is shorter than 100 chars it has to be padded with '\0',
955 # which implies that a string of exactly 100 chars is stored without
956 # a trailing '\0'.
957 name = "0123456789" * 10
958 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000959 try:
960 t = tarfile.TarInfo(name)
961 tar.addfile(t)
962 finally:
963 tar.close()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000964
Guido van Rossumd8faa362007-04-27 19:54:29 +0000965 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000966 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300967 self.assertEqual(tar.getnames()[0], name,
Antoine Pitrou95f55602010-09-23 18:36:46 +0000968 "failed to store 100 char filename")
969 finally:
970 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000971
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972 def test_tar_size(self):
973 # Test for bug #1013882.
974 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000975 try:
976 path = os.path.join(TEMPDIR, "file")
977 with open(path, "wb") as fobj:
978 fobj.write(b"aaa")
979 tar.add(path)
980 finally:
981 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +0300982 self.assertGreater(os.path.getsize(tmpname), 0,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983 "tarfile is empty")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000984
Guido van Rossumd8faa362007-04-27 19:54:29 +0000985 # The test_*_size tests test for bug #1167128.
986 def test_file_size(self):
987 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +0000988 try:
989 path = os.path.join(TEMPDIR, "file")
990 with open(path, "wb"):
991 pass
992 tarinfo = tar.gettarinfo(path)
993 self.assertEqual(tarinfo.size, 0)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +0000994
Antoine Pitrou95f55602010-09-23 18:36:46 +0000995 with open(path, "wb") as fobj:
996 fobj.write(b"aaa")
997 tarinfo = tar.gettarinfo(path)
998 self.assertEqual(tarinfo.size, 3)
999 finally:
1000 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001001
1002 def test_directory_size(self):
1003 path = os.path.join(TEMPDIR, "directory")
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001004 os.mkdir(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001005 try:
1006 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001007 try:
1008 tarinfo = tar.gettarinfo(path)
1009 self.assertEqual(tarinfo.size, 0)
1010 finally:
1011 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001012 finally:
1013 os.rmdir(path)
1014
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001015 @unittest.skipUnless(hasattr(os, "link"),
1016 "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001017 def test_link_size(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001018 link = os.path.join(TEMPDIR, "link")
1019 target = os.path.join(TEMPDIR, "link_target")
1020 with open(target, "wb") as fobj:
1021 fobj.write(b"aaa")
1022 os.link(target, link)
1023 try:
1024 tar = tarfile.open(tmpname, self.mode)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001025 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001026 # Record the link target in the inodes list.
1027 tar.gettarinfo(target)
1028 tarinfo = tar.gettarinfo(link)
1029 self.assertEqual(tarinfo.size, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001030 finally:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001031 tar.close()
1032 finally:
1033 os.remove(target)
1034 os.remove(link)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001035
Brian Curtin3b4499c2010-12-28 14:31:47 +00001036 @support.skip_unless_symlink
Guido van Rossumd8faa362007-04-27 19:54:29 +00001037 def test_symlink_size(self):
Brian Curtind40e6f72010-07-08 21:39:08 +00001038 path = os.path.join(TEMPDIR, "symlink")
1039 os.symlink("link_target", path)
1040 try:
1041 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001042 try:
1043 tarinfo = tar.gettarinfo(path)
1044 self.assertEqual(tarinfo.size, 0)
1045 finally:
1046 tar.close()
Brian Curtind40e6f72010-07-08 21:39:08 +00001047 finally:
1048 os.remove(path)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049
1050 def test_add_self(self):
1051 # Test for #1257255.
1052 dstname = os.path.abspath(tmpname)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001053 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001054 try:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001055 self.assertEqual(tar.name, dstname,
1056 "archive name must be absolute")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001057 tar.add(dstname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001058 self.assertEqual(tar.getnames(), [],
1059 "added the archive to itself")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001060
Antoine Pitrou95f55602010-09-23 18:36:46 +00001061 cwd = os.getcwd()
1062 os.chdir(TEMPDIR)
1063 tar.add(dstname)
1064 os.chdir(cwd)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001065 self.assertEqual(tar.getnames(), [],
1066 "added the archive to itself")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001067 finally:
1068 tar.close()
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001069
Guido van Rossum486364b2007-06-30 05:01:58 +00001070 def test_exclude(self):
1071 tempdir = os.path.join(TEMPDIR, "exclude")
1072 os.mkdir(tempdir)
1073 try:
1074 for name in ("foo", "bar", "baz"):
1075 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001076 support.create_empty_file(name)
Guido van Rossum486364b2007-06-30 05:01:58 +00001077
Benjamin Peterson886af962010-03-21 23:13:07 +00001078 exclude = os.path.isfile
Guido van Rossum486364b2007-06-30 05:01:58 +00001079
1080 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001081 try:
1082 with support.check_warnings(("use the filter argument",
1083 DeprecationWarning)):
1084 tar.add(tempdir, arcname="empty_dir", exclude=exclude)
1085 finally:
1086 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001087
1088 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001089 try:
1090 self.assertEqual(len(tar.getmembers()), 1)
1091 self.assertEqual(tar.getnames()[0], "empty_dir")
1092 finally:
1093 tar.close()
Guido van Rossum486364b2007-06-30 05:01:58 +00001094 finally:
1095 shutil.rmtree(tempdir)
1096
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001097 def test_filter(self):
1098 tempdir = os.path.join(TEMPDIR, "filter")
1099 os.mkdir(tempdir)
1100 try:
1101 for name in ("foo", "bar", "baz"):
1102 name = os.path.join(tempdir, name)
Victor Stinnerbf816222011-06-30 23:25:47 +02001103 support.create_empty_file(name)
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001104
1105 def filter(tarinfo):
1106 if os.path.basename(tarinfo.name) == "bar":
1107 return
1108 tarinfo.uid = 123
1109 tarinfo.uname = "foo"
1110 return tarinfo
1111
1112 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001113 try:
1114 tar.add(tempdir, arcname="empty_dir", filter=filter)
1115 finally:
1116 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001117
Raymond Hettingera63a3122011-01-26 20:34:14 +00001118 # Verify that filter is a keyword-only argument
1119 with self.assertRaises(TypeError):
1120 tar.add(tempdir, "empty_dir", True, None, filter)
1121
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001122 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001123 try:
1124 for tarinfo in tar:
1125 self.assertEqual(tarinfo.uid, 123)
1126 self.assertEqual(tarinfo.uname, "foo")
1127 self.assertEqual(len(tar.getmembers()), 3)
1128 finally:
1129 tar.close()
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001130 finally:
1131 shutil.rmtree(tempdir)
1132
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001133 # Guarantee that stored pathnames are not modified. Don't
1134 # remove ./ or ../ or double slashes. Still make absolute
1135 # pathnames relative.
1136 # For details see bug #6054.
1137 def _test_pathname(self, path, cmp_path=None, dir=False):
1138 # Create a tarfile with an empty member named path
1139 # and compare the stored name with the original.
1140 foo = os.path.join(TEMPDIR, "foo")
1141 if not dir:
Victor Stinnerbf816222011-06-30 23:25:47 +02001142 support.create_empty_file(foo)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001143 else:
1144 os.mkdir(foo)
1145
1146 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001147 try:
1148 tar.add(foo, arcname=path)
1149 finally:
1150 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001151
1152 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001153 try:
1154 t = tar.next()
1155 finally:
1156 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001157
1158 if not dir:
1159 os.remove(foo)
1160 else:
1161 os.rmdir(foo)
1162
1163 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1164
Senthil Kumaranbe5dbeb2011-04-30 06:09:51 +08001165
1166 @support.skip_unless_symlink
Senthil Kumaran123932f2011-04-28 15:38:12 +08001167 def test_extractall_symlinks(self):
1168 # Test if extractall works properly when tarfile contains symlinks
1169 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1170 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1171 os.mkdir(tempdir)
1172 try:
1173 source_file = os.path.join(tempdir,'source')
1174 target_file = os.path.join(tempdir,'symlink')
1175 with open(source_file,'w') as f:
1176 f.write('something\n')
1177 os.symlink(source_file, target_file)
1178 tar = tarfile.open(temparchive,'w')
1179 tar.add(source_file)
1180 tar.add(target_file)
1181 tar.close()
1182 # Let's extract it to the location which contains the symlink
1183 tar = tarfile.open(temparchive,'r')
1184 # this should not raise OSError: [Errno 17] File exists
1185 try:
1186 tar.extractall(path=tempdir)
1187 except OSError:
1188 self.fail("extractall failed with symlinked files")
1189 finally:
1190 tar.close()
1191 finally:
1192 os.unlink(temparchive)
1193 shutil.rmtree(tempdir)
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001194
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001195 def test_pathnames(self):
1196 self._test_pathname("foo")
1197 self._test_pathname(os.path.join("foo", ".", "bar"))
1198 self._test_pathname(os.path.join("foo", "..", "bar"))
1199 self._test_pathname(os.path.join(".", "foo"))
1200 self._test_pathname(os.path.join(".", "foo", "."))
1201 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1202 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1203 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1204 self._test_pathname(os.path.join("..", "foo"))
1205 self._test_pathname(os.path.join("..", "foo", ".."))
1206 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1207 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1208
1209 self._test_pathname("foo" + os.sep + os.sep + "bar")
1210 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1211
1212 def test_abs_pathnames(self):
1213 if sys.platform == "win32":
1214 self._test_pathname("C:\\foo", "foo")
1215 else:
1216 self._test_pathname("/foo", "foo")
1217 self._test_pathname("///foo", "foo")
1218
1219 def test_cwd(self):
1220 # Test adding the current working directory.
1221 cwd = os.getcwd()
1222 os.chdir(TEMPDIR)
1223 try:
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001224 tar = tarfile.open(tmpname, self.mode)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001225 try:
1226 tar.add(".")
1227 finally:
1228 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001229
1230 tar = tarfile.open(tmpname, "r")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001231 try:
1232 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001233 if t.name != ".":
1234 self.assertTrue(t.name.startswith("./"), t.name)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001235 finally:
1236 tar.close()
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001237 finally:
1238 os.chdir(cwd)
1239
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001240 def test_open_nonwritable_fileobj(self):
1241 for exctype in OSError, EOFError, RuntimeError:
1242 class BadFile(io.BytesIO):
1243 first = True
1244 def write(self, data):
1245 if self.first:
1246 self.first = False
1247 raise exctype
1248
1249 f = BadFile()
1250 with self.assertRaises(exctype):
1251 tar = tarfile.open(tmpname, self.mode, fileobj=f,
1252 format=tarfile.PAX_FORMAT,
1253 pax_headers={'non': 'empty'})
1254 self.assertFalse(f.closed)
1255
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001256class GzipWriteTest(GzipTest, WriteTest):
1257 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001258
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001259class Bz2WriteTest(Bz2Test, WriteTest):
1260 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001261
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001262class LzmaWriteTest(LzmaTest, WriteTest):
1263 pass
1264
1265
1266class StreamWriteTest(WriteTestBase, unittest.TestCase):
1267
1268 prefix = "w|"
1269 decompressor = None
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001270
Guido van Rossumd8faa362007-04-27 19:54:29 +00001271 def test_stream_padding(self):
1272 # Test for bug #1543303.
1273 tar = tarfile.open(tmpname, self.mode)
1274 tar.close()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001275 if self.decompressor:
1276 dec = self.decompressor()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001277 with open(tmpname, "rb") as fobj:
1278 data = fobj.read()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001279 data = dec.decompress(data)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001280 self.assertFalse(dec.unused_data, "found trailing data")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001281 else:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001282 with self.open(tmpname) as fobj:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001283 data = fobj.read()
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001284 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1285 "incorrect zero padding")
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001286
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001287 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1288 "Missing umask implementation")
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001289 def test_file_mode(self):
1290 # Test for issue #8464: Create files with correct
1291 # permissions.
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +00001292 if os.path.exists(tmpname):
1293 os.remove(tmpname)
1294
1295 original_umask = os.umask(0o022)
1296 try:
1297 tar = tarfile.open(tmpname, self.mode)
1298 tar.close()
1299 mode = os.stat(tmpname).st_mode & 0o777
1300 self.assertEqual(mode, 0o644, "wrong file permissions")
1301 finally:
1302 os.umask(original_umask)
1303
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001304class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1305 pass
1306
1307class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1308 decompressor = bz2.BZ2Decompressor if bz2 else None
1309
1310class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1311 decompressor = lzma.LZMADecompressor if lzma else None
1312
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001313
Guido van Rossumd8faa362007-04-27 19:54:29 +00001314class GNUWriteTest(unittest.TestCase):
1315 # This testcase checks for correct creation of GNU Longname
1316 # and Longlink extended headers (cp. bug #812325).
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001317
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001318 def _length(self, s):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001319 blocks = len(s) // 512 + 1
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001320 return blocks * 512
1321
1322 def _calc_size(self, name, link=None):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001323 # Initial tar header
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001324 count = 512
1325
1326 if len(name) > tarfile.LENGTH_NAME:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001327 # GNU longname extended header + longname
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001328 count += 512
1329 count += self._length(name)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001330 if link is not None and len(link) > tarfile.LENGTH_LINK:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001331 # GNU longlink extended header + longlink
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001332 count += 512
1333 count += self._length(link)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001334 return count
1335
1336 def _test(self, name, link=None):
1337 tarinfo = tarfile.TarInfo(name)
1338 if link:
1339 tarinfo.linkname = link
1340 tarinfo.type = tarfile.LNKTYPE
1341
Guido van Rossumd8faa362007-04-27 19:54:29 +00001342 tar = tarfile.open(tmpname, "w")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001343 try:
1344 tar.format = tarfile.GNU_FORMAT
1345 tar.addfile(tarinfo)
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001346
Antoine Pitrou95f55602010-09-23 18:36:46 +00001347 v1 = self._calc_size(name, link)
1348 v2 = tar.offset
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001349 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001350 finally:
1351 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001352
Guido van Rossumd8faa362007-04-27 19:54:29 +00001353 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001354 try:
1355 member = tar.next()
1356 self.assertIsNotNone(member,
1357 "unable to read longname member")
1358 self.assertEqual(tarinfo.name, member.name,
1359 "unable to read longname member")
1360 self.assertEqual(tarinfo.linkname, member.linkname,
1361 "unable to read longname member")
1362 finally:
1363 tar.close()
Thomas Wouters89f507f2006-12-13 04:49:30 +00001364
Neal Norwitz0662f8a2004-07-20 21:54:18 +00001365 def test_longname_1023(self):
1366 self._test(("longnam/" * 127) + "longnam")
1367
1368 def test_longname_1024(self):
1369 self._test(("longnam/" * 127) + "longname")
1370
1371 def test_longname_1025(self):
1372 self._test(("longnam/" * 127) + "longname_")
1373
1374 def test_longlink_1023(self):
1375 self._test("name", ("longlnk/" * 127) + "longlnk")
1376
1377 def test_longlink_1024(self):
1378 self._test("name", ("longlnk/" * 127) + "longlink")
1379
1380 def test_longlink_1025(self):
1381 self._test("name", ("longlnk/" * 127) + "longlink_")
1382
1383 def test_longnamelink_1023(self):
1384 self._test(("longnam/" * 127) + "longnam",
1385 ("longlnk/" * 127) + "longlnk")
1386
1387 def test_longnamelink_1024(self):
1388 self._test(("longnam/" * 127) + "longname",
1389 ("longlnk/" * 127) + "longlink")
1390
1391 def test_longnamelink_1025(self):
1392 self._test(("longnam/" * 127) + "longname_",
1393 ("longlnk/" * 127) + "longlink_")
1394
Guido van Rossumd8faa362007-04-27 19:54:29 +00001395
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001396@unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001397class HardlinkTest(unittest.TestCase):
1398 # Test the creation of LNKTYPE (hardlink) members in an archive.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001399
1400 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001401 self.foo = os.path.join(TEMPDIR, "foo")
1402 self.bar = os.path.join(TEMPDIR, "bar")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001403
Antoine Pitrou95f55602010-09-23 18:36:46 +00001404 with open(self.foo, "wb") as fobj:
1405 fobj.write(b"foo")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001406
Guido van Rossumd8faa362007-04-27 19:54:29 +00001407 os.link(self.foo, self.bar)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001408
Guido van Rossumd8faa362007-04-27 19:54:29 +00001409 self.tar = tarfile.open(tmpname, "w")
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001410 self.tar.add(self.foo)
1411
Guido van Rossumd8faa362007-04-27 19:54:29 +00001412 def tearDown(self):
Hirokazu Yamamotoaf079d42008-09-21 11:50:03 +00001413 self.tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001414 support.unlink(self.foo)
1415 support.unlink(self.bar)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001416
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001417 def test_add_twice(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001418 # The same name will be added as a REGTYPE every
1419 # time regardless of st_nlink.
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001420 tarinfo = self.tar.gettarinfo(self.foo)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001421 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001422 "add file as regular failed")
1423
1424 def test_add_hardlink(self):
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001425 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001426 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001427 "add file as hardlink failed")
1428
1429 def test_dereference_hardlink(self):
1430 self.tar.dereference = True
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001431 tarinfo = self.tar.gettarinfo(self.bar)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001432 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
Neal Norwitzb0e32e22005-10-20 04:50:13 +00001433 "dereferencing hardlink failed")
1434
Neal Norwitza4f651a2004-07-20 22:07:44 +00001435
Guido van Rossumd8faa362007-04-27 19:54:29 +00001436class PaxWriteTest(GNUWriteTest):
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001437
Guido van Rossumd8faa362007-04-27 19:54:29 +00001438 def _test(self, name, link=None):
1439 # See GNUWriteTest.
1440 tarinfo = tarfile.TarInfo(name)
1441 if link:
1442 tarinfo.linkname = link
1443 tarinfo.type = tarfile.LNKTYPE
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001444
Guido van Rossumd8faa362007-04-27 19:54:29 +00001445 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001446 try:
1447 tar.addfile(tarinfo)
1448 finally:
1449 tar.close()
Andrew M. Kuchlingd4f25522004-10-20 11:47:01 +00001450
Guido van Rossumd8faa362007-04-27 19:54:29 +00001451 tar = tarfile.open(tmpname)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001452 try:
1453 if link:
1454 l = tar.getmembers()[0].linkname
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001455 self.assertEqual(link, l, "PAX longlink creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001456 else:
1457 n = tar.getmembers()[0].name
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001458 self.assertEqual(name, n, "PAX longname creation failed")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001459 finally:
1460 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001461
Guido van Rossume7ba4952007-06-06 23:52:48 +00001462 def test_pax_global_header(self):
1463 pax_headers = {
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001464 "foo": "bar",
1465 "uid": "0",
1466 "mtime": "1.23",
Guido van Rossuma0557702007-08-07 23:19:53 +00001467 "test": "\xe4\xf6\xfc",
1468 "\xe4\xf6\xfc": "test"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001469
Benjamin Peterson886af962010-03-21 23:13:07 +00001470 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001471 pax_headers=pax_headers)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001472 try:
1473 tar.addfile(tarfile.TarInfo("test"))
1474 finally:
1475 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001476
1477 # Test if the global header was written correctly.
1478 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001479 try:
1480 self.assertEqual(tar.pax_headers, pax_headers)
1481 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
1482 # Test if all the fields are strings.
1483 for key, val in tar.pax_headers.items():
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001484 self.assertIsNot(type(key), bytes)
1485 self.assertIsNot(type(val), bytes)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001486 if key in tarfile.PAX_NUMBER_FIELDS:
1487 try:
1488 tarfile.PAX_NUMBER_FIELDS[key](val)
1489 except (TypeError, ValueError):
1490 self.fail("unable to convert pax header field")
1491 finally:
1492 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001493
1494 def test_pax_extended_header(self):
1495 # The fields from the pax header have priority over the
1496 # TarInfo.
Guido van Rossum9cbfffd2007-06-07 00:54:15 +00001497 pax_headers = {"path": "foo", "uid": "123"}
Guido van Rossume7ba4952007-06-06 23:52:48 +00001498
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001499 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1500 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001501 try:
1502 t = tarfile.TarInfo()
1503 t.name = "\xe4\xf6\xfc" # non-ASCII
1504 t.uid = 8**8 # too large
1505 t.pax_headers = pax_headers
1506 tar.addfile(t)
1507 finally:
1508 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001509
1510 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001511 try:
1512 t = tar.getmembers()[0]
1513 self.assertEqual(t.pax_headers, pax_headers)
1514 self.assertEqual(t.name, "foo")
1515 self.assertEqual(t.uid, 123)
1516 finally:
1517 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001518
1519
1520class UstarUnicodeTest(unittest.TestCase):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001521
1522 format = tarfile.USTAR_FORMAT
1523
1524 def test_iso8859_1_filename(self):
1525 self._test_unicode_filename("iso8859-1")
1526
1527 def test_utf7_filename(self):
1528 self._test_unicode_filename("utf7")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001529
1530 def test_utf8_filename(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001531 self._test_unicode_filename("utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001532
Guido van Rossumd8faa362007-04-27 19:54:29 +00001533 def _test_unicode_filename(self, encoding):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001534 tar = tarfile.open(tmpname, "w", format=self.format,
1535 encoding=encoding, errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001536 try:
1537 name = "\xe4\xf6\xfc"
1538 tar.addfile(tarfile.TarInfo(name))
1539 finally:
1540 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001541
1542 tar = tarfile.open(tmpname, encoding=encoding)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001543 try:
1544 self.assertEqual(tar.getmembers()[0].name, name)
1545 finally:
1546 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001547
1548 def test_unicode_filename_error(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001549 tar = tarfile.open(tmpname, "w", format=self.format,
1550 encoding="ascii", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001551 try:
1552 tarinfo = tarfile.TarInfo()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001553
Antoine Pitrou95f55602010-09-23 18:36:46 +00001554 tarinfo.name = "\xe4\xf6\xfc"
1555 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001556
Antoine Pitrou95f55602010-09-23 18:36:46 +00001557 tarinfo.name = "foo"
1558 tarinfo.uname = "\xe4\xf6\xfc"
1559 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
1560 finally:
1561 tar.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001562
1563 def test_unicode_argument(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001564 tar = tarfile.open(tarname, "r",
1565 encoding="iso8859-1", errors="strict")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001566 try:
1567 for t in tar:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001568 self.assertIs(type(t.name), str)
1569 self.assertIs(type(t.linkname), str)
1570 self.assertIs(type(t.uname), str)
1571 self.assertIs(type(t.gname), str)
Antoine Pitrou95f55602010-09-23 18:36:46 +00001572 finally:
1573 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001574
Guido van Rossume7ba4952007-06-06 23:52:48 +00001575 def test_uname_unicode(self):
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001576 t = tarfile.TarInfo("foo")
1577 t.uname = "\xe4\xf6\xfc"
1578 t.gname = "\xe4\xf6\xfc"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001579
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001580 tar = tarfile.open(tmpname, mode="w", format=self.format,
1581 encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001582 try:
1583 tar.addfile(t)
1584 finally:
1585 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001586
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001587 tar = tarfile.open(tmpname, encoding="iso8859-1")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001588 try:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001589 t = tar.getmember("foo")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001590 self.assertEqual(t.uname, "\xe4\xf6\xfc")
1591 self.assertEqual(t.gname, "\xe4\xf6\xfc")
1592
1593 if self.format != tarfile.PAX_FORMAT:
Antoine Pitrouab58b5f2010-09-23 19:39:35 +00001594 tar.close()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001595 tar = tarfile.open(tmpname, encoding="ascii")
1596 t = tar.getmember("foo")
1597 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
1598 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
1599 finally:
1600 tar.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001601
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001602
Guido van Rossume7ba4952007-06-06 23:52:48 +00001603class GNUUnicodeTest(UstarUnicodeTest):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001604
Guido van Rossume7ba4952007-06-06 23:52:48 +00001605 format = tarfile.GNU_FORMAT
Guido van Rossumd8faa362007-04-27 19:54:29 +00001606
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001607 def test_bad_pax_header(self):
1608 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
1609 # without a hdrcharset=BINARY header.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001610 for encoding, name in (
1611 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001612 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001613 with tarfile.open(tarname, encoding=encoding,
1614 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001615 try:
1616 t = tar.getmember(name)
1617 except KeyError:
1618 self.fail("unable to read bad GNU tar pax header")
1619
Guido van Rossumd8faa362007-04-27 19:54:29 +00001620
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001621class PAXUnicodeTest(UstarUnicodeTest):
1622
1623 format = tarfile.PAX_FORMAT
1624
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001625 # PAX_FORMAT ignores encoding in write mode.
1626 test_unicode_filename_error = None
1627
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001628 def test_binary_header(self):
1629 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001630 for encoding, name in (
1631 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001632 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001633 with tarfile.open(tarname, encoding=encoding,
1634 errors="surrogateescape") as tar:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001635 try:
1636 t = tar.getmember(name)
1637 except KeyError:
1638 self.fail("unable to read POSIX.1-2008 binary header")
1639
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001640
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001641class AppendTestBase:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001642 # Test append mode (cp. patch #1652681).
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001643
Guido van Rossumd8faa362007-04-27 19:54:29 +00001644 def setUp(self):
1645 self.tarname = tmpname
1646 if os.path.exists(self.tarname):
1647 os.remove(self.tarname)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001648
Guido van Rossumd8faa362007-04-27 19:54:29 +00001649 def _create_testtar(self, mode="w:"):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001650 with tarfile.open(tarname, encoding="iso8859-1") as src:
1651 t = src.getmember("ustar/regtype")
1652 t.name = "foo"
Lars Gustäbel7a919e92012-05-05 18:15:03 +02001653 with src.extractfile(t) as f:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001654 with tarfile.open(self.tarname, mode) as tar:
1655 tar.addfile(t, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001656
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001657 def test_append_compressed(self):
1658 self._create_testtar("w:" + self.suffix)
1659 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
1660
1661class AppendTest(AppendTestBase, unittest.TestCase):
1662 test_append_compressed = None
1663
1664 def _add_testfile(self, fileobj=None):
1665 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
1666 tar.addfile(tarfile.TarInfo("bar"))
1667
Guido van Rossumd8faa362007-04-27 19:54:29 +00001668 def _test(self, names=["bar"], fileobj=None):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001669 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
1670 self.assertEqual(tar.getnames(), names)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001671
1672 def test_non_existing(self):
1673 self._add_testfile()
1674 self._test()
1675
1676 def test_empty(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001677 tarfile.open(self.tarname, "w:").close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001678 self._add_testfile()
1679 self._test()
1680
1681 def test_empty_fileobj(self):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001682 fobj = io.BytesIO(b"\0" * 1024)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001683 self._add_testfile(fobj)
1684 fobj.seek(0)
1685 self._test(fileobj=fobj)
1686
1687 def test_fileobj(self):
1688 self._create_testtar()
Antoine Pitrou95f55602010-09-23 18:36:46 +00001689 with open(self.tarname, "rb") as fobj:
1690 data = fobj.read()
Guido van Rossum34d19282007-08-09 01:03:29 +00001691 fobj = io.BytesIO(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001692 self._add_testfile(fobj)
1693 fobj.seek(0)
1694 self._test(names=["foo", "bar"], fileobj=fobj)
1695
1696 def test_existing(self):
1697 self._create_testtar()
1698 self._add_testfile()
1699 self._test(names=["foo", "bar"])
1700
Lars Gustäbel9520a432009-11-22 18:48:49 +00001701 # Append mode is supposed to fail if the tarfile to append to
1702 # does not end with a zero block.
1703 def _test_error(self, data):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001704 with open(self.tarname, "wb") as fobj:
1705 fobj.write(data)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001706 self.assertRaises(tarfile.ReadError, self._add_testfile)
1707
1708 def test_null(self):
1709 self._test_error(b"")
1710
1711 def test_incomplete(self):
1712 self._test_error(b"\0" * 13)
1713
1714 def test_premature_eof(self):
1715 data = tarfile.TarInfo("foo").tobuf()
1716 self._test_error(data)
1717
1718 def test_trailing_garbage(self):
1719 data = tarfile.TarInfo("foo").tobuf()
1720 self._test_error(data + b"\0" * 13)
1721
1722 def test_invalid(self):
1723 self._test_error(b"a" * 512)
1724
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001725class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
1726 pass
1727
1728class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
1729 pass
1730
1731class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
1732 pass
1733
Guido van Rossumd8faa362007-04-27 19:54:29 +00001734
1735class LimitsTest(unittest.TestCase):
1736
1737 def test_ustar_limits(self):
1738 # 100 char name
1739 tarinfo = tarfile.TarInfo("0123456789" * 10)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001740 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001741
1742 # 101 char name that cannot be stored
1743 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001744 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001745
1746 # 256 char name with a slash at pos 156
1747 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001748 tarinfo.tobuf(tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001749
1750 # 256 char name that cannot be stored
1751 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001752 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001753
1754 # 512 char name
1755 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001756 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001757
1758 # 512 char linkname
1759 tarinfo = tarfile.TarInfo("longlink")
1760 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001761 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001762
1763 # uid > 8 digits
1764 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001765 tarinfo.uid = 0o10000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001766 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001767
1768 def test_gnu_limits(self):
1769 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001770 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001771
1772 tarinfo = tarfile.TarInfo("longlink")
1773 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001774 tarinfo.tobuf(tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001775
1776 # uid >= 256 ** 7
1777 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001778 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001779 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001780
1781 def test_pax_limits(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001782 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
Guido van Rossume7ba4952007-06-06 23:52:48 +00001783 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001784
1785 tarinfo = tarfile.TarInfo("longlink")
1786 tarinfo.linkname = "123/" * 126 + "longname"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001787 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001788
1789 tarinfo = tarfile.TarInfo("name")
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001790 tarinfo.uid = 0o4000000000000000000
Guido van Rossume7ba4952007-06-06 23:52:48 +00001791 tarinfo.tobuf(tarfile.PAX_FORMAT)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001792
1793
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001794class MiscTest(unittest.TestCase):
1795
1796 def test_char_fields(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001797 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
1798 b"foo\0\0\0\0\0")
1799 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
1800 b"foo")
1801 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
1802 "foo")
1803 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
1804 "foo")
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001805
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001806 def test_read_number_fields(self):
1807 # Issue 13158: Test if GNU tar specific base-256 number fields
1808 # are decoded correctly.
1809 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
1810 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001811 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
1812 0o10000000)
1813 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
1814 0xffffffff)
1815 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
1816 -1)
1817 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
1818 -100)
1819 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
1820 -0x100000000000000)
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001821
1822 def test_write_number_fields(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001823 self.assertEqual(tarfile.itn(1), b"0000001\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001824 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001825 self.assertEqual(tarfile.itn(0o10000000),
1826 b"\x80\x00\x00\x00\x00\x20\x00\x00")
1827 self.assertEqual(tarfile.itn(0xffffffff),
1828 b"\x80\x00\x00\x00\xff\xff\xff\xff")
1829 self.assertEqual(tarfile.itn(-1),
1830 b"\xff\xff\xff\xff\xff\xff\xff\xff")
1831 self.assertEqual(tarfile.itn(-100),
1832 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
1833 self.assertEqual(tarfile.itn(-0x100000000000000),
1834 b"\xff\x00\x00\x00\x00\x00\x00\x00")
Lars Gustäbelac3d1372011-10-14 12:46:40 +02001835
1836 def test_number_field_limits(self):
Serhiy Storchaka8b562922013-06-17 15:38:50 +03001837 with self.assertRaises(ValueError):
1838 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
1839 with self.assertRaises(ValueError):
1840 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
1841 with self.assertRaises(ValueError):
1842 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
1843 with self.assertRaises(ValueError):
1844 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001845
1846
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001847class CommandLineTest(unittest.TestCase):
1848
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001849 def tarfilecmd(self, *args, **kwargs):
1850 rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
1851 **kwargs)
Antoine Pitrou3b7b1e52013-11-24 01:55:05 +01001852 return out.replace(os.linesep.encode(), b'\n')
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001853
1854 def tarfilecmd_failure(self, *args):
1855 return script_helper.assert_python_failure('-m', 'tarfile', *args)
1856
1857 def make_simple_tarfile(self, tar_name):
1858 files = [support.findfile('tokenize_tests.txt'),
1859 support.findfile('tokenize_tests-no-coding-cookie-'
1860 'and-utf8-bom-sig-only.txt')]
1861 self.addCleanup(support.unlink, tar_name)
1862 with tarfile.open(tar_name, 'w') as tf:
1863 for tardata in files:
1864 tf.add(tardata, arcname=os.path.basename(tardata))
1865
1866 def test_test_command(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001867 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001868 for opt in '-t', '--test':
1869 out = self.tarfilecmd(opt, tar_name)
1870 self.assertEqual(out, b'')
1871
1872 def test_test_command_verbose(self):
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001873 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001874 for opt in '-v', '--verbose':
1875 out = self.tarfilecmd(opt, '-t', tar_name)
1876 self.assertIn(b'is a tar archive.\n', out)
1877
1878 def test_test_command_invalid_file(self):
1879 zipname = support.findfile('zipdir.zip')
1880 rc, out, err = self.tarfilecmd_failure('-t', zipname)
1881 self.assertIn(b' is not a tar archive.', err)
1882 self.assertEqual(out, b'')
1883 self.assertEqual(rc, 1)
1884
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02001885 for tar_name in testtarnames:
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001886 with self.subTest(tar_name=tar_name):
1887 with open(tar_name, 'rb') as f:
1888 data = f.read()
1889 try:
1890 with open(tmpname, 'wb') as f:
1891 f.write(data[:511])
1892 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
1893 self.assertEqual(out, b'')
1894 self.assertEqual(rc, 1)
1895 finally:
1896 support.unlink(tmpname)
1897
1898 def test_list_command(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001899 for tar_name in testtarnames:
1900 with support.captured_stdout() as t:
1901 with tarfile.open(tar_name, 'r') as tf:
1902 tf.list(verbose=False)
1903 expected = t.getvalue().encode('ascii', 'backslashreplace')
1904 for opt in '-l', '--list':
1905 out = self.tarfilecmd(opt, tar_name,
1906 PYTHONIOENCODING='ascii')
1907 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001908
1909 def test_list_command_verbose(self):
Serhiy Storchaka255493c2014-02-05 20:54:43 +02001910 for tar_name in testtarnames:
1911 with support.captured_stdout() as t:
1912 with tarfile.open(tar_name, 'r') as tf:
1913 tf.list(verbose=True)
1914 expected = t.getvalue().encode('ascii', 'backslashreplace')
1915 for opt in '-v', '--verbose':
1916 out = self.tarfilecmd(opt, '-l', tar_name,
1917 PYTHONIOENCODING='ascii')
1918 self.assertEqual(out, expected)
Serhiy Storchakad27b4552013-11-24 01:53:29 +02001919
1920 def test_list_command_invalid_file(self):
1921 zipname = support.findfile('zipdir.zip')
1922 rc, out, err = self.tarfilecmd_failure('-l', zipname)
1923 self.assertIn(b' is not a tar archive.', err)
1924 self.assertEqual(out, b'')
1925 self.assertEqual(rc, 1)
1926
1927 def test_create_command(self):
1928 files = [support.findfile('tokenize_tests.txt'),
1929 support.findfile('tokenize_tests-no-coding-cookie-'
1930 'and-utf8-bom-sig-only.txt')]
1931 for opt in '-c', '--create':
1932 try:
1933 out = self.tarfilecmd(opt, tmpname, *files)
1934 self.assertEqual(out, b'')
1935 with tarfile.open(tmpname) as tar:
1936 tar.getmembers()
1937 finally:
1938 support.unlink(tmpname)
1939
1940 def test_create_command_verbose(self):
1941 files = [support.findfile('tokenize_tests.txt'),
1942 support.findfile('tokenize_tests-no-coding-cookie-'
1943 'and-utf8-bom-sig-only.txt')]
1944 for opt in '-v', '--verbose':
1945 try:
1946 out = self.tarfilecmd(opt, '-c', tmpname, *files)
1947 self.assertIn(b' file created.', out)
1948 with tarfile.open(tmpname) as tar:
1949 tar.getmembers()
1950 finally:
1951 support.unlink(tmpname)
1952
1953 def test_create_command_dotless_filename(self):
1954 files = [support.findfile('tokenize_tests.txt')]
1955 try:
1956 out = self.tarfilecmd('-c', dotlessname, *files)
1957 self.assertEqual(out, b'')
1958 with tarfile.open(dotlessname) as tar:
1959 tar.getmembers()
1960 finally:
1961 support.unlink(dotlessname)
1962
1963 def test_create_command_dot_started_filename(self):
1964 tar_name = os.path.join(TEMPDIR, ".testtar")
1965 files = [support.findfile('tokenize_tests.txt')]
1966 try:
1967 out = self.tarfilecmd('-c', tar_name, *files)
1968 self.assertEqual(out, b'')
1969 with tarfile.open(tar_name) as tar:
1970 tar.getmembers()
1971 finally:
1972 support.unlink(tar_name)
1973
1974 def test_extract_command(self):
1975 self.make_simple_tarfile(tmpname)
1976 for opt in '-e', '--extract':
1977 try:
1978 with support.temp_cwd(tarextdir):
1979 out = self.tarfilecmd(opt, tmpname)
1980 self.assertEqual(out, b'')
1981 finally:
1982 support.rmtree(tarextdir)
1983
1984 def test_extract_command_verbose(self):
1985 self.make_simple_tarfile(tmpname)
1986 for opt in '-v', '--verbose':
1987 try:
1988 with support.temp_cwd(tarextdir):
1989 out = self.tarfilecmd(opt, '-e', tmpname)
1990 self.assertIn(b' file is extracted.', out)
1991 finally:
1992 support.rmtree(tarextdir)
1993
1994 def test_extract_command_different_directory(self):
1995 self.make_simple_tarfile(tmpname)
1996 try:
1997 with support.temp_cwd(tarextdir):
1998 out = self.tarfilecmd('-e', tmpname, 'spamdir')
1999 self.assertEqual(out, b'')
2000 finally:
2001 support.rmtree(tarextdir)
2002
2003 def test_extract_command_invalid_file(self):
2004 zipname = support.findfile('zipdir.zip')
2005 with support.temp_cwd(tarextdir):
2006 rc, out, err = self.tarfilecmd_failure('-e', zipname)
2007 self.assertIn(b' is not a tar archive.', err)
2008 self.assertEqual(out, b'')
2009 self.assertEqual(rc, 1)
2010
2011
Lars Gustäbel01385812010-03-03 12:08:54 +00002012class ContextManagerTest(unittest.TestCase):
2013
2014 def test_basic(self):
2015 with tarfile.open(tarname) as tar:
2016 self.assertFalse(tar.closed, "closed inside runtime context")
2017 self.assertTrue(tar.closed, "context manager failed")
2018
2019 def test_closed(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002020 # The __enter__() method is supposed to raise OSError
Lars Gustäbel01385812010-03-03 12:08:54 +00002021 # if the TarFile object is already closed.
2022 tar = tarfile.open(tarname)
2023 tar.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002024 with self.assertRaises(OSError):
Lars Gustäbel01385812010-03-03 12:08:54 +00002025 with tar:
2026 pass
2027
2028 def test_exception(self):
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002029 # Test if the OSError exception is passed through properly.
Lars Gustäbel01385812010-03-03 12:08:54 +00002030 with self.assertRaises(Exception) as exc:
2031 with tarfile.open(tarname) as tar:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002032 raise OSError
2033 self.assertIsInstance(exc.exception, OSError,
Lars Gustäbel01385812010-03-03 12:08:54 +00002034 "wrong exception raised in context manager")
2035 self.assertTrue(tar.closed, "context manager failed")
2036
2037 def test_no_eof(self):
2038 # __exit__() must not write end-of-archive blocks if an
2039 # exception was raised.
2040 try:
2041 with tarfile.open(tmpname, "w") as tar:
2042 raise Exception
2043 except:
2044 pass
2045 self.assertEqual(os.path.getsize(tmpname), 0,
2046 "context manager wrote an end-of-archive block")
2047 self.assertTrue(tar.closed, "context manager failed")
2048
2049 def test_eof(self):
2050 # __exit__() must write end-of-archive blocks, i.e. call
2051 # TarFile.close() if there was no error.
2052 with tarfile.open(tmpname, "w"):
2053 pass
2054 self.assertNotEqual(os.path.getsize(tmpname), 0,
2055 "context manager wrote no end-of-archive block")
2056
2057 def test_fileobj(self):
2058 # Test that __exit__() did not close the external file
2059 # object.
Antoine Pitrou95f55602010-09-23 18:36:46 +00002060 with open(tmpname, "wb") as fobj:
2061 try:
2062 with tarfile.open(fileobj=fobj, mode="w") as tar:
2063 raise Exception
2064 except:
2065 pass
2066 self.assertFalse(fobj.closed, "external file object was closed")
2067 self.assertTrue(tar.closed, "context manager failed")
Lars Gustäbel01385812010-03-03 12:08:54 +00002068
2069
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002070@unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
2071class LinkEmulationTest(ReadTest, unittest.TestCase):
Lars Gustäbel1b512722010-06-03 12:45:16 +00002072
2073 # Test for issue #8741 regression. On platforms that do not support
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002074 # symbolic or hard links tarfile tries to extract these types of members
2075 # as the regular files they point to.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002076 def _test_link_extraction(self, name):
2077 self.tar.extract(name, TEMPDIR)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002078 with open(os.path.join(TEMPDIR, name), "rb") as f:
2079 data = f.read()
Lars Gustäbel1b512722010-06-03 12:45:16 +00002080 self.assertEqual(md5sum(data), md5_regtype)
2081
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002082 # See issues #1578269, #8879, and #17689 for some history on these skips
Brian Curtind40e6f72010-07-08 21:39:08 +00002083 @unittest.skipIf(hasattr(os.path, "islink"),
2084 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002085 def test_hardlink_extraction1(self):
2086 self._test_link_extraction("ustar/lnktype")
2087
Brian Curtind40e6f72010-07-08 21:39:08 +00002088 @unittest.skipIf(hasattr(os.path, "islink"),
2089 "Skip emulation - has os.path.islink but not os.link")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002090 def test_hardlink_extraction2(self):
2091 self._test_link_extraction("./ustar/linktest2/lnktype")
2092
Brian Curtin74e45612010-07-09 15:58:59 +00002093 @unittest.skipIf(hasattr(os, "symlink"),
2094 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002095 def test_symlink_extraction1(self):
2096 self._test_link_extraction("ustar/symtype")
2097
Brian Curtin74e45612010-07-09 15:58:59 +00002098 @unittest.skipIf(hasattr(os, "symlink"),
2099 "Skip emulation if symlink exists")
Lars Gustäbel1b512722010-06-03 12:45:16 +00002100 def test_symlink_extraction2(self):
2101 self._test_link_extraction("./ustar/linktest2/symtype")
2102
2103
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002104class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
Lars Gustäbel42e00912009-03-22 20:34:29 +00002105 # Issue5068: The _BZ2Proxy.read() method loops forever
2106 # on an empty or partial bzipped file.
2107
2108 def _test_partial_input(self, mode):
2109 class MyBytesIO(io.BytesIO):
2110 hit_eof = False
2111 def read(self, n):
2112 if self.hit_eof:
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002113 raise AssertionError("infinite loop detected in "
2114 "tarfile.open()")
Lars Gustäbel42e00912009-03-22 20:34:29 +00002115 self.hit_eof = self.tell() == len(self.getvalue())
2116 return super(MyBytesIO, self).read(n)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002117 def seek(self, *args):
2118 self.hit_eof = False
2119 return super(MyBytesIO, self).seek(*args)
Lars Gustäbel42e00912009-03-22 20:34:29 +00002120
2121 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
2122 for x in range(len(data) + 1):
Lars Gustäbel9520a432009-11-22 18:48:49 +00002123 try:
2124 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
2125 except tarfile.ReadError:
2126 pass # we have no interest in ReadErrors
Lars Gustäbel42e00912009-03-22 20:34:29 +00002127
2128 def test_partial_input(self):
2129 self._test_partial_input("r")
2130
2131 def test_partial_input_bz2(self):
2132 self._test_partial_input("r:bz2")
2133
2134
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002135def setUpModule():
Antoine Pitrou95f55602010-09-23 18:36:46 +00002136 support.unlink(TEMPDIR)
Antoine Pitrou941ee882009-11-11 20:59:38 +00002137 os.makedirs(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002138
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002139 global testtarnames
2140 testtarnames = [tarname]
Antoine Pitrou95f55602010-09-23 18:36:46 +00002141 with open(tarname, "rb") as fobj:
2142 data = fobj.read()
Neal Norwitza4f651a2004-07-20 22:07:44 +00002143
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002144 # Create compressed tarfiles.
2145 for c in GzipTest, Bz2Test, LzmaTest:
2146 if c.open:
2147 support.unlink(c.tarname)
Serhiy Storchaka5e8c8092013-11-24 02:30:59 +02002148 testtarnames.append(c.tarname)
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002149 with c.open(c.tarname, "wb") as tar:
2150 tar.write(data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002151
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002152def tearDownModule():
2153 if os.path.exists(TEMPDIR):
2154 shutil.rmtree(TEMPDIR)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002155
Neal Norwitz996acf12003-02-17 14:51:41 +00002156if __name__ == "__main__":
Serhiy Storchaka8b562922013-06-17 15:38:50 +03002157 unittest.main()